text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Flutter code sample for [MenuAnchor].
void main() => runApp(const MenuApp());
/// An enhanced enum to define the available menus and their shortcuts.
///
/// Using an enum for menu definition is not required, but this illustrates how
/// they could be used for simple menu systems.
enum MenuEntry {
about('About'),
showMessage('Show Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)),
hideMessage('Hide Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)),
colorMenu('Color Menu'),
colorRed('Red Background', SingleActivator(LogicalKeyboardKey.keyR, control: true)),
colorGreen('Green Background', SingleActivator(LogicalKeyboardKey.keyG, control: true)),
colorBlue('Blue Background', SingleActivator(LogicalKeyboardKey.keyB, control: true));
const MenuEntry(this.label, [this.shortcut]);
final String label;
final MenuSerializableShortcut? shortcut;
}
class MyCascadingMenu extends StatefulWidget {
const MyCascadingMenu({super.key, required this.message});
final String message;
@override
State<MyCascadingMenu> createState() => _MyCascadingMenuState();
}
class _MyCascadingMenuState extends State<MyCascadingMenu> {
MenuEntry? _lastSelection;
final FocusNode _buttonFocusNode = FocusNode(debugLabel: 'Menu Button');
ShortcutRegistryEntry? _shortcutsEntry;
Color get backgroundColor => _backgroundColor;
Color _backgroundColor = Colors.red;
set backgroundColor(Color value) {
if (_backgroundColor != value) {
setState(() {
_backgroundColor = value;
});
}
}
bool get showingMessage => _showingMessage;
bool _showingMessage = false;
set showingMessage(bool value) {
if (_showingMessage != value) {
setState(() {
_showingMessage = value;
});
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Dispose of any previously registered shortcuts, since they are about to
// be replaced.
_shortcutsEntry?.dispose();
// Collect the shortcuts from the different menu selections so that they can
// be registered to apply to the entire app. Menus don't register their
// shortcuts, they only display the shortcut hint text.
final Map<ShortcutActivator, Intent> shortcuts = <ShortcutActivator, Intent>{
for (final MenuEntry item in MenuEntry.values)
if (item.shortcut != null) item.shortcut!: VoidCallbackIntent(() => _activate(item)),
};
// Register the shortcuts with the ShortcutRegistry so that they are
// available to the entire application.
_shortcutsEntry = ShortcutRegistry.of(context).addAll(shortcuts);
}
@override
void dispose() {
_shortcutsEntry?.dispose();
_buttonFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
MenuAnchor(
childFocusNode: _buttonFocusNode,
menuChildren: <Widget>[
MenuItemButton(
child: Text(MenuEntry.about.label),
onPressed: () => _activate(MenuEntry.about),
),
if (_showingMessage)
MenuItemButton(
onPressed: () => _activate(MenuEntry.hideMessage),
shortcut: MenuEntry.hideMessage.shortcut,
child: Text(MenuEntry.hideMessage.label),
),
if (!_showingMessage)
MenuItemButton(
onPressed: () => _activate(MenuEntry.showMessage),
shortcut: MenuEntry.showMessage.shortcut,
child: Text(MenuEntry.showMessage.label),
),
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
onPressed: () => _activate(MenuEntry.colorRed),
shortcut: MenuEntry.colorRed.shortcut,
child: Text(MenuEntry.colorRed.label),
),
MenuItemButton(
onPressed: () => _activate(MenuEntry.colorGreen),
shortcut: MenuEntry.colorGreen.shortcut,
child: Text(MenuEntry.colorGreen.label),
),
MenuItemButton(
onPressed: () => _activate(MenuEntry.colorBlue),
shortcut: MenuEntry.colorBlue.shortcut,
child: Text(MenuEntry.colorBlue.label),
),
],
child: const Text('Background Color'),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return TextButton(
focusNode: _buttonFocusNode,
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
child: const Text('OPEN MENU'),
);
},
),
Expanded(
child: Container(
alignment: Alignment.center,
color: backgroundColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
showingMessage ? widget.message : '',
style: Theme.of(context).textTheme.headlineSmall,
),
),
Text(_lastSelection != null ? 'Last Selected: ${_lastSelection!.label}' : ''),
],
),
),
),
],
);
}
void _activate(MenuEntry selection) {
setState(() {
_lastSelection = selection;
});
switch (selection) {
case MenuEntry.about:
showAboutDialog(
context: context,
applicationName: 'MenuBar Sample',
applicationVersion: '1.0.0',
);
case MenuEntry.hideMessage:
case MenuEntry.showMessage:
showingMessage = !showingMessage;
case MenuEntry.colorMenu:
break;
case MenuEntry.colorRed:
backgroundColor = Colors.red;
case MenuEntry.colorGreen:
backgroundColor = Colors.green;
case MenuEntry.colorBlue:
backgroundColor = Colors.blue;
}
}
}
class MenuApp extends StatelessWidget {
const MenuApp({super.key});
static const String kMessage = '"Talk less. Smile more." - A. Burr';
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const Scaffold(body: SafeArea(child: MyCascadingMenu(message: kMessage))),
);
}
}
| flutter/examples/api/lib/material/menu_anchor/menu_anchor.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/menu_anchor/menu_anchor.0.dart",
"repo_id": "flutter",
"token_count": 2939
} | 569 |
// 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';
/// Flutter code sample for [PaginatedDataTable].
class MyDataSource extends DataTableSource {
static const List<int> _displayIndexToRawIndex = <int>[ 0, 3, 4, 5, 6 ];
late List<List<Comparable<Object>>> sortedData;
void setData(List<List<Comparable<Object>>> rawData, int sortColumn, bool sortAscending) {
sortedData = rawData.toList()..sort((List<Comparable<Object>> a, List<Comparable<Object>> b) {
final Comparable<Object> cellA = a[_displayIndexToRawIndex[sortColumn]];
final Comparable<Object> cellB = b[_displayIndexToRawIndex[sortColumn]];
return cellA.compareTo(cellB) * (sortAscending ? 1 : -1);
});
notifyListeners();
}
@override
int get rowCount => sortedData.length;
static DataCell cellFor(Object data) {
String value;
if (data is DateTime) {
value = '${data.year}-${data.month.toString().padLeft(2, '0')}-${data.day.toString().padLeft(2, '0')}';
} else {
value = data.toString();
}
return DataCell(Text(value));
}
@override
DataRow? getRow(int index) {
return DataRow.byIndex(
index: sortedData[index][0] as int,
cells: <DataCell>[
cellFor('S${sortedData[index][1]}E${sortedData[index][2].toString().padLeft(2, '0')}'),
cellFor(sortedData[index][3]),
cellFor(sortedData[index][4]),
cellFor(sortedData[index][5]),
cellFor(sortedData[index][6]),
],
);
}
@override
bool get isRowCountApproximate => false;
@override
int get selectedRowCount => 0;
}
void main() => runApp(const DataTableExampleApp());
class DataTableExampleApp extends StatelessWidget {
const DataTableExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: SingleChildScrollView(
padding: EdgeInsets.all(12.0),
child: DataTableExample(),
),
);
}
}
class DataTableExample extends StatefulWidget {
const DataTableExample({super.key});
@override
State<DataTableExample> createState() => _DataTableExampleState();
}
class _DataTableExampleState extends State<DataTableExample> {
final MyDataSource dataSource = MyDataSource()
..setData(episodes, 0, true);
int _columnIndex = 0;
bool _columnAscending = true;
void _sort(int columnIndex, bool ascending) {
setState(() {
_columnIndex = columnIndex;
_columnAscending = ascending;
dataSource.setData(episodes, _columnIndex, _columnAscending);
});
}
@override
Widget build(BuildContext context) {
return PaginatedDataTable(
sortColumnIndex: _columnIndex,
sortAscending: _columnAscending,
columns: <DataColumn>[
DataColumn(
label: const Text('Episode'),
onSort: _sort,
),
DataColumn(
label: const Text('Title'),
onSort: _sort,
),
DataColumn(
label: const Text('Director'),
onSort: _sort,
),
DataColumn(
label: const Text('Writer(s)'),
onSort: _sort,
),
DataColumn(
label: const Text('Air Date'),
onSort: _sort,
),
],
source: dataSource,
);
}
}
final List<List<Comparable<Object>>> episodes = <List<Comparable<Object>>>[
<Comparable<Object>>[
1,
1,
1,
'Strange New Worlds',
'Akiva Goldsman',
'Akiva Goldsman, Alex Kurtzman, Jenny Lumet',
DateTime(2022, 5, 5),
],
<Comparable<Object>>[
2,
1,
2,
'Children of the Comet',
'Maja Vrvilo',
'Henry Alonso Myers, Sarah Tarkoff',
DateTime(2022, 5, 12),
],
<Comparable<Object>>[
3,
1,
3,
'Ghosts of Illyria',
'Leslie Hope',
'Akela Cooper, Bill Wolkoff',
DateTime(2022, 5, 19),
],
<Comparable<Object>>[
4,
1,
4,
'Memento Mori',
'Dan Liu',
'Davy Perez, Beau DeMayo',
DateTime(2022, 5, 26),
],
<Comparable<Object>>[
5,
1,
5,
'Spock Amok',
'Rachel Leiterman',
'Henry Alonso Myers, Robin Wasserman',
DateTime(2022, 6, 2),
],
<Comparable<Object>>[
6,
1,
6,
'Lift Us Where Suffering Cannot Reach',
'Andi Armaganian',
'Robin Wasserman, Bill Wolkoff',
DateTime(2022, 6, 9),
],
<Comparable<Object>>[
7,
1,
7,
'The Serene Squall',
'Sydney Freeland',
'Beau DeMayo, Sarah Tarkoff',
DateTime(2022, 6, 16),
],
<Comparable<Object>>[
8,
1,
8,
'The Elysian Kingdom',
'Amanda Row',
'Akela Cooper, Onitra Johnson',
DateTime(2022, 6, 23),
],
<Comparable<Object>>[
9,
1,
9,
'All Those Who Wander',
'Christopher J. Byrne',
'Davy Perez',
DateTime(2022, 6, 30),
],
<Comparable<Object>>[
10,
2,
10,
'A Quality of Mercy',
'Chris Fisher',
'Henry Alonso Myers, Akiva Goldsman',
DateTime(2022, 7, 7),
],
<Comparable<Object>>[
11,
2,
1,
'The Broken Circle',
'Chris Fisher',
'Henry Alonso Myers, Akiva Goldsman',
DateTime(2023, 6, 15),
],
<Comparable<Object>>[
12,
2,
2,
'Ad Astra per Aspera',
'Valerie Weiss',
'Dana Horgan',
DateTime(2023, 6, 22),
],
<Comparable<Object>>[
13,
2,
3,
'Tomorrow and Tomorrow and Tomorrow',
'Amanda Row',
'David Reed',
DateTime(2023, 6, 29),
],
<Comparable<Object>>[
14,
2,
4,
'Among the Lotus Eaters',
'Eduardo Sánchez',
'Kirsten Beyer, Davy Perez',
DateTime(2023, 7, 6),
],
<Comparable<Object>>[
15,
2,
5,
'Charades',
'Jordan Canning',
'Kathryn Lyn, Henry Alonso Myers',
DateTime(2023, 7, 13),
],
<Comparable<Object>>[
16,
2,
6,
'Lost in Translation',
'Dan Liu',
'Onitra Johnson, David Reed',
DateTime(2023, 7, 20),
],
<Comparable<Object>>[
17,
2,
7,
'Those Old Scientists',
'Jonathan Frakes',
'Kathryn Lyn, Bill Wolkoff',
DateTime(2023, 7, 22),
],
<Comparable<Object>>[
18,
2,
8,
'Under the Cloak of War',
'',
'Davy Perez',
DateTime(2023, 7, 27),
],
<Comparable<Object>>[
19,
2,
9,
'Subspace Rhapsody',
'',
'Dana Horgan, Bill Wolkoff',
DateTime(2023, 8, 3),
],
<Comparable<Object>>[
20,
2,
10,
'Hegemony',
'',
'Henry Alonso Myers',
DateTime(2023, 8, 10),
],
];
| flutter/examples/api/lib/material/paginated_data_table/paginated_data_table.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/paginated_data_table/paginated_data_table.1.dart",
"repo_id": "flutter",
"token_count": 2902
} | 570 |
// 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';
/// Flutter code sample for [RangeSlider].
void main() => runApp(const RangeSliderExampleApp());
class RangeSliderExampleApp extends StatelessWidget {
const RangeSliderExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('RangeSlider Sample')),
body: const RangeSliderExample(),
),
);
}
}
class RangeSliderExample extends StatefulWidget {
const RangeSliderExample({super.key});
@override
State<RangeSliderExample> createState() => _RangeSliderExampleState();
}
class _RangeSliderExampleState extends State<RangeSliderExample> {
RangeValues _currentRangeValues = const RangeValues(40, 80);
@override
Widget build(BuildContext context) {
return RangeSlider(
values: _currentRangeValues,
max: 100,
divisions: 5,
labels: RangeLabels(
_currentRangeValues.start.round().toString(),
_currentRangeValues.end.round().toString(),
),
onChanged: (RangeValues values) {
setState(() {
_currentRangeValues = values;
});
},
);
}
}
| flutter/examples/api/lib/material/range_slider/range_slider.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/range_slider/range_slider.0.dart",
"repo_id": "flutter",
"token_count": 478
} | 571 |
// 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';
/// Flutter code sample for [ScaffoldMessenger.of].
void main() => runApp(const OfExampleApp());
class OfExampleApp extends StatelessWidget {
const OfExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ScaffoldMessenger.of Sample')),
body: const Center(
child: OfExample(),
),
),
);
}
}
class OfExample extends StatelessWidget {
const OfExample({super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton(
child: const Text('SHOW A SNACKBAR'),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Have a snack!'),
),
);
},
);
}
}
| flutter/examples/api/lib/material/scaffold/scaffold_messenger.of.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/scaffold/scaffold_messenger.of.0.dart",
"repo_id": "flutter",
"token_count": 399
} | 572 |
// 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';
/// Flutter code sample for [SegmentedButton.styleFrom].
void main() {
runApp(const SegmentedButtonApp());
}
class SegmentedButtonApp extends StatelessWidget {
const SegmentedButtonApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: SegmentedButtonExample(),
),
),
);
}
}
class SegmentedButtonExample extends StatefulWidget {
const SegmentedButtonExample({super.key});
@override
State<SegmentedButtonExample> createState() => _SegmentedButtonExampleState();
}
enum Calendar { day, week, month, year }
class _SegmentedButtonExampleState extends State<SegmentedButtonExample> {
Calendar calendarView = Calendar.week;
@override
Widget build(BuildContext context) {
return SegmentedButton<Calendar>(
style: SegmentedButton.styleFrom(
backgroundColor: Colors.grey[200],
foregroundColor: Colors.red,
selectedForegroundColor: Colors.white,
selectedBackgroundColor: Colors.green,
),
segments: const <ButtonSegment<Calendar>>[
ButtonSegment<Calendar>(value: Calendar.day, label: Text('Day'), icon: Icon(Icons.calendar_view_day)),
ButtonSegment<Calendar>(value: Calendar.week, label: Text('Week'), icon: Icon(Icons.calendar_view_week)),
ButtonSegment<Calendar>(value: Calendar.month, label: Text('Month'), icon: Icon(Icons.calendar_view_month)),
ButtonSegment<Calendar>(value: Calendar.year, label: Text('Year'), icon: Icon(Icons.calendar_today)),
],
selected: <Calendar>{calendarView},
onSelectionChanged: (Set<Calendar> newSelection) {
setState(() {
// By default there is only a single segment that can be
// selected at one time, so its value is always the first
// item in the selected set.
calendarView = newSelection.first;
});
},
);
}
}
| flutter/examples/api/lib/material/segmented_button/segmented_button.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/segmented_button/segmented_button.1.dart",
"repo_id": "flutter",
"token_count": 768
} | 573 |
// 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';
/// Flutter code sample for [Switch].
void main() => runApp(const SwitchApp());
class SwitchApp extends StatelessWidget {
const SwitchApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
appBar: AppBar(title: const Text('Switch Sample')),
body: const Center(
child: SwitchExample(),
),
),
);
}
}
class SwitchExample extends StatefulWidget {
const SwitchExample({super.key});
@override
State<SwitchExample> createState() => _SwitchExampleState();
}
class _SwitchExampleState extends State<SwitchExample> {
bool light0 = true;
bool light1 = true;
final MaterialStateProperty<Icon?> thumbIcon = MaterialStateProperty.resolveWith<Icon?>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return const Icon(Icons.check);
}
return const Icon(Icons.close);
},
);
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch(
value: light0,
onChanged: (bool value) {
setState(() {
light0 = value;
});
},
),
Switch(
thumbIcon: thumbIcon,
value: light1,
onChanged: (bool value) {
setState(() {
light1 = value;
});
},
),
],
);
}
}
| flutter/examples/api/lib/material/switch/switch.2.dart/0 | {
"file_path": "flutter/examples/api/lib/material/switch/switch.2.dart",
"repo_id": "flutter",
"token_count": 716
} | 574 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Flutter code sample for [TextFormField].
void main() => runApp(const TextFormFieldExampleApp());
class TextFormFieldExampleApp extends StatelessWidget {
const TextFormFieldExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: TextFormFieldExample(),
);
}
}
class TextFormFieldExample extends StatefulWidget {
const TextFormFieldExample({super.key});
@override
State<TextFormFieldExample> createState() => _TextFormFieldExampleState();
}
class _TextFormFieldExampleState extends State<TextFormFieldExample> {
@override
Widget build(BuildContext context) {
return Material(
child: Center(
child: Shortcuts(
shortcuts: const <ShortcutActivator, Intent>{
// Pressing space in the field will now move to the next field.
SingleActivator(LogicalKeyboardKey.space): NextFocusIntent(),
},
child: FocusTraversalGroup(
child: Form(
autovalidateMode: AutovalidateMode.always,
onChanged: () {
Form.of(primaryFocus!.context!).save();
},
child: Wrap(
children: List<Widget>.generate(5, (int index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ConstrainedBox(
constraints: BoxConstraints.tight(const Size(200, 50)),
child: TextFormField(
onSaved: (String? value) {
debugPrint('Value for field $index saved as "$value"');
},
),
),
);
}),
),
),
),
),
),
);
}
}
| flutter/examples/api/lib/material/text_form_field/text_form_field.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/text_form_field/text_form_field.1.dart",
"repo_id": "flutter",
"token_count": 939
} | 575 |
// 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';
void main() => runApp(const SampleApp());
class SampleApp extends StatefulWidget {
const SampleApp({super.key});
@override
State<SampleApp> createState() => _SampleAppState();
}
class _SampleAppState extends State<SampleApp> {
// This can be toggled using buttons in the UI to change which layout render object is used.
bool _compact = false;
// This is the content we show in the rendering.
//
// Headline and Paragraph are simple custom widgets defined below.
//
// Any widget _could_ be specified here, and would render fine.
// The Headline and Paragraph widgets are used so that the renderer
// can distinguish between the kinds of content and use different
// spacing between different children.
static const List<Widget> body = <Widget>[
Headline('Bugs that improve T for future bugs'),
Paragraph(
'The best bugs to fix are those that make us more productive '
'in the future. Reducing test flakiness, reducing technical '
'debt, increasing the number of team members who are able to '
'review code confidently and well: this all makes future bugs '
'easier to fix, which is a huge multiplier to our overall '
'effectiveness and thus to developer happiness.',
),
Headline('Bugs affecting more people are more valuable (maximize N)'),
Paragraph(
'We will make more people happier if we fix a bug experienced by more people.'
),
Paragraph(
'One thing to be careful about is to think about the number of '
'people we are ignoring in our metrics. For example, if we had '
'a bug that prevented our product from working on Windows, we '
'would have no Windows users, so the bug would affect nobody. '
'However, fixing the bug would enable millions of developers '
"to use our product, and that's the number that counts."
),
Headline('Bugs with greater impact on developers are more valuable (maximize ΔH)'),
Paragraph(
'A slight improvement to the user experience is less valuable '
'than a greater improvement. For example, if our application, '
'under certain conditions, shows a message with a typo, and '
'then crashes because of an off-by-one error in the code, '
'fixing the crash is a higher priority than fixing the typo.'
),
];
// This is the description of the demo's interface.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Custom Render Boxes'),
// There are two buttons over to the top right of the demo that let you
// toggle between the two rendering modes.
actions: <Widget>[
IconButton(
icon: const Icon(Icons.density_small),
isSelected: _compact,
onPressed: () {
setState(() { _compact = true; });
},
),
IconButton(
icon: const Icon(Icons.density_large),
isSelected: !_compact,
onPressed: () {
setState(() { _compact = false; });
},
),
],
),
body: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 30.0, vertical: 20.0),
// CompactLayout and OpenLayout are the two rendering widgets defined below.
child: _compact ? const CompactLayout(children: body) : const OpenLayout(children: body),
),
),
);
}
}
// Headline and Paragraph are just wrappers around the Text widget, but they
// also introduce a TextCategory widget that the CompactLayout and OpenLayout
// widgets can read to determine what kind of child is being rendered.
class Headline extends StatelessWidget {
const Headline(this.text, { super.key });
final String text;
@override
Widget build(BuildContext context) {
return TextCategory(
category: 'headline',
child: Text(text, style: Theme.of(context).textTheme.titleLarge),
);
}
}
class Paragraph extends StatelessWidget {
const Paragraph(this.text, { super.key });
final String text;
@override
Widget build(BuildContext context) {
return TextCategory(
category: 'paragraph',
child: Text(text, style: Theme.of(context).textTheme.bodyLarge),
);
}
}
// This is the ParentDataWidget that allows us to specify what kind of child
// is being rendered. It allows information to be shared with the render object
// without violating the principle of agnostic composition (wherein parents should
// work with any child, not only support a fixed set of children).
class TextCategory extends ParentDataWidget<TextFlowParentData> {
const TextCategory({ super.key, required this.category, required super.child });
final String category;
@override
void applyParentData(RenderObject renderObject) {
final TextFlowParentData parentData = renderObject.parentData! as TextFlowParentData;
if (parentData.category != category) {
parentData.category = category;
renderObject.parent!.markNeedsLayout();
}
}
@override
Type get debugTypicalAncestorWidgetClass => OpenLayout;
}
// This is one of the two layout variants. It is a widget that defers to
// a render object defined below (RenderCompactLayout).
class CompactLayout extends MultiChildRenderObjectWidget {
const CompactLayout({ super.key, super.children });
@override
RenderCompactLayout createRenderObject(BuildContext context) {
return RenderCompactLayout();
}
@override
void updateRenderObject(BuildContext context, RenderCompactLayout renderObject) {
// nothing to update
}
}
// This is the other of the two layout variants. It is a widget that defers to a
// render object defined below (RenderOpenLayout).
class OpenLayout extends MultiChildRenderObjectWidget {
const OpenLayout({ super.key, super.children });
@override
RenderOpenLayout createRenderObject(BuildContext context) {
return RenderOpenLayout();
}
@override
void updateRenderObject(BuildContext context, RenderOpenLayout renderObject) {
// nothing to update
}
}
// This is the data structure that contains the kind of data that can be
// passed to the parent to label the child. It is literally stored on
// the RenderObject child, in its "parentData" field.
class TextFlowParentData extends ContainerBoxParentData<RenderBox> {
String category = '';
}
// This is the bulk of the layout logic. (It's similar to RenderListBody,
// but only supports vertical layout.) It has no properties.
//
// This is an abstract class that is then extended by RenderCompactLayout and
// RenderOpenLayout to get different layouts based on the children's categories,
// as stored in the ParentData structure defined above.
//
// The documentation for the RenderBox class and its members provides much
// more detail on how to implement each of the methods below.
abstract class RenderTextFlow extends RenderBox
with ContainerRenderObjectMixin<RenderBox, TextFlowParentData>,
RenderBoxContainerDefaultsMixin<RenderBox, TextFlowParentData> {
RenderTextFlow({ List<RenderBox>? children }) {
addAll(children);
}
@override
void setupParentData(RenderBox child) {
if (child.parentData is! TextFlowParentData) {
child.parentData = TextFlowParentData();
}
}
// This is the function that is overridden by the subclasses to do the
// actual decision about the space to use between children.
double spacingBetween(String before, String after);
// The next few functions are the layout functions. In each case we walk the
// children, calling each one to determine the geometry of the child, and use
// that to determine the layout.
// The first two functions compute the intrinsic width of the render object,
// as seen when using the IntrinsicWidth widget.
//
// They essentially defer to the widest child.
@override
double computeMinIntrinsicWidth(double height) {
double width = 0.0;
RenderBox? child = firstChild;
while (child != null) {
final double childWidth = child.getMinIntrinsicWidth(height);
if (childWidth > width) {
width = childWidth;
}
child = childAfter(child);
}
return width;
}
@override
double computeMaxIntrinsicWidth(double height) {
double width = 0.0;
RenderBox? child = firstChild;
while (child != null) {
final double childWidth = child.getMaxIntrinsicWidth(height);
if (childWidth > width) {
width = childWidth;
}
child = childAfter(child);
}
return width;
}
// The next two functions compute the intrinsic height of the render object,
// as seen when using the IntrinsicHeight widget.
//
// They add up the height contributed by each child.
//
// They have to take into account the categories of the children and the
// spacing that will be added, hence the slightly more elaborate logic.
@override
double computeMinIntrinsicHeight(double width) {
String? previousCategory;
double height = 0.0;
RenderBox? child = firstChild;
while (child != null) {
final String category = (child.parentData! as TextFlowParentData).category;
if (previousCategory != null) {
height += spacingBetween(previousCategory, category);
}
height += child.getMinIntrinsicHeight(width);
previousCategory = category;
child = childAfter(child);
}
return height;
}
@override
double computeMaxIntrinsicHeight(double width) {
String? previousCategory;
double height = 0.0;
RenderBox? child = firstChild;
while (child != null) {
final String category = (child.parentData! as TextFlowParentData).category;
if (previousCategory != null) {
height += spacingBetween(previousCategory, category);
}
height += child.getMaxIntrinsicHeight(width);
previousCategory = category;
child = childAfter(child);
}
return height;
}
// This function implements the baseline logic. Because this class does
// nothing special, we just defer to the default implementation in the
// RenderBoxContainerDefaultsMixin utility class.
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
return defaultComputeDistanceToFirstActualBaseline(baseline);
}
// Next we have a function similar to the intrinsic methods, but for both axes
// at the same time.
@override
Size computeDryLayout(BoxConstraints constraints) {
final BoxConstraints innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth);
String? previousCategory;
double y = 0.0;
RenderBox? child = firstChild;
while (child != null) {
final String category = (child.parentData! as TextFlowParentData).category;
if (previousCategory != null) {
y += spacingBetween(previousCategory, category);
}
final Size childSize = child.getDryLayout(innerConstraints);
y += childSize.height;
previousCategory = category;
child = childAfter(child);
}
return constraints.constrain(Size(constraints.maxWidth, y));
}
// This is the core of the layout logic. Most of the time, this is the only
// function that will be called. It computes the size and position of each
// child, and stores it (in the parent data, as it happens!) for use during
// the paint phase.
@override
void performLayout() {
final BoxConstraints innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth);
String? previousCategory;
double y = 0.0;
RenderBox? child = firstChild;
while (child != null) {
final String category = (child.parentData! as TextFlowParentData).category;
if (previousCategory != null) {
// This is where we call the function that computes the spacing between
// the different children. The arguments are the categories, obtained
// from the parentData property of each child.
y += spacingBetween(previousCategory, category);
}
child.layout(innerConstraints, parentUsesSize: true);
(child.parentData! as TextFlowParentData).offset = Offset(0.0, y);
y += child.size.height;
previousCategory = category;
child = childAfter(child);
}
size = constraints.constrain(Size(constraints.maxWidth, y));
}
// Hit testing is normal for this widget, so we defer to the default implementation.
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return defaultHitTestChildren(result, position: position);
}
// Painting is normal for this widget, so we defer to the default
// implementation. The default implementation expects to find the positions
// configured in the parentData property of each child, which is why we
// configure it that way in performLayout above.
@override
void paint(PaintingContext context, Offset offset) {
defaultPaint(context, offset);
}
}
// Finally we have the two render objects that implement the two layouts in this demo.
class RenderOpenLayout extends RenderTextFlow {
@override
double spacingBetween(String before, String after) {
if (after == 'headline') {
return 20.0;
}
if (before == 'headline') {
return 5.0;
}
return 10.0;
}
}
class RenderCompactLayout extends RenderTextFlow {
@override
double spacingBetween(String before, String after) {
if (after == 'headline') {
return 4.0;
}
return 2.0;
}
}
| flutter/examples/api/lib/rendering/box/parent_data.0.dart/0 | {
"file_path": "flutter/examples/api/lib/rendering/box/parent_data.0.dart",
"repo_id": "flutter",
"token_count": 4350
} | 576 |
// 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';
/// Flutter code sample for [SliverAnimatedList].
void main() => runApp(const SliverAnimatedListSample());
class SliverAnimatedListSample extends StatefulWidget {
const SliverAnimatedListSample({super.key});
@override
State<SliverAnimatedListSample> createState() => _SliverAnimatedListSampleState();
}
class _SliverAnimatedListSampleState extends State<SliverAnimatedListSample> {
final GlobalKey<SliverAnimatedListState> _listKey = GlobalKey<SliverAnimatedListState>();
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
late ListModel<int> _list;
int? _selectedItem;
late int _nextItem; // The next item inserted when the user presses the '+' button.
@override
void initState() {
super.initState();
_list = ListModel<int>(
listKey: _listKey,
initialItems: <int>[0, 1, 2],
removedItemBuilder: _buildRemovedItem,
);
_nextItem = 3;
}
// Used to build list items that haven't been removed.
Widget _buildItem(BuildContext context, int index, Animation<double> animation) {
return CardItem(
animation: animation,
item: _list[index],
selected: _selectedItem == _list[index],
onTap: () {
setState(() {
_selectedItem = _selectedItem == _list[index] ? null : _list[index];
});
},
);
}
/// The builder function used to build items that have been removed.
///
/// Used to build an item after it has been removed from the list. This method
/// is needed because a removed item remains visible until its animation has
/// completed (even though it's gone as far this ListModel is concerned). The
/// widget will be used by the [AnimatedListState.removeItem] method's
/// [AnimatedRemovedItemBuilder] parameter.
Widget _buildRemovedItem(int item, BuildContext context, Animation<double> animation) {
return CardItem(
animation: animation,
item: item,
);
}
// Insert the "next item" into the list model.
void _insert() {
final int index = _selectedItem == null ? _list.length : _list.indexOf(_selectedItem!);
_list.insert(index, _nextItem++);
}
// Remove the selected item from the list model.
void _remove() {
if (_selectedItem != null) {
_list.removeAt(_list.indexOf(_selectedItem!));
setState(() {
_selectedItem = null;
});
} else {
_scaffoldMessengerKey.currentState!.showSnackBar(const SnackBar(
content: Text(
'Select an item to remove from the list.',
style: TextStyle(fontSize: 20),
),
));
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
scaffoldMessengerKey: _scaffoldMessengerKey,
home: Scaffold(
key: _scaffoldKey,
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: const Text(
'SliverAnimatedList',
style: TextStyle(fontSize: 30),
),
expandedHeight: 60,
centerTitle: true,
backgroundColor: Colors.amber[900],
leading: IconButton(
icon: const Icon(Icons.add_circle),
onPressed: _insert,
tooltip: 'Insert a new item.',
iconSize: 32,
),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.remove_circle),
onPressed: _remove,
tooltip: 'Remove the selected item.',
iconSize: 32,
),
],
),
SliverAnimatedList(
key: _listKey,
initialItemCount: _list.length,
itemBuilder: _buildItem,
),
],
),
),
);
}
}
typedef RemovedItemBuilder<E> = Widget Function(E item, BuildContext context, Animation<double> animation);
// Keeps a Dart [List] in sync with an [AnimatedList].
//
// The [insert] and [removeAt] methods apply to both the internal list and
// the animated list that belongs to [listKey].
//
// This class only exposes as much of the Dart List API as is needed by the
// sample app. More list methods are easily added, however methods that
// mutate the list must make the same changes to the animated list in terms
// of [AnimatedListState.insertItem] and [AnimatedList.removeItem].
class ListModel<E> {
ListModel({
required this.listKey,
required this.removedItemBuilder,
Iterable<E>? initialItems,
}) : _items = List<E>.from(initialItems ?? <E>[]);
final GlobalKey<SliverAnimatedListState> listKey;
final RemovedItemBuilder<E> removedItemBuilder;
final List<E> _items;
SliverAnimatedListState get _animatedList => listKey.currentState!;
void insert(int index, E item) {
_items.insert(index, item);
_animatedList.insertItem(index);
}
E removeAt(int index) {
final E removedItem = _items.removeAt(index);
if (removedItem != null) {
_animatedList.removeItem(
index,
(BuildContext context, Animation<double> animation) => removedItemBuilder(removedItem, context, animation),
);
}
return removedItem;
}
int get length => _items.length;
E operator [](int index) => _items[index];
int indexOf(E item) => _items.indexOf(item);
}
// Displays its integer item as 'Item N' on a Card whose color is based on
// the item's value.
//
// The card turns gray when [selected] is true. This widget's height
// is based on the [animation] parameter. It varies as the animation value
// transitions from 0.0 to 1.0.
class CardItem extends StatelessWidget {
const CardItem({
super.key,
this.onTap,
this.selected = false,
required this.animation,
required this.item,
}) : assert(item >= 0);
final Animation<double> animation;
final VoidCallback? onTap;
final int item;
final bool selected;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(
left: 2.0,
right: 2.0,
top: 2.0,
),
child: SizeTransition(
sizeFactor: animation,
child: GestureDetector(
onTap: onTap,
child: SizedBox(
height: 80.0,
child: Card(
color: selected ? Colors.black12 : Colors.primaries[item % Colors.primaries.length],
child: Center(
child: Text(
'Item $item',
style: Theme.of(context).textTheme.headlineMedium,
),
),
),
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/animated_list/sliver_animated_list.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/animated_list/sliver_animated_list.0.dart",
"repo_id": "flutter",
"token_count": 2771
} | 577 |
// 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';
/// Flutter code sample for [OverflowBox].
void main() => runApp(const OverflowBoxApp());
class OverflowBoxApp extends StatelessWidget {
const OverflowBoxApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('OverflowBox Sample')),
body: const Center(
child: OverflowBoxExample(),
),
),
);
}
}
class OverflowBoxExample extends StatelessWidget {
const OverflowBoxExample({super.key});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Cover Me'),
// This parent container has fixed width and
// height of 100 pixels.
Container(
width: 100,
height: 100,
color: Theme.of(context).colorScheme.secondaryContainer,
// This OverflowBox imposes its own constraints of maxWidth
// and maxHeight of 200 pixels on its child which allows the
// child to overflow the parent container.
child: const OverflowBox(
maxWidth: 200,
maxHeight: 200,
// Without the OverflowBox, the child widget would be
// constrained to the size of the parent container
// and would not overflow the parent container.
child: FlutterLogo(size: 200),
),
),
],
);
}
}
| flutter/examples/api/lib/widgets/basic/overflowbox.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/basic/overflowbox.0.dart",
"repo_id": "flutter",
"token_count": 649
} | 578 |
// 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';
/// Flutter code sample for [FocusScope].
void main() => runApp(const FocusScopeExampleApp());
class FocusScopeExampleApp extends StatelessWidget {
const FocusScopeExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: FocusScopeExample(),
);
}
}
/// A demonstration pane.
///
/// This is just a separate widget to simplify the example.
class Pane extends StatelessWidget {
const Pane({
super.key,
required this.focusNode,
this.onPressed,
required this.backgroundColor,
required this.icon,
this.child,
});
final FocusNode focusNode;
final VoidCallback? onPressed;
final Color backgroundColor;
final Widget icon;
final Widget? child;
@override
Widget build(BuildContext context) {
return Material(
color: backgroundColor,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Center(
child: child,
),
Align(
alignment: Alignment.topLeft,
child: IconButton(
autofocus: true,
focusNode: focusNode,
onPressed: onPressed,
icon: icon,
),
),
],
),
);
}
}
class FocusScopeExample extends StatefulWidget {
const FocusScopeExample({super.key});
@override
State<FocusScopeExample> createState() => _FocusScopeExampleState();
}
class _FocusScopeExampleState extends State<FocusScopeExample> {
bool backdropIsVisible = false;
FocusNode backdropNode = FocusNode(debugLabel: 'Close Backdrop Button');
FocusNode foregroundNode = FocusNode(debugLabel: 'Option Button');
@override
void dispose() {
backdropNode.dispose();
foregroundNode.dispose();
super.dispose();
}
Widget _buildStack(BuildContext context, BoxConstraints constraints) {
final Size stackSize = constraints.biggest;
return Stack(
fit: StackFit.expand,
// The backdrop is behind the front widget in the Stack, but the widgets
// would still be active and traversable without the FocusScope.
children: <Widget>[
// TRY THIS: Try removing this FocusScope entirely to see how it affects
// the behavior. Without this FocusScope, the "ANOTHER BUTTON TO FOCUS"
// button, and the IconButton in the backdrop Pane would be focusable
// even when the backdrop wasn't visible.
FocusScope(
// TRY THIS: Try commenting out this line. Notice that the focus
// starts on the backdrop and is stuck there? It seems like the app is
// non-responsive, but it actually isn't. This line makes sure that
// this focus scope and its children can't be focused when they're not
// visible. It might help to make the background color of the
// foreground pane semi-transparent to see it clearly.
canRequestFocus: backdropIsVisible,
child: Pane(
icon: const Icon(Icons.close),
focusNode: backdropNode,
backgroundColor: Colors.lightBlue,
onPressed: () => setState(() => backdropIsVisible = false),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// This button would be not visible, but still focusable from
// the foreground pane without the FocusScope.
ElevatedButton(
onPressed: () => debugPrint('You pressed the other button!'),
child: const Text('ANOTHER BUTTON TO FOCUS'),
),
DefaultTextStyle(
style: Theme.of(context).textTheme.displayMedium!,
child: const Text('BACKDROP'),
),
],
),
),
),
AnimatedPositioned(
curve: Curves.easeInOut,
duration: const Duration(milliseconds: 300),
top: backdropIsVisible ? stackSize.height * 0.9 : 0.0,
width: stackSize.width,
height: stackSize.height,
onEnd: () {
if (backdropIsVisible) {
backdropNode.requestFocus();
} else {
foregroundNode.requestFocus();
}
},
child: Pane(
icon: const Icon(Icons.menu),
focusNode: foregroundNode,
// TRY THIS: Try changing this to Colors.green.withOpacity(0.8) to see for
// yourself that the hidden components do/don't get focus.
backgroundColor: Colors.green,
onPressed: backdropIsVisible ? null : () => setState(() => backdropIsVisible = true),
child: DefaultTextStyle(
style: Theme.of(context).textTheme.displayMedium!,
child: const Text('FOREGROUND'),
),
),
),
],
);
}
@override
Widget build(BuildContext context) {
// Use a LayoutBuilder so that we can base the size of the stack on the size
// of its parent.
return LayoutBuilder(builder: _buildStack);
}
}
| flutter/examples/api/lib/widgets/focus_scope/focus_scope.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/focus_scope/focus_scope.0.dart",
"repo_id": "flutter",
"token_count": 2162
} | 579 |
// 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';
/// Flutter code sample for [AnimatedAlign].
void main() => runApp(const AnimatedAlignExampleApp());
class AnimatedAlignExampleApp extends StatelessWidget {
const AnimatedAlignExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('AnimatedAlign Sample')),
body: const AnimatedAlignExample(),
),
);
}
}
class AnimatedAlignExample extends StatefulWidget {
const AnimatedAlignExample({super.key});
@override
State<AnimatedAlignExample> createState() => _AnimatedAlignExampleState();
}
class _AnimatedAlignExampleState extends State<AnimatedAlignExample> {
bool selected = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
selected = !selected;
});
},
child: Center(
child: Container(
width: 250.0,
height: 250.0,
color: Colors.red,
child: AnimatedAlign(
alignment: selected ? Alignment.topRight : Alignment.bottomLeft,
duration: const Duration(seconds: 1),
curve: Curves.fastOutSlowIn,
child: const FlutterLogo(size: 50.0),
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/implicit_animations/animated_align.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/implicit_animations/animated_align.0.dart",
"repo_id": "flutter",
"token_count": 587
} | 580 |
// 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';
/// Flutter code sample for [MediaQueryData.systemGestureInsets].
void main() => runApp(const SystemGestureInsetsExampleApp());
class SystemGestureInsetsExampleApp extends StatelessWidget {
const SystemGestureInsetsExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: SystemGestureInsetsExample(),
);
}
}
class SystemGestureInsetsExample extends StatefulWidget {
const SystemGestureInsetsExample({super.key});
@override
State<SystemGestureInsetsExample> createState() => _SystemGestureInsetsExampleState();
}
class _SystemGestureInsetsExampleState extends State<SystemGestureInsetsExample> {
double _currentValue = 0.2;
@override
Widget build(BuildContext context) {
final EdgeInsets systemGestureInsets = MediaQuery.of(context).systemGestureInsets;
return Scaffold(
appBar: AppBar(title: const Text('Pad Slider to avoid systemGestureInsets')),
body: Padding(
padding: EdgeInsets.only(
// only left and right padding are needed here
left: systemGestureInsets.left,
right: systemGestureInsets.right,
),
child: Slider(
value: _currentValue,
onChanged: (double newValue) {
setState(() {
_currentValue = newValue;
});
},
),
),
);
}
}
| flutter/examples/api/lib/widgets/media_query/media_query_data.system_gesture_insets.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/media_query/media_query_data.system_gesture_insets.0.dart",
"repo_id": "flutter",
"token_count": 592
} | 581 |
// 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';
/// Flutter code sample for [OverflowBar].
void main() => runApp(const OverflowBarExampleApp());
class OverflowBarExampleApp extends StatelessWidget {
const OverflowBarExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('OverflowBar Sample')),
body: const Center(
child: OverflowBarExample(),
),
),
);
}
}
class OverflowBarExample extends StatelessWidget {
const OverflowBarExample({super.key});
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(16),
color: Colors.black.withOpacity(0.15),
child: Material(
color: Colors.white,
elevation: 24,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4))),
child: Padding(
padding: const EdgeInsets.all(8),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
const SizedBox(height: 128, child: Placeholder()),
Align(
alignment: AlignmentDirectional.centerEnd,
child: OverflowBar(
spacing: 8,
overflowAlignment: OverflowBarAlignment.end,
children: <Widget>[
TextButton(child: const Text('Cancel'), onPressed: () {}),
TextButton(child: const Text('Really Really Cancel'), onPressed: () {}),
OutlinedButton(child: const Text('OK'), onPressed: () {}),
],
),
),
],
),
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/overflow_bar/overflow_bar.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/overflow_bar/overflow_bar.0.dart",
"repo_id": "flutter",
"token_count": 964
} | 582 |
// 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';
/// Flutter code sample for [ScrollController] & [ScrollNotification].
void main() => runApp(const ScrollNotificationDemo());
class ScrollNotificationDemo extends StatefulWidget {
const ScrollNotificationDemo({super.key});
@override
State<ScrollNotificationDemo> createState() => _ScrollNotificationDemoState();
}
class _ScrollNotificationDemoState extends State<ScrollNotificationDemo> {
ScrollNotification? _lastNotification;
late final ScrollController _controller;
bool _useController = true;
// This method handles the notification from the ScrollController.
void _handleControllerNotification() {
print('Notified through the scroll controller.');
// Access the position directly through the controller for details on the
// scroll position.
}
// This method handles the notification from the NotificationListener.
bool _handleScrollNotification(ScrollNotification notification) {
print('Notified through scroll notification.');
// The position can still be accessed through the scroll controller, but
// the notification object provides more details about the activity that is
// occurring.
if (_lastNotification.runtimeType != notification.runtimeType) {
setState(() {
// Call set state to respond to a change in the scroll notification.
_lastNotification = notification;
});
}
// Returning false allows the notification to continue bubbling up to
// ancestor listeners. If we wanted the notification to stop bubbling,
// return true.
return false;
}
@override
void initState() {
_controller = ScrollController();
if (_useController) {
// When listening to scrolling via the ScrollController, call
// `addListener` on the controller.
_controller.addListener(_handleControllerNotification);
}
super.initState();
}
@override
Widget build(BuildContext context) {
// ListView.separated works very similarly to this example with
// CustomScrollView & SliverList.
Widget body = CustomScrollView(
// Provide the scroll controller to the scroll view.
controller: _controller,
slivers: <Widget>[
SliverList.separated(
itemCount: 50,
itemBuilder: (_,int index) {
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 20.0,
),
child: Text('Item $index'),
);
},
separatorBuilder: (_, __) => const Divider(
indent: 20,
endIndent: 20,
thickness: 2,
),
),
],
);
if (!_useController) {
// If we are not using a ScrollController to listen to scrolling,
// let's use a NotificationListener. Similar, but with a different
// handler that provides information on what scrolling is occurring.
body = NotificationListener<ScrollNotification>(
onNotification: _handleScrollNotification,
child: body,
);
}
return MaterialApp(
theme: ThemeData.from(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blueGrey),
),
home: Scaffold(
appBar: AppBar(
title: const Text('Listening to a ScrollPosition'),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(70),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
if (!_useController) Text('Last notification: ${_lastNotification.runtimeType}'),
if (!_useController) const SizedBox.square(dimension: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('with:'),
Radio<bool>(
value: true,
groupValue: _useController,
onChanged: _handleRadioChange,
),
const Text('ScrollController'),
Radio<bool>(
value: false,
groupValue: _useController,
onChanged: _handleRadioChange,
),
const Text('NotificationListener'),
],
),
],
),
),
),
body: body,
),
);
}
void _handleRadioChange(bool? value) {
if (value == null) {
return;
}
if (value != _useController) {
setState(() {
// Respond to a change in selected radio button, and add/remove the
// listener to the scroll controller.
_useController = value;
if (_useController) {
_controller.addListener(_handleControllerNotification);
} else {
_controller.removeListener(_handleControllerNotification);
}
});
}
}
@override
void dispose() {
_controller.removeListener(_handleControllerNotification);
super.dispose();
}
}
| flutter/examples/api/lib/widgets/scroll_position/scroll_controller_notification.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/scroll_position/scroll_controller_notification.0.dart",
"repo_id": "flutter",
"token_count": 2146
} | 583 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Flutter code sample for [LogicalKeySet].
void main() => runApp(const LogicalKeySetExampleApp());
class LogicalKeySetExampleApp extends StatelessWidget {
const LogicalKeySetExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('LogicalKeySet Sample')),
body: const Center(
child: LogicalKeySetExample(),
),
),
);
}
}
class IncrementIntent extends Intent {
const IncrementIntent();
}
class LogicalKeySetExample extends StatefulWidget {
const LogicalKeySetExample({super.key});
@override
State<LogicalKeySetExample> createState() => _LogicalKeySetExampleState();
}
class _LogicalKeySetExampleState extends State<LogicalKeySetExample> {
int count = 0;
@override
Widget build(BuildContext context) {
return Shortcuts(
shortcuts: <ShortcutActivator, Intent>{
LogicalKeySet(LogicalKeyboardKey.keyC, LogicalKeyboardKey.controlLeft): const IncrementIntent(),
},
child: Actions(
actions: <Type, Action<Intent>>{
IncrementIntent: CallbackAction<IncrementIntent>(
onInvoke: (IncrementIntent intent) => setState(() {
count = count + 1;
}),
),
},
child: Focus(
autofocus: true,
child: Column(
children: <Widget>[
const Text('Add to the counter by pressing Ctrl+C'),
Text('count: $count'),
],
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/shortcuts/logical_key_set.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/shortcuts/logical_key_set.0.dart",
"repo_id": "flutter",
"token_count": 726
} | 584 |
// 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';
/// Flutter code sample for [Table].
void main() => runApp(const TableExampleApp());
class TableExampleApp extends StatelessWidget {
const TableExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Table Sample')),
body: const TableExample(),
),
);
}
}
class TableExample extends StatelessWidget {
const TableExample({super.key});
@override
Widget build(BuildContext context) {
return Table(
border: TableBorder.all(),
columnWidths: const <int, TableColumnWidth>{
0: IntrinsicColumnWidth(),
1: FlexColumnWidth(),
2: FixedColumnWidth(64),
},
defaultVerticalAlignment: TableCellVerticalAlignment.middle,
children: <TableRow>[
TableRow(
children: <Widget>[
Container(
height: 32,
color: Colors.green,
),
TableCell(
verticalAlignment: TableCellVerticalAlignment.top,
child: Container(
height: 32,
width: 32,
color: Colors.red,
),
),
Container(
height: 64,
color: Colors.blue,
),
],
),
TableRow(
decoration: const BoxDecoration(
color: Colors.grey,
),
children: <Widget>[
Container(
height: 64,
width: 128,
color: Colors.purple,
),
Container(
height: 32,
color: Colors.yellow,
),
Center(
child: Container(
height: 32,
width: 32,
color: Colors.orange,
),
),
],
),
],
);
}
}
| flutter/examples/api/lib/widgets/table/table.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/table/table.0.dart",
"repo_id": "flutter",
"token_count": 1060
} | 585 |
// 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';
/// Flutter code sample for [RelativePositionedTransition].
void main() => runApp(const RelativePositionedTransitionExampleApp());
class RelativePositionedTransitionExampleApp extends StatelessWidget {
const RelativePositionedTransitionExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: RelativePositionedTransitionExample(),
);
}
}
class RelativePositionedTransitionExample extends StatefulWidget {
const RelativePositionedTransitionExample({super.key});
@override
State<RelativePositionedTransitionExample> createState() => _RelativePositionedTransitionExampleState();
}
/// [AnimationController]s can be created with `vsync: this` because of
/// [TickerProviderStateMixin].
class _RelativePositionedTransitionExampleState extends State<RelativePositionedTransitionExample>
with TickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
const double smallLogo = 100;
const double bigLogo = 200;
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final Size biggest = constraints.biggest;
return Stack(
children: <Widget>[
RelativePositionedTransition(
size: biggest,
rect: RectTween(
begin: const Rect.fromLTWH(0, 0, bigLogo, bigLogo),
end: Rect.fromLTWH(
biggest.width - smallLogo,
biggest.height - smallLogo,
smallLogo,
smallLogo,
),
).animate(CurvedAnimation(
parent: _controller,
curve: Curves.elasticInOut,
)),
child: const Padding(
padding: EdgeInsets.all(8),
child: FlutterLogo(),
),
),
],
);
},
);
}
}
| flutter/examples/api/lib/widgets/transitions/relative_positioned_transition.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/transitions/relative_positioned_transition.0.dart",
"repo_id": "flutter",
"token_count": 930
} | 586 |
// 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_api_samples/cupertino/date_picker/cupertino_date_picker.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
const Offset _kRowOffset = Offset(0.0, -50.0);
void main() {
testWidgets('Can change date, time and dateTime using CupertinoDatePicker', (WidgetTester tester) async {
await tester.pumpWidget(
const example.DatePickerApp(),
);
// Open the date picker.
await tester.tap(find.text('10-26-2016'));
await tester.pumpAndSettle();
// Drag month, day and year wheels to change the picked date.
await tester.drag(find.text('October'), _kRowOffset, touchSlopY: 0, warnIfMissed: false); // see top of file
await tester.drag(find.textContaining('26').last, _kRowOffset, touchSlopY: 0, warnIfMissed: false); // see top of file
await tester.drag(find.text('2016'), _kRowOffset, touchSlopY: 0, warnIfMissed: false); // see top of file
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
// Close the date picker.
await tester.tapAt(const Offset(1.0, 1.0));
await tester.pumpAndSettle();
expect(find.text('12-28-2018'), findsOneWidget);
// Open the time picker.
await tester.tap(find.text('22:35'));
await tester.pumpAndSettle();
// Drag hour and minute wheels to change the picked time.
await tester.drag(find.text('22'), const Offset(0.0, 50.0), touchSlopY: 0, warnIfMissed: false); // see top of file
await tester.drag(find.text('35'), const Offset(0.0, 50.0), touchSlopY: 0, warnIfMissed: false); // see top of file
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
// Close the time picker.
await tester.tapAt(const Offset(1.0, 1.0));
await tester.pumpAndSettle();
expect(find.text('20:33'), findsOneWidget);
// Open the dateTime picker.
await tester.tap(find.text('8-3-2016 17:45'));
await tester.pumpAndSettle();
// Drag hour and minute wheels to change the picked time.
await tester.drag(find.text('17'), const Offset(0.0, 50.0), touchSlopY: 0, warnIfMissed: false); // see top of file
await tester.drag(find.text('45'), const Offset(0.0, 50.0), touchSlopY: 0, warnIfMissed: false); // see top of file
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
// Close the dateTime picker.
await tester.tapAt(const Offset(1.0, 1.0));
await tester.pumpAndSettle();
expect(find.text('8-3-2016 15:43'), findsOneWidget);
});
}
| flutter/examples/api/test/cupertino/date_picker/cupertino_date_picker.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/cupertino/date_picker/cupertino_date_picker.0_test.dart",
"repo_id": "flutter",
"token_count": 1003
} | 587 |
// 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_api_samples/cupertino/scrollbar/cupertino_scrollbar.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('List view displays CupertinoScrollbar', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ScrollbarApp(),
);
expect(find.text('Item 0'), findsOneWidget);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(ListView)));
await gesture.moveBy(const Offset(0.0, -100.0));
await tester.pumpAndSettle();
expect(find.text('Item 0'), findsNothing);
final Finder scrollbar = find.byType(CupertinoScrollbar);
expect(scrollbar, findsOneWidget);
expect(tester.getTopLeft(scrollbar).dy, 0.0);
expect(tester.getBottomLeft(scrollbar).dy, 600.0);
});
}
| flutter/examples/api/test/cupertino/scrollbar/cupertino_scrollbar.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/cupertino/scrollbar/cupertino_scrollbar.0_test.dart",
"repo_id": "flutter",
"token_count": 358
} | 588 |
// 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_api_samples/material/action_buttons/action_icon_theme.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Action Icon Buttons', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: example.ActionIconThemeExampleApp(),
),
),
);
expect(find.byType(DrawerButton), findsOneWidget);
final Icon drawerButtonIcon = tester.widget(
find.descendant(
of: find.byType(DrawerButton),
matching: find.byType(Icon),
),
);
expect(drawerButtonIcon.icon, Icons.segment);
// open next page
await tester.tap(find.byType(example.NextPageButton));
await tester.pumpAndSettle();
expect(find.byType(EndDrawerButton), findsOneWidget);
final Icon endDrawerButtonIcon = tester.widget(
find.descendant(
of: find.byType(EndDrawerButton),
matching: find.byType(Icon),
),
);
expect(endDrawerButtonIcon.icon, Icons.more_horiz);
expect(find.byType(BackButton), findsOneWidget);
final Icon backButtonIcon = tester.widget(
find.descendant(
of: find.byType(BackButton),
matching: find.byType(Icon),
),
);
expect(backButtonIcon.icon, Icons.arrow_back_ios_new_rounded);
});
}
| flutter/examples/api/test/material/action_buttons/action_icon_theme.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/action_buttons/action_icon_theme.0_test.dart",
"repo_id": "flutter",
"token_count": 607
} | 589 |
// 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_api_samples/material/bottom_navigation_bar/bottom_navigation_bar.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('BottomNavigationBar Updates Screen Content', (WidgetTester tester) async {
await tester.pumpWidget(
const example.BottomNavigationBarExampleApp(),
);
expect(find.widgetWithText(AppBar, 'BottomNavigationBar Sample'), findsOneWidget);
expect(find.byType(BottomNavigationBar), findsOneWidget);
expect(find.widgetWithText(Center, 'Index 0: Home'), findsOneWidget);
await tester.tap(find.byIcon(Icons.business));
await tester.pumpAndSettle();
expect(find.widgetWithText(Center, 'Index 1: Business'), findsOneWidget);
await tester.tap(find.byIcon(Icons.school));
await tester.pumpAndSettle();
expect(find.widgetWithText(Center, 'Index 2: School'), findsOneWidget);
// Verify we can go back
await tester.tap(find.byIcon(Icons.home));
await tester.pumpAndSettle();
expect(find.widgetWithText(Center, 'Index 0: Home'), findsOneWidget);
});
}
| flutter/examples/api/test/material/bottom_navigation_bar/bottom_navigation_bar.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/bottom_navigation_bar/bottom_navigation_bar.0_test.dart",
"repo_id": "flutter",
"token_count": 432
} | 590 |
// 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_api_samples/material/chip/deletable_chip_attributes.delete_icon_box_constraints.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('RawChip.deleteIconBoxConstraints updates delete icon size constraints', (WidgetTester tester) async {
const double border = 1.0;
const double iconSize = 18.0;
const double padding = 8.0;
await tester.pumpWidget(
const example.DeleteIconBoxConstraintsApp(),
);
expect(tester.getSize(find.byType(RawChip).at(0)).width, equals(202.0));
expect(tester.getSize(find.byType(RawChip).at(0)).height, equals(58.0));
Offset chipToRight = tester.getTopRight(find.byWidget(tester.widget<Material>(
find.descendant(
of: find.byType(RawChip).at(0),
matching: find.byType(Material),
),
)));
Offset deleteIconCenter = tester.getCenter(find.byIcon(Icons.cancel).at(0));
expect(chipToRight.dx, deleteIconCenter.dx + (iconSize / 2) + padding + border);
expect(tester.getSize(find.byType(RawChip).at(1)).width, equals(202.0));
expect(tester.getSize(find.byType(RawChip).at(1)).height, equals(78.0));
chipToRight = tester.getTopRight(find.byWidget(tester.widget<Material>(
find.descendant(
of: find.byType(RawChip).at(1),
matching: find.byType(Material),
),
)));
deleteIconCenter = tester.getCenter(find.byIcon(Icons.cancel).at(1));
expect(chipToRight.dx, deleteIconCenter.dx + (iconSize / 2) + padding + border);
expect(tester.getSize(find.byType(RawChip).at(2)).width, equals(202.0));
expect(tester.getSize(find.byType(RawChip).at(2)).height, equals(78.0));
chipToRight = tester.getTopRight(find.byWidget(tester.widget<Material>(
find.descendant(
of: find.byType(RawChip).at(2),
matching: find.byType(Material),
),
)));
deleteIconCenter = tester.getCenter(find.byIcon(Icons.cancel).at(2));
expect(chipToRight.dx, deleteIconCenter.dx + (iconSize / 2) + padding + border);
});
}
| flutter/examples/api/test/material/chip/deletable_chip_attributes.delete_icon_box_constraints.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/chip/deletable_chip_attributes.delete_icon_box_constraints.0_test.dart",
"repo_id": "flutter",
"token_count": 870
} | 591 |
// 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_api_samples/material/dialog/dialog.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Show Dialog', (WidgetTester tester) async {
const String dialogText = 'This is a typical dialog.';
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: example.DialogExampleApp(),
),
),
);
expect(find.text(dialogText), findsNothing);
await tester.tap(find.text('Show Dialog'));
await tester.pumpAndSettle();
expect(find.text(dialogText), findsOneWidget);
await tester.tap(find.text('Close'));
await tester.pumpAndSettle();
expect(find.text(dialogText), findsNothing);
});
testWidgets('Show Dialog.fullscreen', (WidgetTester tester) async {
const String dialogText = 'This is a fullscreen dialog.';
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: example.DialogExampleApp(),
),
),
);
expect(find.text(dialogText), findsNothing);
await tester.tap(find.text('Show Fullscreen Dialog'));
await tester.pumpAndSettle();
expect(find.text(dialogText), findsOneWidget);
await tester.tap(find.text('Close'));
await tester.pumpAndSettle();
expect(find.text(dialogText), findsNothing);
});
}
| flutter/examples/api/test/material/dialog/dialog.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/dialog/dialog.0_test.dart",
"repo_id": "flutter",
"token_count": 578
} | 592 |
// 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_api_samples/material/expansion_tile/expansion_tile.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('When expansion tiles are expanded tile numbers are revealed', (WidgetTester tester) async {
const int totalTiles = 3;
await tester.pumpWidget(
const example.ExpansionTileApp(),
);
expect(find.byType(ExpansionTile), findsNWidgets(totalTiles));
const String tileOne = 'This is tile number 1';
expect(find.text(tileOne), findsNothing);
await tester.tap(find.text('ExpansionTile 1'));
await tester.pumpAndSettle();
expect(find.text(tileOne), findsOneWidget);
const String tileTwo = 'This is tile number 2';
expect(find.text(tileTwo), findsNothing);
await tester.tap(find.text('ExpansionTile 2'));
await tester.pumpAndSettle();
expect(find.text(tileTwo), findsOneWidget);
const String tileThree = 'This is tile number 3';
expect(find.text(tileThree), findsNothing);
await tester.tap(find.text('ExpansionTile 3'));
await tester.pumpAndSettle();
expect(find.text(tileThree), findsOneWidget);
});
}
| flutter/examples/api/test/material/expansion_tile/expansion_tile.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/expansion_tile/expansion_tile.0_test.dart",
"repo_id": "flutter",
"token_count": 459
} | 593 |
// 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_api_samples/material/input_decorator/input_decoration.floating_label_style_error.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('InputDecorator label uses error color', (WidgetTester tester) async {
await tester.pumpWidget(
const example.FloatingLabelStyleErrorExampleApp(),
);
final Theme theme = tester.firstWidget(find.byType(Theme));
await tester.tap(find.byType(TextFormField));
await tester.pumpAndSettle();
final AnimatedDefaultTextStyle label = tester.firstWidget(find.ancestor(of: find.text('Name'), matching: find.byType(AnimatedDefaultTextStyle)));
expect(label.style.color, theme.data.colorScheme.error);
});
}
| flutter/examples/api/test/material/input_decorator/input_decoration.floating_label_style_error.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/input_decorator/input_decoration.floating_label_style_error.0_test.dart",
"repo_id": "flutter",
"token_count": 307
} | 594 |
// 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/services.dart';
import 'package:flutter_api_samples/material/menu_anchor/menu_anchor.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Can open menu', (WidgetTester tester) async {
Finder findMenu() {
return find.ancestor(
of: find.text(example.MenuEntry.about.label),
matching: find.byType(FocusScope),
).first;
}
await tester.pumpWidget(const example.ContextMenuApp());
await tester.tapAt(const Offset(100, 200), buttons: kSecondaryButton);
await tester.pumpAndSettle();
expect(tester.getRect(findMenu()).left, equals(100.0));
expect(tester.getRect(findMenu()).top, equals(200.0));
expect(tester.getRect(findMenu()).right, closeTo(389.8, 0.1));
expect(tester.getRect(findMenu()).bottom, equals(360.0));
// Make sure tapping in a different place causes the menu to move.
await tester.tapAt(const Offset(200, 100), buttons: kSecondaryButton);
await tester.pump();
expect(tester.getRect(findMenu()).left, equals(200.0));
expect(tester.getRect(findMenu()).top, equals(100.0));
expect(tester.getRect(findMenu()).right, closeTo(489.8, 0.1));
expect(tester.getRect(findMenu()).bottom, equals(260.0));
expect(find.text(example.MenuEntry.about.label), findsOneWidget);
expect(find.text(example.MenuEntry.showMessage.label), findsOneWidget);
expect(find.text(example.MenuEntry.hideMessage.label), findsNothing);
expect(find.text('Background Color'), findsOneWidget);
expect(find.text(example.MenuEntry.colorRed.label), findsNothing);
expect(find.text(example.MenuEntry.colorGreen.label), findsNothing);
expect(find.text(example.MenuEntry.colorBlue.label), findsNothing);
expect(find.text(example.ContextMenuApp.kMessage), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(find.text('Background Color'), findsOneWidget);
// Focusing the background color item with the keyboard caused the submenu
// to open. Tapping it should cause it to close.
await tester.tap(find.text('Background Color'));
await tester.pump();
await tester.pumpAndSettle();
expect(find.text(example.MenuEntry.colorRed.label), findsNothing);
expect(find.text(example.MenuEntry.colorGreen.label), findsNothing);
expect(find.text(example.MenuEntry.colorBlue.label), findsNothing);
await tester.tap(find.text('Background Color'));
await tester.pump();
await tester.pumpAndSettle();
expect(find.text(example.MenuEntry.colorRed.label), findsOneWidget);
expect(find.text(example.MenuEntry.colorGreen.label), findsOneWidget);
expect(find.text(example.MenuEntry.colorBlue.label), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(find.text(example.ContextMenuApp.kMessage), findsOneWidget);
expect(find.text('Last Selected: ${example.MenuEntry.showMessage.label}'), findsOneWidget);
});
testWidgets('Shortcuts work', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ContextMenuApp(),
);
// Open the menu so we can look for state changes reflected in the menu.
await tester.tapAt(const Offset(100, 200), buttons: kSecondaryButton);
await tester.pump();
expect(find.text(example.MenuEntry.showMessage.label), findsOneWidget);
expect(find.text(example.MenuEntry.hideMessage.label), findsNothing);
expect(find.text(example.ContextMenuApp.kMessage), findsNothing);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyS);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
// Need to pump twice because of the one frame delay in the notification to
// update the overlay entry.
await tester.pump();
expect(find.text(example.MenuEntry.showMessage.label), findsNothing);
expect(find.text(example.MenuEntry.hideMessage.label), findsOneWidget);
expect(find.text(example.ContextMenuApp.kMessage), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyS);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
await tester.pump();
expect(find.text(example.MenuEntry.showMessage.label), findsOneWidget);
expect(find.text(example.MenuEntry.hideMessage.label), findsNothing);
expect(find.text(example.ContextMenuApp.kMessage), findsNothing);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyR);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('Last Selected: ${example.MenuEntry.colorRed.label}'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyG);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('Last Selected: ${example.MenuEntry.colorGreen.label}'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyB);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('Last Selected: ${example.MenuEntry.colorBlue.label}'), findsOneWidget);
});
}
| flutter/examples/api/test/material/menu_anchor/menu_anchor.1_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/menu_anchor/menu_anchor.1_test.dart",
"repo_id": "flutter",
"token_count": 2031
} | 595 |
// 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_api_samples/material/popup_menu/popup_menu.2.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Popup animation can be customized using AnimationStyle', (WidgetTester tester) async {
await tester.pumpWidget(
const example.PopupMenuApp(),
);
// Test the default popup animation.
await tester.tap(find.byIcon(Icons.more_vert));
await tester.pump();
// Advance the animation by half of the default duration.
await tester.pump(const Duration(milliseconds: 100));
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(224.0, 130.0)));
// Let the animation finish.
await tester.pumpAndSettle();
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(224.0, 312.0)));
// Tap outside the popup menu to close it.
await tester.tapAt(const Offset(1, 1));
await tester.pumpAndSettle();
// Test the custom animation curve and duration.
await tester.tap(find.text('Custom'));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.more_vert));
await tester.pump();
// Advance the animation by one third of the custom duration.
await tester.pump(const Duration(milliseconds: 1000));
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(224.0, 312.0)));
// Let the animation finish.
await tester.pumpAndSettle();
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(224.0, 312.0)));
// Tap outside the popup menu to close it.
await tester.tapAt(const Offset(1, 1));
await tester.pumpAndSettle();
// Test the no animation style.
await tester.tap(find.text('None'));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.more_vert));
// Advance the animation by only one frame.
await tester.pump();
// The popup menu is shown immediately.
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(224.0, 312.0)));
});
}
| flutter/examples/api/test/material/popup_menu/popup_menu.2_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/popup_menu/popup_menu.2_test.dart",
"repo_id": "flutter",
"token_count": 823
} | 596 |
// 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_api_samples/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
Future<void> longPressDrag(WidgetTester tester, Offset start, Offset end) async {
final TestGesture drag = await tester.startGesture(start);
await tester.pump(kLongPressTimeout + kPressTimeout);
await drag.moveTo(end);
await tester.pump(kPressTimeout);
await drag.up();
}
testWidgets('Reorder list item', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: example.ReorderableApp(),
),
);
expect(tester.getCenter(find.text('Item 3')).dy, 280.0);
await longPressDrag(
tester,
tester.getCenter(find.text('Item 3')),
tester.getCenter(find.text('Item 2')),
);
await tester.pumpAndSettle();
expect(tester.getCenter(find.text('Item 3')).dy, 216.0);
});
}
| flutter/examples/api/test/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0_test.dart",
"repo_id": "flutter",
"token_count": 457
} | 597 |
// 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_api_samples/material/toggle_buttons/toggle_buttons.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Single-select ToggleButtons', (WidgetTester tester) async {
TextButton findButton(String text) {
return tester.widget<TextButton>(find.widgetWithText(TextButton, text));
}
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: example.ToggleButtonsExampleApp(),
),
),
);
TextButton firstButton = findButton('Apple');
TextButton secondButton = findButton('Banana');
TextButton thirdButton = findButton('Orange');
const Color selectedColor = Color(0xffef9a9a);
const Color unselectedColor = Color(0x00fef7ff);
/// First button is selected.
expect(firstButton.style!.backgroundColor!.resolve(enabled), selectedColor);
expect(secondButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
expect(thirdButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
/// Tap on second button.
await tester.tap(find.widgetWithText(TextButton, 'Banana'));
await tester.pumpAndSettle();
firstButton = findButton('Apple');
secondButton = findButton('Banana');
thirdButton = findButton('Orange');
/// Only second button is selected.
expect(firstButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
expect(secondButton.style!.backgroundColor!.resolve(enabled), selectedColor);
expect(thirdButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
});
testWidgets('Multi-select ToggleButtons', (WidgetTester tester) async {
TextButton findButton(String text) {
return tester.widget<TextButton>(find.widgetWithText(TextButton, text));
}
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: example.ToggleButtonsExampleApp(),
),
),
);
TextButton firstButton = findButton('Tomatoes');
TextButton secondButton = findButton('Potatoes');
TextButton thirdButton = findButton('Carrots');
const Color selectedColor = Color(0xffa5d6a7);
const Color unselectedColor = Color(0x00fef7ff);
/// Second button is selected.
expect(firstButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
expect(secondButton.style!.backgroundColor!.resolve(enabled), selectedColor);
expect(thirdButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
/// Tap on other two buttons.
await tester.tap(find.widgetWithText(TextButton, 'Tomatoes'));
await tester.tap(find.widgetWithText(TextButton, 'Carrots'));
await tester.pumpAndSettle();
firstButton = findButton('Tomatoes');
secondButton = findButton('Potatoes');
thirdButton = findButton('Carrots');
/// All buttons are selected.
expect(firstButton.style!.backgroundColor!.resolve(enabled), selectedColor);
expect(secondButton.style!.backgroundColor!.resolve(enabled), selectedColor);
expect(thirdButton.style!.backgroundColor!.resolve(enabled), selectedColor);
});
testWidgets('Icon-only ToggleButtons', (WidgetTester tester) async {
TextButton findButton(IconData iconData) {
return tester.widget<TextButton>(find.widgetWithIcon(TextButton, iconData));
}
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: example.ToggleButtonsExampleApp(),
),
),
);
TextButton firstButton = findButton(Icons.sunny);
TextButton secondButton = findButton(Icons.cloud);
TextButton thirdButton = findButton(Icons.ac_unit);
const Color selectedColor = Color(0xff90caf9);
const Color unselectedColor = Color(0x00fef7ff);
/// Third button is selected.
expect(firstButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
expect(secondButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
expect(thirdButton.style!.backgroundColor!.resolve(enabled), selectedColor);
/// Tap on the first button.
await tester.tap(find.widgetWithIcon(TextButton, Icons.sunny));
await tester.pumpAndSettle();
firstButton = findButton(Icons.sunny);
secondButton = findButton(Icons.cloud);
thirdButton = findButton(Icons.ac_unit);
/// First button os selected.
expect(firstButton.style!.backgroundColor!.resolve(enabled), selectedColor);
expect(secondButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
expect(thirdButton.style!.backgroundColor!.resolve(enabled), unselectedColor);
});
}
Set<MaterialState> enabled = <MaterialState>{ };
| flutter/examples/api/test/material/toggle_buttons/toggle_buttons.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/toggle_buttons/toggle_buttons.0_test.dart",
"repo_id": "flutter",
"token_count": 1599
} | 598 |
// 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_api_samples/ui/text/font_feature.font_feature_swash.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('shows font features', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: example.ExampleWidget(),
),
);
expect(find.byType(Text), findsOneWidget);
expect((tester.widget(find.byType(Text).first) as Text).style!.fontFamily, equals('BioRhyme Expanded'));
expect(
(tester.widget(find.byType(Text).first) as Text).style!.fontFeatures,
equals(const <FontFeature>[FontFeature.swash()]),
);
});
}
| flutter/examples/api/test/ui/text/font_feature.font_feature_swash.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/ui/text/font_feature.font_feature_swash.0_test.dart",
"repo_id": "flutter",
"token_count": 304
} | 599 |
// 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_api_samples/widgets/basic/expanded.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Expanded widget in a Column', (WidgetTester tester) async {
const double totalHeight = 600;
const double appBarHeight = 56.0;
const double columnWidth = 100.0;
const double columnHeight = totalHeight - appBarHeight;
const double containerOneHeight = 100;
const double containerTwoHeight = columnHeight - 200;
const double containerThreeHeight = 100;
await tester.pumpWidget(
const example.ExpandedApp(),
);
final Size column = tester.getSize(find.byType(Column));
expect(column, const Size(columnWidth, columnHeight));
final Size containerOne = tester.getSize(find.byType(Container).at(0));
expect(containerOne, const Size(columnWidth, containerOneHeight));
// This Container is wrapped in an Expanded widget, so it should take up
// the remaining space in the Column.
final Size containerTwo = tester.getSize(find.byType(Container).at(1));
expect(containerTwo, const Size(columnWidth, containerTwoHeight));
final Size containerThree = tester.getSize(find.byType(Container).at(2));
expect(containerThree, const Size(columnWidth, containerThreeHeight));
});
}
| flutter/examples/api/test/widgets/basic/expanded.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/basic/expanded.0_test.dart",
"repo_id": "flutter",
"token_count": 464
} | 600 |
// 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 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_api_samples/widgets/editable_text/editable_text.on_content_inserted.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Image.memory displays inserted content', (WidgetTester tester) async {
await tester.pumpWidget(
const example.KeyboardInsertedContentApp(),
);
expect(find.text('Keyboard Inserted Content Sample'), findsOneWidget);
await tester.tap(find.byType(EditableText));
await tester.enterText(find.byType(EditableText), 'test');
await tester.idle();
const String uri = 'content://com.google.android.inputmethod.latin.fileprovider/test.png';
const List<int> kBlueSquarePng = <int>[
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49,
0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x32, 0x08, 0x06,
0x00, 0x00, 0x00, 0x1e, 0x3f, 0x88, 0xb1, 0x00, 0x00, 0x00, 0x48, 0x49, 0x44,
0x41, 0x54, 0x78, 0xda, 0xed, 0xcf, 0x31, 0x0d, 0x00, 0x30, 0x08, 0x00, 0xb0,
0x61, 0x63, 0x2f, 0xfe, 0x2d, 0x61, 0x05, 0x34, 0xf0, 0x92, 0xd6, 0x41, 0x23,
0x7f, 0xf5, 0x3b, 0x20, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x36, 0x06, 0x03, 0x6e, 0x69, 0x47, 0x12, 0x8e, 0xea, 0xaa,
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
-1,
'TextInputAction.commitContent',
jsonDecode('{"mimeType": "image/png", "data": $kBlueSquarePng, "uri": "$uri"}'),
],
'method': 'TextInputClient.performAction',
});
try {
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
} catch (_) {}
await tester.pumpAndSettle();
expect(find.byType(Image), findsOneWidget);
});
}
| flutter/examples/api/test/widgets/editable_text/editable_text.on_content_inserted.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/editable_text/editable_text.on_content_inserted.0_test.dart",
"repo_id": "flutter",
"token_count": 1182
} | 601 |
// 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_api_samples/widgets/overlay/overlay.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Can use Overlay to highlight NavigationBar destination', (WidgetTester tester) async {
const String explorePage = 'Explore page';
const String commutePage = 'Commute page';
const String savedPage = 'Saved page';
await tester.pumpWidget(
const example.OverlayApp(),
);
expect(find.text(explorePage), findsNothing);
expect(find.text(commutePage), findsNothing);
expect(find.text(savedPage), findsNothing);
await tester.tap(find.widgetWithText(ElevatedButton, 'Explore'));
await tester.pumpAndSettle();
expect(find.text(explorePage), findsOneWidget);
await tester.tap(find.widgetWithText(ElevatedButton, 'Commute'));
await tester.pumpAndSettle();
expect(find.text(commutePage), findsOneWidget);
await tester.tap(find.widgetWithText(ElevatedButton, 'Saved'));
await tester.pumpAndSettle();
expect(find.text(savedPage), findsOneWidget);
await tester.tap(find.widgetWithText(ElevatedButton, 'Remove Overlay'));
await tester.pumpAndSettle();
expect(find.text(explorePage), findsNothing);
expect(find.text(commutePage), findsNothing);
expect(find.text(savedPage), findsNothing);
});
}
| flutter/examples/api/test/widgets/overlay/overlay.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/overlay/overlay.0_test.dart",
"repo_id": "flutter",
"token_count": 527
} | 602 |
The Flutter Gallery sample application that used to live in
this /examples/ directory has moved, and is now located here:
https://github.com/flutter/gallery
| flutter/examples/flutter_gallery.readme/0 | {
"file_path": "flutter/examples/flutter_gallery.readme",
"repo_id": "flutter",
"token_count": 40
} | 603 |
<!-- 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. -->
<resources>
<string name="app_name">Flutter View</string>
<string name="title">Flutter Application</string>
<string name="button_tap">Flutter button tapped 0 times.</string>
<string name="android">Android</string>
</resources>
| flutter/examples/flutter_view/android/app/src/main/res/values/strings.xml/0 | {
"file_path": "flutter/examples/flutter_view/android/app/src/main/res/values/strings.xml",
"repo_id": "flutter",
"token_count": 111
} | 604 |
#include "Generated.xcconfig"
| flutter/examples/image_list/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "flutter/examples/image_list/ios/Flutter/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 605 |
// 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 example shows how to use process input events in the underlying render
// tree.
import 'package:flutter/material.dart'; // Imported just for its color palette.
import 'package:flutter/rendering.dart';
import 'src/binding.dart';
// Material design colors. :p
List<Color> _kColors = <Color>[
Colors.teal,
Colors.amber,
Colors.purple,
Colors.lightBlue,
Colors.deepPurple,
Colors.lime,
];
/// A simple model object for a dot that reacts to pointer pressure.
class Dot {
Dot({ required Color color }) : _paint = Paint()..color = color;
final Paint _paint;
Offset position = Offset.zero;
double radius = 0.0;
void update(PointerEvent event) {
position = event.position;
radius = 5 + (95 * event.pressure);
}
void paint(Canvas canvas, Offset offset) {
canvas.drawCircle(position + offset, radius, _paint);
}
}
/// A render object that draws dots under each pointer.
class RenderDots extends RenderBox {
RenderDots();
/// State to remember which dots to paint.
final Map<int, Dot> _dots = <int, Dot>{};
/// Indicates that the size of this render object depends only on the
/// layout constraints provided by the parent.
@override
bool get sizedByParent => true;
/// By selecting the biggest value permitted by the incoming constraints
/// during layout, this function makes this render object as large as
/// possible (i.e., fills the entire screen).
@override
void performResize() {
size = constraints.biggest;
}
/// Makes this render object hittable so that it receives pointer events.
@override
bool hitTestSelf(Offset position) => true;
/// Processes pointer events by mutating state and invalidating its previous
/// painting commands.
@override
void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
if (event is PointerDownEvent) {
final Color color = _kColors[event.pointer.remainder(_kColors.length)];
_dots[event.pointer] = Dot(color: color)..update(event);
// We call markNeedsPaint to indicate that our painting commands have
// changed and that paint needs to be called before displaying a new frame
// to the user. It's harmless to call markNeedsPaint multiple times
// because the render tree will ignore redundant calls.
markNeedsPaint();
} else if (event is PointerUpEvent || event is PointerCancelEvent) {
_dots.remove(event.pointer);
markNeedsPaint();
} else if (event is PointerMoveEvent) {
_dots[event.pointer]!.update(event);
markNeedsPaint();
}
}
/// Issues new painting commands.
@override
void paint(PaintingContext context, Offset offset) {
final Canvas canvas = context.canvas;
// The "size" property indicates the size of that this render box was
// allotted during layout. Here we paint our bounds white. Notice that we're
// located at "offset" from the origin of the canvas' coordinate system.
// Passing offset during the render tree's paint walk is an optimization to
// avoid having to change the origin of the canvas's coordinate system too
// often.
canvas.drawRect(offset & size, Paint()..color = const Color(0xFFFFFFFF));
// We iterate through our model and paint each dot.
for (final Dot dot in _dots.values) {
dot.paint(canvas, offset);
}
}
}
void main() {
// Create some styled text to tell the user to interact with the app.
final RenderParagraph paragraph = RenderParagraph(
const TextSpan(
style: TextStyle(color: Colors.black87),
text: 'Touch me!',
),
textDirection: TextDirection.ltr,
);
// A stack is a render object that layers its children on top of each other.
// The bottom later is our RenderDots object, and on top of that we show the
// text.
final RenderStack stack = RenderStack(
textDirection: TextDirection.ltr,
children: <RenderBox>[
RenderDots(),
paragraph,
],
);
// The "parentData" field of a render object is controlled by the render
// object's parent render object. Now that we've added the paragraph as a
// child of the RenderStack, the paragraph's parentData field has been
// populated with a StackParentData, which we can use to provide input to the
// stack's layout algorithm.
//
// We use the StackParentData of the paragraph to position the text in the top
// left corner of the screen.
final StackParentData paragraphParentData = paragraph.parentData! as StackParentData;
paragraphParentData
..top = 40.0
..left = 20.0;
// Finally, we attach the render tree we've built to the screen.
ViewRenderingFlutterBinding(root: stack).scheduleFrame();
}
| flutter/examples/layers/rendering/touch_input.dart/0 | {
"file_path": "flutter/examples/layers/rendering/touch_input.dart",
"repo_id": "flutter",
"token_count": 1466
} | 606 |
// 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';
class AdaptedListItem extends StatelessWidget {
const AdaptedListItem({ super.key, required this.name });
final String name;
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Container(
width: 32.0,
height: 32.0,
margin: const EdgeInsets.all(8.0),
color: Colors.lightBlueAccent.shade100,
),
Text(name),
],
);
}
}
class AdaptedGridItem extends StatelessWidget {
const AdaptedGridItem({ super.key, required this.name });
final String name;
@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: <Widget>[
Expanded(
child: Container(
color: Colors.lightBlueAccent.shade100,
),
),
Container(
margin: const EdgeInsets.only(left: 8.0),
child: Row(
children: <Widget>[
Expanded(
child: Text(name),
),
const IconButton(
icon: Icon(Icons.more_vert),
onPressed: null,
),
],
),
),
],
),
);
}
}
const double _kListItemExtent = 50.0;
const double _kMaxTileWidth = 150.0;
const double _kGridViewBreakpoint = 450.0;
class AdaptiveContainer extends StatelessWidget {
const AdaptiveContainer({ super.key, required this.names });
final List<String> names;
@override
Widget build(BuildContext context) {
if (MediaQuery.of(context).size.width < _kGridViewBreakpoint) {
return ListView(
itemExtent: _kListItemExtent,
children: names.map<Widget>((String name) => AdaptedListItem(name: name)).toList(),
);
} else {
return GridView.extent(
maxCrossAxisExtent: _kMaxTileWidth,
children: names.map<Widget>((String name) => AdaptedGridItem(name: name)).toList(),
);
}
}
}
List<String> _initNames() => List<String>.generate(30, (int i) => 'Item $i');
final List<String> _kNames = _initNames();
void main() {
runApp(MaterialApp(
title: 'Media Query Example',
home: Scaffold(
appBar: AppBar(
title: const Text('Media Query Example'),
),
body: Material(child: AdaptiveContainer(names: _kNames)),
),
));
}
| flutter/examples/layers/widgets/media_query.dart/0 | {
"file_path": "flutter/examples/layers/widgets/media_query.dart",
"repo_id": "flutter",
"token_count": 1127
} | 607 |
#include "Generated.xcconfig"
| flutter/examples/platform_channel/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "flutter/examples/platform_channel/ios/Flutter/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 608 |
// 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.
package io.flutter.examples.platform_view;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class CountActivity extends AppCompatActivity {
public static final String EXTRA_COUNTER = "counter";
private int counter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.android_full_screen_layout);
Toolbar myToolbar = findViewById(R.id.my_toolbar);
myToolbar.setTitle("Platform View");
setSupportActionBar(myToolbar);
counter = getIntent().getIntExtra(EXTRA_COUNTER, 0);
updateText();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter++;
updateText();
}
});
Button switchViewButton = findViewById(R.id.button);
switchViewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
returnToFlutterView();
}
});
}
private void updateText() {
TextView textView = findViewById(R.id.button_tap);
String value = "Button tapped " + counter + (counter == 1 ? " time" : " times");
textView.setText(value);
}
private void returnToFlutterView() {
Intent returnIntent = new Intent();
returnIntent.putExtra(EXTRA_COUNTER, counter);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
public void onBackPressed() {
returnToFlutterView();
}
}
| flutter/examples/platform_view/android/app/src/main/java/io/flutter/examples/platform_view/CountActivity.java/0 | {
"file_path": "flutter/examples/platform_view/android/app/src/main/java/io/flutter/examples/platform_view/CountActivity.java",
"repo_id": "flutter",
"token_count": 673
} | 609 |
# Flutter
Flutter is a new way to build high-performance, cross-platform mobile, web,
and desktop apps. Flutter is optimized for today's — and tomorrow's — mobile
and desktop devices. We are focused on low-latency input and high frame rates
on all platforms.
See the [getting started guide](https://flutter.dev/getting-started/) for
information about using Flutter.
| flutter/packages/flutter/README.md/0 | {
"file_path": "flutter/packages/flutter/README.md",
"repo_id": "flutter",
"token_count": 94
} | 610 |
# 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/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.
# * Fixes in this file are for the ThemeData class from the Material library. *
# For fixes to
# * AppBar: fix_app_bar.yaml
# * AppBarTheme: fix_app_bar_theme.yaml
# * ColorScheme: fix_color_scheme.yaml
# * Material (general): fix_material.yaml
# * SliverAppBar: fix_sliver_app_bar.yaml
# * TextTheme: fix_text_theme.yaml
# * WidgetState: fix_widget_state.yaml
version: 1
transforms:
# Changes made in https://github.com/flutter/flutter/pull/87281
- title: "Remove 'fixTextFieldOutlineLabel'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'fixTextFieldOutlineLabel'
# Changes made in https://github.com/flutter/flutter/pull/87281
- title: "Remove 'fixTextFieldOutlineLabel'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'fixTextFieldOutlineLabel'
# Changes made in https://github.com/flutter/flutter/pull/87281
- title: "Remove 'fixTextFieldOutlineLabel'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'fixTextFieldOutlineLabel'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'buttonColor'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'buttonColor'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'buttonColor'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'buttonColor'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'buttonColor'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'buttonColor'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'accentIconTheme'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'accentIconTheme'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'accentIconTheme'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'accentIconTheme'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'accentIconTheme'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'accentIconTheme'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'accentTextTheme'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'accentTextTheme'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'accentTextTheme'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'accentTextTheme'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'accentTextTheme'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'accentTextTheme'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'accentColorBrightness'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'accentColorBrightness'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'accentColorBrightness'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'accentColorBrightness'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Remove 'accentColorBrightness'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'accentColorBrightness'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Migrate to 'ColorScheme.secondary'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
field: 'accentColor'
inClass: 'ThemeData'
changes:
- kind: 'rename'
newName: 'colorScheme.secondary'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Migrate to 'ColorScheme.secondary'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
oneOf:
- if: "accentColor != '' && primarySwatch == '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch().copyWith(secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch == '' && colorScheme ==''"
- kind: 'removeParameter'
name: 'accentColor'
- if: "accentColor != '' && primarySwatch != '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch(primarySwatch: {% primarySwatch %}).copyWith(secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch != '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'accentColor'
- kind: 'removeParameter'
name: 'primarySwatch'
- if: "accentColor != '' && primarySwatch == '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch == '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'accentColor'
- if: "accentColor != '' && primarySwatch != '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(primarySwatch: {% primarySwatch %}, secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch != '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'accentColor'
- kind: 'removeParameter'
name: 'primarySwatch'
variables:
accentColor:
kind: 'fragment'
value: 'arguments[accentColor]'
primarySwatch:
kind: 'fragment'
value: 'arguments[primarySwatch]'
colorScheme:
kind: 'fragment'
value: 'arguments[colorScheme]'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Migrate to 'ColorScheme.secondary'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
oneOf:
- if: "accentColor != '' && primarySwatch == '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch().copyWith(secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch == '' && colorScheme ==''"
- kind: 'removeParameter'
name: 'accentColor'
- if: "accentColor != '' && primarySwatch != '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch(primarySwatch: {% primarySwatch %}).copyWith(secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch != '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'accentColor'
- kind: 'removeParameter'
name: 'primarySwatch'
- if: "accentColor != '' && primarySwatch == '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch == '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'accentColor'
- if: "accentColor != '' && primarySwatch != '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(primarySwatch: {% primarySwatch %}, secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch != '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'accentColor'
- kind: 'removeParameter'
name: 'primarySwatch'
variables:
accentColor:
kind: 'fragment'
value: 'arguments[accentColor]'
primarySwatch:
kind: 'fragment'
value: 'arguments[primarySwatch]'
colorScheme:
kind: 'fragment'
value: 'arguments[colorScheme]'
# Changes made in https://github.com/flutter/flutter/pull/81336
- title: "Migrate to 'ColorScheme.secondary'"
date: 2021-04-30
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
oneOf:
- if: "accentColor != '' && primarySwatch == '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch().copyWith(secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch == '' && colorScheme ==''"
- kind: 'removeParameter'
name: 'accentColor'
- if: "accentColor != '' && primarySwatch != '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch(primarySwatch: {% primarySwatch %}).copyWith(secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch != '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'accentColor'
- kind: 'removeParameter'
name: 'primarySwatch'
- if: "accentColor != '' && primarySwatch == '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch == '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'accentColor'
- if: "accentColor != '' && primarySwatch != '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(primarySwatch: {% primarySwatch %}, secondary: {% accentColor %})'
requiredIf: "accentColor != '' && primarySwatch != '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'accentColor'
- kind: 'removeParameter'
name: 'primarySwatch'
variables:
accentColor:
kind: 'fragment'
value: 'arguments[accentColor]'
primarySwatch:
kind: 'fragment'
value: 'arguments[primarySwatch]'
colorScheme:
kind: 'fragment'
value: 'arguments[colorScheme]'
# Changes made in https://github.com/flutter/flutter/pull/93396
- title: "Remove 'primaryColorBrightness'"
date: 2021-11-11
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'primaryColorBrightness'
# Changes made in https://github.com/flutter/flutter/pull/93396
- title: "Remove 'primaryColorBrightness'"
date: 2021-11-11
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'primaryColorBrightness'
# Changes made in https://github.com/flutter/flutter/pull/93396
- title: "Remove 'primaryColorBrightness'"
date: 2021-11-11
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'primaryColorBrightness'
# Changes made in https://github.com/flutter/flutter/pull/66482
- title: "Migrate to 'TextSelectionThemeData'"
date: 2020-09-24
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
oneOf:
- if: "textSelectionColor != '' && cursorColor != '' && textSelectionHandleColor != ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(cursorColor: {% cursorColor %}, selectionColor: {% textSelectionColor %}, selectionHandleColor: {% textSelectionHandleColor %},)'
requiredIf: "textSelectionColor != '' && cursorColor != '' && textSelectionHandleColor != ''"
- kind: 'removeParameter'
name: 'textSelectionColor'
- kind: 'removeParameter'
name: 'cursorColor'
- kind: 'removeParameter'
name: 'textSelectionHandleColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor == '' && cursorColor != '' && textSelectionHandleColor != ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(cursorColor: {% cursorColor %}, selectionHandleColor: {% textSelectionHandleColor %},)'
requiredIf: "textSelectionColor == '' && cursorColor != '' && textSelectionHandleColor != ''"
- kind: 'removeParameter'
name: 'cursorColor'
- kind: 'removeParameter'
name: 'textSelectionHandleColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor != '' && cursorColor != '' && textSelectionHandleColor == ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(cursorColor: {% cursorColor %}, selectionColor: {% textSelectionColor %},)'
requiredIf: "textSelectionColor != '' && cursorColor != '' && textSelectionHandleColor == ''"
- kind: 'removeParameter'
name: 'textSelectionColor'
- kind: 'removeParameter'
name: 'cursorColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor != '' && cursorColor == '' && textSelectionHandleColor != ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(selectionColor: {% textSelectionColor %}, selectionHandleColor: {% textSelectionHandleColor %},)'
requiredIf: "textSelectionColor != '' && cursorColor == '' && textSelectionHandleColor != ''"
- kind: 'removeParameter'
name: 'textSelectionColor'
- kind: 'removeParameter'
name: 'textSelectionHandleColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor == '' && cursorColor != '' && textSelectionHandleColor == ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(cursorColor: {% cursorColor %})'
requiredIf: "textSelectionColor == '' && cursorColor != '' && textSelectionHandleColor == ''"
- kind: 'removeParameter'
name: 'cursorColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor != '' && cursorColor == '' && textSelectionHandleColor == ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(selectionColor: {% textSelectionColor %})'
requiredIf: "textSelectionColor != '' && cursorColor == '' && textSelectionHandleColor == ''"
- kind: 'removeParameter'
name: 'textSelectionColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor == '' && cursorColor == '' && textSelectionHandleColor != ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(selectionHandleColor: {% textSelectionHandleColor %})'
requiredIf: "textSelectionColor == '' && cursorColor == '' && textSelectionHandleColor != ''"
- kind: 'removeParameter'
name: 'textSelectionHandleColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "useTextSelectionTheme != ''"
changes:
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
variables:
textSelectionColor:
kind: 'fragment'
value: 'arguments[textSelectionColor]'
cursorColor:
kind: 'fragment'
value: 'arguments[cursorColor]'
textSelectionHandleColor:
kind: 'fragment'
value: 'arguments[textSelectionHandleColor]'
useTextSelectionTheme:
kind: 'fragment'
value: 'arguments[useTextSelectionTheme]'
# Changes made in https://github.com/flutter/flutter/pull/66482
- title: "Migrate to 'TextSelectionThemeData'"
date: 2020-09-24
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
oneOf:
- if: "textSelectionColor != '' && cursorColor != '' && textSelectionHandleColor != ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(cursorColor: {% cursorColor %}, selectionColor: {% textSelectionColor %}, selectionHandleColor: {% textSelectionHandleColor %},)'
requiredIf: "textSelectionColor != '' && cursorColor != '' && textSelectionHandleColor != ''"
- kind: 'removeParameter'
name: 'textSelectionColor'
- kind: 'removeParameter'
name: 'cursorColor'
- kind: 'removeParameter'
name: 'textSelectionHandleColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor == '' && cursorColor != '' && textSelectionHandleColor != ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(cursorColor: {% cursorColor %}, selectionHandleColor: {% textSelectionHandleColor %},)'
requiredIf: "textSelectionColor == '' && cursorColor != '' && textSelectionHandleColor != ''"
- kind: 'removeParameter'
name: 'cursorColor'
- kind: 'removeParameter'
name: 'textSelectionHandleColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor != '' && cursorColor != '' && textSelectionHandleColor == ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(cursorColor: {% cursorColor %}, selectionColor: {% textSelectionColor %},)'
requiredIf: "textSelectionColor != '' && cursorColor != '' && textSelectionHandleColor == ''"
- kind: 'removeParameter'
name: 'textSelectionColor'
- kind: 'removeParameter'
name: 'cursorColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor != '' && cursorColor == '' && textSelectionHandleColor != ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(selectionColor: {% textSelectionColor %}, selectionHandleColor: {% textSelectionHandleColor %},)'
requiredIf: "textSelectionColor != '' && cursorColor == '' && textSelectionHandleColor != ''"
- kind: 'removeParameter'
name: 'textSelectionColor'
- kind: 'removeParameter'
name: 'textSelectionHandleColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor == '' && cursorColor != '' && textSelectionHandleColor == ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(cursorColor: {% cursorColor %})'
requiredIf: "textSelectionColor == '' && cursorColor != '' && textSelectionHandleColor == ''"
- kind: 'removeParameter'
name: 'cursorColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor != '' && cursorColor == '' && textSelectionHandleColor == ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(selectionColor: {% textSelectionColor %})'
requiredIf: "textSelectionColor != '' && cursorColor == '' && textSelectionHandleColor == ''"
- kind: 'removeParameter'
name: 'textSelectionColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "textSelectionColor == '' && cursorColor == '' && textSelectionHandleColor != ''"
changes:
- kind: 'addParameter'
index: 73
name: 'textSelectionTheme'
style: optional_named
argumentValue:
expression: 'TextSelectionThemeData(selectionHandleColor: {% textSelectionHandleColor %})'
requiredIf: "textSelectionColor == '' && cursorColor == '' && textSelectionHandleColor != ''"
- kind: 'removeParameter'
name: 'textSelectionHandleColor'
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
- if: "useTextSelectionTheme != ''"
changes:
- kind: 'removeParameter'
name: 'useTextSelectionTheme'
variables:
textSelectionColor:
kind: 'fragment'
value: 'arguments[textSelectionColor]'
cursorColor:
kind: 'fragment'
value: 'arguments[cursorColor]'
textSelectionHandleColor:
kind: 'fragment'
value: 'arguments[textSelectionHandleColor]'
useTextSelectionTheme:
kind: 'fragment'
value: 'arguments[useTextSelectionTheme]'
# Changes made in https://github.com/flutter/flutter/pull/109070
- title: "Remove 'selectedRowColor'"
date: 2022-08-05
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'selectedRowColor'
# Changes made in https://github.com/flutter/flutter/pull/109070
- title: "Remove 'selectedRowColor'"
date: 2022-08-05
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'selectedRowColor'
# Changes made in https://github.com/flutter/flutter/pull/109070
- title: "Remove 'selectedRowColor'"
date: 2022-08-05
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'selectedRowColor'
# Changes made in https://github.com/flutter/flutter/pull/97972/
- title: "Migrate 'ThemeData.toggleableActiveColor' to individual themes"
date: 2022-05-18
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'toggleableActiveColor'
- kind: 'addParameter'
index: 96
name: 'checkboxTheme'
style: optional_named
argumentValue:
expression: "CheckboxThemeData(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && checkboxTheme == ''"
- kind: 'addParameter'
index: 97
name: 'checkboxTheme'
style: optional_named
argumentValue:
expression: "{% checkboxTheme %}.copyWith(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && checkboxTheme != ''"
- kind: 'addParameter'
index: 98
name: 'radioTheme'
style: optional_named
argumentValue:
expression: "RadioThemeData(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && radioTheme == ''"
- kind: 'addParameter'
index: 99
name: 'radioTheme'
style: optional_named
argumentValue:
expression: "{% radioTheme %}.copyWith(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && radioTheme != ''"
- kind: 'addParameter'
index: 100
name: 'switchTheme'
style: optional_named
argumentValue:
expression: "SwitchThemeData(\n
thumbColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
trackColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && switchTheme == ''"
- kind: 'addParameter'
index: 101
name: 'switchTheme'
style: optional_named
argumentValue:
expression: "{% switchTheme %}.copyWith(\n
thumbColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
trackColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && switchTheme != ''"
variables:
checkboxTheme:
kind: 'fragment'
value: 'arguments[checkboxTheme]'
radioTheme:
kind: 'fragment'
value: 'arguments[radioTheme]'
switchTheme:
kind: 'fragment'
value: 'arguments[switchTheme]'
toggleableActiveColor:
kind: 'fragment'
value: 'arguments[toggleableActiveColor]'
# Changes made in https://github.com/flutter/flutter/pull/97972/
- title: "Migrate 'ThemeData.raw.toggleableActiveColor' to individual themes"
date: 2022-05-18
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'toggleableActiveColor'
- kind: 'addParameter'
index: 96
name: 'checkboxTheme'
style: optional_named
argumentValue:
expression: "CheckboxThemeData(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && checkboxTheme == ''"
- kind: 'addParameter'
index: 97
name: 'checkboxTheme'
style: optional_named
argumentValue:
expression: "{% checkboxTheme %}.copyWith(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && checkboxTheme != ''"
- kind: 'addParameter'
index: 98
name: 'radioTheme'
style: optional_named
argumentValue:
expression: "RadioThemeData(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && radioTheme == ''"
- kind: 'addParameter'
index: 99
name: 'radioTheme'
style: optional_named
argumentValue:
expression: "{% radioTheme %}.copyWith(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && radioTheme != ''"
- kind: 'addParameter'
index: 100
name: 'switchTheme'
style: optional_named
argumentValue:
expression: "SwitchThemeData(\n
thumbColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
trackColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && switchTheme == ''"
- kind: 'addParameter'
index: 101
name: 'switchTheme'
style: optional_named
argumentValue:
expression: "{% switchTheme %}.copyWith(\n
thumbColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
trackColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && switchTheme != ''"
variables:
checkboxTheme:
kind: 'fragment'
value: 'arguments[checkboxTheme]'
radioTheme:
kind: 'fragment'
value: 'arguments[radioTheme]'
switchTheme:
kind: 'fragment'
value: 'arguments[switchTheme]'
toggleableActiveColor:
kind: 'fragment'
value: 'arguments[toggleableActiveColor]'
# Changes made in https://github.com/flutter/flutter/pull/97972/
- title: "Migrate 'ThemeData.copyWith.toggleableActiveColor' to individual themes"
date: 2022-05-18
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'toggleableActiveColor'
- kind: 'addParameter'
index: 96
name: 'checkboxTheme'
style: optional_named
argumentValue:
expression: "CheckboxThemeData(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && checkboxTheme == ''"
- kind: 'addParameter'
index: 97
name: 'checkboxTheme'
style: optional_named
argumentValue:
expression: "{% checkboxTheme %}.copyWith(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && checkboxTheme != ''"
- kind: 'addParameter'
index: 98
name: 'radioTheme'
style: optional_named
argumentValue:
expression: "RadioThemeData(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && radioTheme == ''"
- kind: 'addParameter'
index: 99
name: 'radioTheme'
style: optional_named
argumentValue:
expression: "{% radioTheme %}.copyWith(\n
fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && radioTheme != ''"
- kind: 'addParameter'
index: 100
name: 'switchTheme'
style: optional_named
argumentValue:
expression: "SwitchThemeData(\n
thumbColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
trackColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && switchTheme == ''"
- kind: 'addParameter'
index: 101
name: 'switchTheme'
style: optional_named
argumentValue:
expression: "{% switchTheme %}.copyWith(\n
thumbColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
trackColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {\n
if (states.contains(MaterialState.disabled)) {
return null;
}\n
if (states.contains(MaterialState.selected)) {
return {% toggleableActiveColor %};
}\n
return null;\n
}),\n
)"
requiredIf: "toggleableActiveColor != '' && switchTheme != ''"
variables:
checkboxTheme:
kind: 'fragment'
value: 'arguments[checkboxTheme]'
radioTheme:
kind: 'fragment'
value: 'arguments[radioTheme]'
switchTheme:
kind: 'fragment'
value: 'arguments[switchTheme]'
toggleableActiveColor:
kind: 'fragment'
value: 'arguments[toggleableActiveColor]'
# Changes made in https://github.com/flutter/flutter/pull/111080
- title: "Migrate to 'BottomAppBarTheme.color'"
date: 2022-09-07
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
oneOf:
- if: "bottomAppBarColor != ''"
changes:
- kind: 'removeParameter'
name: 'bottomAppBarColor'
- kind: 'addParameter'
index: 73
name: 'bottomAppBarTheme'
style: optional_named
argumentValue:
expression: 'BottomAppBarTheme(color: {% bottomAppBarColor %})'
requiredIf: "bottomAppBarColor != ''"
variables:
bottomAppBarColor:
kind: 'fragment'
value: 'arguments[bottomAppBarColor]'
# Changes made in https://github.com/flutter/flutter/pull/111080
- title: "Migrate to 'BottomAppBarTheme.color'"
date: 2022-09-07
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
oneOf:
- if: "bottomAppBarColor != ''"
changes:
- kind: 'removeParameter'
name: 'bottomAppBarColor'
- kind: 'addParameter'
index: 73
name: 'bottomAppBarTheme'
style: optional_named
argumentValue:
expression: 'BottomAppBarTheme(color: {% bottomAppBarColor %})'
requiredIf: "bottomAppBarColor != ''"
variables:
bottomAppBarColor:
kind: 'fragment'
value: 'arguments[bottomAppBarColor]'
# Changes made in https://github.com/flutter/flutter/pull/111080
- title: "Migrate to 'BottomAppBarTheme.color'"
date: 2022-09-06
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
oneOf:
- if: "bottomAppBarColor != ''"
changes:
- kind: 'removeParameter'
name: 'bottomAppBarColor'
- kind: 'addParameter'
index: 73
name: 'bottomAppBarTheme'
style: optional_named
argumentValue:
expression: 'BottomAppBarTheme(color: {% bottomAppBarColor %})'
requiredIf: "bottomAppBarColor != ''"
variables:
bottomAppBarColor:
kind: 'fragment'
value: 'arguments[bottomAppBarColor]'
# Changes made in https://github.com/flutter/flutter/pull/110162
- title: "Migrate to 'ColorScheme.background'"
date: 2022-08-24
element:
uris: [ 'material.dart' ]
field: 'backgroundColor'
inClass: 'ThemeData'
changes:
- kind: 'rename'
newName: 'colorScheme.background'
# Changes made in https://github.com/flutter/flutter/pull/110162
- title: "Migrate to 'ColorScheme.background'"
date: 2022-08-24
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
oneOf:
- if: "backgroundColor != '' && primarySwatch == '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme(background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch == '' && colorScheme ==''"
- kind: 'removeParameter'
name: 'backgroundColor'
- if: "backgroundColor != '' && primarySwatch != '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch(primarySwatch: {% primarySwatch %}).copyWith(background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch != '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- kind: 'removeParameter'
name: 'primarySwatch'
- if: "backgroundColor != '' && primarySwatch == '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch == '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- if: "backgroundColor != '' && primarySwatch != '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(primarySwatch: {% primarySwatch %}, background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch != '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- kind: 'removeParameter'
name: 'primarySwatch'
variables:
backgroundColor:
kind: 'fragment'
value: 'arguments[backgroundColor]'
primarySwatch:
kind: 'fragment'
value: 'arguments[primarySwatch]'
colorScheme:
kind: 'fragment'
value: 'arguments[colorScheme]'
# Changes made in https://github.com/flutter/flutter/pull/110162
- title: "Migrate to 'ColorScheme.background'"
date: 2022-08-24
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
oneOf:
- if: "backgroundColor != '' && primarySwatch == '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme(background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch == '' && colorScheme ==''"
- kind: 'removeParameter'
name: 'backgroundColor'
- if: "backgroundColor != '' && primarySwatch != '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch(primarySwatch: {% primarySwatch %}).copyWith(background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch != '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- kind: 'removeParameter'
name: 'primarySwatch'
- if: "backgroundColor != '' && primarySwatch == '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch == '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- if: "backgroundColor != '' && primarySwatch != '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(primarySwatch: {% primarySwatch %}, background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch != '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- kind: 'removeParameter'
name: 'primarySwatch'
variables:
backgroundColor:
kind: 'fragment'
value: 'arguments[backgroundColor]'
primarySwatch:
kind: 'fragment'
value: 'arguments[primarySwatch]'
colorScheme:
kind: 'fragment'
value: 'arguments[colorScheme]'
# Changes made in https://github.com/flutter/flutter/pull/110162
- title: "Migrate to 'ColorScheme.background'"
date: 2022-08-24
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
oneOf:
- if: "backgroundColor != '' && primarySwatch == '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme(background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch == '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- if: "backgroundColor != '' && primarySwatch != '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch(primarySwatch: {% primarySwatch %}).copyWith(background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch != '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- kind: 'removeParameter'
name: 'primarySwatch'
- if: "backgroundColor != '' && primarySwatch == '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch == '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- if: "backgroundColor != '' && primarySwatch != '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(primarySwatch: {% primarySwatch %}, background: {% backgroundColor %})'
requiredIf: "backgroundColor != '' && primarySwatch != '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'backgroundColor'
- kind: 'removeParameter'
name: 'primarySwatch'
variables:
backgroundColor:
kind: 'fragment'
value: 'arguments[backgroundColor]'
primarySwatch:
kind: 'fragment'
value: 'arguments[primarySwatch]'
colorScheme:
kind: 'fragment'
value: 'arguments[colorScheme]'
# Changes made in https://github.com/flutter/flutter/pull/110162
- title: "Migrate to 'ColorScheme.error'"
date: 2022-08-24
element:
uris: [ 'material.dart' ]
field: 'errorColor'
inClass: 'ThemeData'
changes:
- kind: 'rename'
newName: 'colorScheme.error'
# Changes made in https://github.com/flutter/flutter/pull/110162
- title: "Migrate to 'ColorScheme.error'"
date: 2022-08-24
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
oneOf:
- if: "errorColor != '' && primarySwatch == '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme(error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch == '' && colorScheme ==''"
- kind: 'removeParameter'
name: 'errorColor'
- if: "errorColor != '' && primarySwatch != '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch(primarySwatch: {% primarySwatch %}).copyWith(error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch != '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'errorColor'
- kind: 'removeParameter'
name: 'primarySwatch'
- if: "errorColor != '' && primarySwatch == '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch == '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'errorColor'
- if: "errorColor != '' && primarySwatch != '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(primarySwatch: {% primarySwatch %}, error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch != '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'errorColor'
- kind: 'removeParameter'
name: 'primarySwatch'
variables:
errorColor:
kind: 'fragment'
value: 'arguments[errorColor]'
primarySwatch:
kind: 'fragment'
value: 'arguments[primarySwatch]'
colorScheme:
kind: 'fragment'
value: 'arguments[colorScheme]'
# Changes made in https://github.com/flutter/flutter/pull/110162
- title: "Migrate to 'ColorScheme.error'"
date: 2022-08-24
element:
uris: [ 'material.dart' ]
constructor: 'raw'
inClass: 'ThemeData'
oneOf:
- if: "errorColor != '' && primarySwatch == '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme(error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch == '' && colorScheme ==''"
- kind: 'removeParameter'
name: 'errorColor'
- if: "errorColor != '' && primarySwatch != '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch(primarySwatch: {% primarySwatch %}).copyWith(error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch != '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'errorColor'
- kind: 'removeParameter'
name: 'primarySwatch'
- if: "errorColor != '' && primarySwatch == '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch == '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'errorColor'
- if: "errorColor != '' && primarySwatch != '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(primarySwatch: {% primarySwatch %}, error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch != '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'errorColor'
- kind: 'removeParameter'
name: 'primarySwatch'
variables:
errorColor:
kind: 'fragment'
value: 'arguments[errorColor]'
primarySwatch:
kind: 'fragment'
value: 'arguments[primarySwatch]'
colorScheme:
kind: 'fragment'
value: 'arguments[colorScheme]'
# Changes made in https://github.com/flutter/flutter/pull/110162
- title: "Migrate to 'ColorScheme.error'"
date: 2022-08-24
element:
uris: [ 'material.dart' ]
constructor: ''
inClass: 'ThemeData'
oneOf:
- if: "errorColor != '' && primarySwatch == '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme(error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch == '' && colorScheme ==''"
- kind: 'removeParameter'
name: 'errorColor'
- if: "errorColor != '' && primarySwatch != '' && colorScheme == ''"
changes:
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: 'ColorScheme.fromSwatch(primarySwatch: {% primarySwatch %}).copyWith(error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch != '' && colorScheme == ''"
- kind: 'removeParameter'
name: 'errorColor'
- kind: 'removeParameter'
name: 'primarySwatch'
- if: "errorColor != '' && primarySwatch == '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch == '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'errorColor'
- if: "errorColor != '' && primarySwatch != '' && colorScheme != ''"
changes:
- kind: 'removeParameter'
name: 'colorScheme' # Remove to add back with modification
- kind: 'addParameter'
index: 56
name: 'colorScheme'
style: optional_named
argumentValue:
expression: '{% colorScheme %}.copyWith(primarySwatch: {% primarySwatch %}, error: {% errorColor %})'
requiredIf: "errorColor != '' && primarySwatch != '' && colorScheme != ''"
- kind: 'removeParameter'
name: 'errorColor'
- kind: 'removeParameter'
name: 'primarySwatch'
variables:
errorColor:
kind: 'fragment'
value: 'arguments[errorColor]'
primarySwatch:
kind: 'fragment'
value: 'arguments[primarySwatch]'
colorScheme:
kind: 'fragment'
value: 'arguments[colorScheme]'
# Changes made in https://github.com/flutter/flutter/pull/131455
- title: "Remove 'useMaterial3'"
date: 2023-07-27
element:
uris: [ 'material.dart' ]
method: 'copyWith'
inClass: 'ThemeData'
changes:
- kind: 'removeParameter'
name: 'useMaterial3'
# Before adding a new fix: read instructions at the top of this file.
| flutter/packages/flutter/lib/fix_data/fix_material/fix_theme_data.yaml/0 | {
"file_path": "flutter/packages/flutter/lib/fix_data/fix_material/fix_theme_data.yaml",
"repo_id": "flutter",
"token_count": 30245
} | 611 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// The Flutter gesture recognizers.
///
/// To use, import `package:flutter/gestures.dart`.
library gestures;
export 'src/gestures/arena.dart';
export 'src/gestures/binding.dart';
export 'src/gestures/constants.dart';
export 'src/gestures/converter.dart';
export 'src/gestures/debug.dart';
export 'src/gestures/drag.dart';
export 'src/gestures/drag_details.dart';
export 'src/gestures/eager.dart';
export 'src/gestures/events.dart';
export 'src/gestures/force_press.dart';
export 'src/gestures/gesture_settings.dart';
export 'src/gestures/hit_test.dart';
export 'src/gestures/long_press.dart';
export 'src/gestures/lsq_solver.dart';
export 'src/gestures/monodrag.dart';
export 'src/gestures/multidrag.dart';
export 'src/gestures/multitap.dart';
export 'src/gestures/pointer_router.dart';
export 'src/gestures/pointer_signal_resolver.dart';
export 'src/gestures/recognizer.dart';
export 'src/gestures/resampler.dart';
export 'src/gestures/scale.dart';
export 'src/gestures/tap.dart';
export 'src/gestures/tap_and_drag.dart';
export 'src/gestures/team.dart';
export 'src/gestures/velocity_tracker.dart';
| flutter/packages/flutter/lib/gestures.dart/0 | {
"file_path": "flutter/packages/flutter/lib/gestures.dart",
"repo_id": "flutter",
"token_count": 463
} | 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 'dart:math' as math;
import 'package:flutter/widgets.dart';
import 'colors.dart';
const double _kDefaultIndicatorRadius = 10.0;
// Extracted from iOS 13.2 Beta.
const Color _kActiveTickColor = CupertinoDynamicColor.withBrightness(
color: Color(0xFF3C3C44),
darkColor: Color(0xFFEBEBF5),
);
/// An iOS-style activity indicator that spins clockwise.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=AENVH-ZqKDQ}
///
/// {@tool dartpad}
/// This example shows how [CupertinoActivityIndicator] can be customized.
///
/// ** See code in examples/api/lib/cupertino/activity_indicator/cupertino_activity_indicator.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * <https://developer.apple.com/design/human-interface-guidelines/progress-indicators/>
class CupertinoActivityIndicator extends StatefulWidget {
/// Creates an iOS-style activity indicator that spins clockwise.
const CupertinoActivityIndicator({
super.key,
this.color,
this.animating = true,
this.radius = _kDefaultIndicatorRadius,
}) : assert(radius > 0.0),
progress = 1.0;
/// Creates a non-animated iOS-style activity indicator that displays
/// a partial count of ticks based on the value of [progress].
///
/// When provided, the value of [progress] must be between 0.0 (zero ticks
/// will be shown) and 1.0 (all ticks will be shown) inclusive. Defaults
/// to 1.0.
const CupertinoActivityIndicator.partiallyRevealed({
super.key,
this.color,
this.radius = _kDefaultIndicatorRadius,
this.progress = 1.0,
}) : assert(radius > 0.0),
assert(progress >= 0.0),
assert(progress <= 1.0),
animating = false;
/// Color of the activity indicator.
///
/// Defaults to color extracted from native iOS.
final Color? color;
/// Whether the activity indicator is running its animation.
///
/// Defaults to true.
final bool animating;
/// Radius of the spinner widget.
///
/// Defaults to 10 pixels. Must be positive.
final double radius;
/// Determines the percentage of spinner ticks that will be shown. Typical usage would
/// display all ticks, however, this allows for more fine-grained control such as
/// during pull-to-refresh when the drag-down action shows one tick at a time as
/// the user continues to drag down.
///
/// Defaults to one. Must be between zero and one, inclusive.
final double progress;
@override
State<CupertinoActivityIndicator> createState() => _CupertinoActivityIndicatorState();
}
class _CupertinoActivityIndicatorState extends State<CupertinoActivityIndicator>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 1),
vsync: this,
);
if (widget.animating) {
_controller.repeat();
}
}
@override
void didUpdateWidget(CupertinoActivityIndicator oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.animating != oldWidget.animating) {
if (widget.animating) {
_controller.repeat();
} else {
_controller.stop();
}
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SizedBox(
height: widget.radius * 2,
width: widget.radius * 2,
child: CustomPaint(
painter: _CupertinoActivityIndicatorPainter(
position: _controller,
activeColor: widget.color ?? CupertinoDynamicColor.resolve(_kActiveTickColor, context),
radius: widget.radius,
progress: widget.progress,
),
),
);
}
}
const double _kTwoPI = math.pi * 2.0;
/// Alpha values extracted from the native component (for both dark and light mode) to
/// draw the spinning ticks.
const List<int> _kAlphaValues = <int>[
47,
47,
47,
47,
72,
97,
122,
147,
];
/// The alpha value that is used to draw the partially revealed ticks.
const int _partiallyRevealedAlpha = 147;
class _CupertinoActivityIndicatorPainter extends CustomPainter {
_CupertinoActivityIndicatorPainter({
required this.position,
required this.activeColor,
required this.radius,
required this.progress,
}) : tickFundamentalRRect = RRect.fromLTRBXY(
-radius / _kDefaultIndicatorRadius,
-radius / 3.0,
radius / _kDefaultIndicatorRadius,
-radius,
radius / _kDefaultIndicatorRadius,
radius / _kDefaultIndicatorRadius,
),
super(repaint: position);
final Animation<double> position;
final Color activeColor;
final double radius;
final double progress;
final RRect tickFundamentalRRect;
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint();
final int tickCount = _kAlphaValues.length;
canvas.save();
canvas.translate(size.width / 2.0, size.height / 2.0);
final int activeTick = (tickCount * position.value).floor();
for (int i = 0; i < tickCount * progress; ++i) {
final int t = (i - activeTick) % tickCount;
paint.color = activeColor
.withAlpha(progress < 1 ? _partiallyRevealedAlpha : _kAlphaValues[t]);
canvas.drawRRect(tickFundamentalRRect, paint);
canvas.rotate(_kTwoPI / tickCount);
}
canvas.restore();
}
@override
bool shouldRepaint(_CupertinoActivityIndicatorPainter oldPainter) {
return oldPainter.position != position ||
oldPainter.activeColor != activeColor ||
oldPainter.progress != progress;
}
}
| flutter/packages/flutter/lib/src/cupertino/activity_indicator.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/activity_indicator.dart",
"repo_id": "flutter",
"token_count": 2025
} | 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 'colors.dart';
import 'theme.dart';
// Content padding determined via SwiftUI's `Form` view in the iOS 14.2 SDK.
const EdgeInsetsGeometry _kDefaultPadding =
EdgeInsetsDirectional.fromSTEB(20.0, 6.0, 6.0, 6.0);
/// An iOS-style form row.
///
/// Creates an iOS-style split form row with a standard prefix and child widget.
/// Also provides a space for error and helper widgets that appear underneath.
///
/// The [child] parameter is required. This widget is displayed at the end of
/// the row.
///
/// The [prefix] parameter is optional and is displayed at the start of the
/// row. Standard iOS guidelines encourage passing a [Text] widget to [prefix]
/// to detail the nature of the row's [child] widget.
///
/// The [padding] parameter is used to pad the contents of the row. It defaults
/// to the standard iOS padding. If no edge insets are intended, explicitly pass
/// [EdgeInsets.zero] to [padding].
///
/// The [helper] and [error] parameters are both optional widgets targeted at
/// displaying more information about the row. Both widgets are placed
/// underneath the [prefix] and [child], and will expand the row's height to
/// accommodate for their presence. When a [Text] is given to [error], it will
/// be shown in [CupertinoColors.destructiveRed] coloring and
/// medium-weighted font.
///
/// {@tool dartpad}
/// Creates a [CupertinoFormSection] containing a [CupertinoFormRow] with [prefix],
/// [child], [helper] and [error] specified.
///
/// ** See code in examples/api/lib/cupertino/form_row/cupertino_form_row.0.dart **
/// {@end-tool}
///
class CupertinoFormRow extends StatelessWidget {
/// Creates an iOS-style split form row with a standard prefix and child widget.
/// Also provides a space for error and helper widgets that appear underneath.
///
/// The [child] parameter is required. This widget is displayed at the end of
/// the row.
///
/// The [prefix] parameter is optional and is displayed at the start of the
/// row. Standard iOS guidelines encourage passing a [Text] widget to [prefix]
/// to detail the nature of the row's [child] widget.
///
/// The [padding] parameter is used to pad the contents of the row. It defaults
/// to the standard iOS padding. If no edge insets are intended, explicitly
/// pass [EdgeInsets.zero] to [padding].
///
/// The [helper] and [error] parameters are both optional widgets targeted at
/// displaying more information about the row. Both widgets are placed
/// underneath the [prefix] and [child], and will expand the row's height to
/// accommodate for their presence. When a [Text] is given to [error], it will
/// be shown in [CupertinoColors.destructiveRed] coloring and
/// medium-weighted font.
const CupertinoFormRow({
super.key,
required this.child,
this.prefix,
this.padding,
this.helper,
this.error,
});
/// A widget that is displayed at the start of the row.
///
/// The [prefix] parameter is displayed at the start of the row. Standard iOS
/// guidelines encourage passing a [Text] widget to [prefix] to detail the
/// nature of the row's [child] widget. If null, the [child] widget will take
/// up all horizontal space in the row.
final Widget? prefix;
/// Content padding for the row.
///
/// Defaults to the standard iOS padding for form rows. If no edge insets are
/// intended, explicitly pass [EdgeInsets.zero] to [padding].
final EdgeInsetsGeometry? padding;
/// A widget that is displayed underneath the [prefix] and [child] widgets.
///
/// The [helper] appears in primary label coloring, and is meant to inform the
/// user about interaction with the child widget. The row becomes taller in
/// order to display the [helper] widget underneath [prefix] and [child]. If
/// null, the row is shorter.
final Widget? helper;
/// A widget that is displayed underneath the [prefix] and [child] widgets.
///
/// The [error] widget is primarily used to inform users of input errors. When
/// a [Text] is given to [error], it will be shown in
/// [CupertinoColors.destructiveRed] coloring and medium-weighted font. The
/// row becomes taller in order to display the [helper] widget underneath
/// [prefix] and [child]. If null, the row is shorter.
final Widget? error;
/// Child widget.
///
/// The [child] widget is primarily used for input. It end-aligned and
/// horizontally flexible, taking up the entire space trailing past the
/// [prefix] widget.
final Widget child;
@override
Widget build(BuildContext context) {
final CupertinoThemeData theme = CupertinoTheme.of(context);
final TextStyle textStyle = theme.textTheme.textStyle.copyWith(
color: CupertinoDynamicColor.maybeResolve(theme.textTheme.textStyle.color, context)
);
return Padding(
padding: padding ?? _kDefaultPadding,
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
if (prefix != null)
DefaultTextStyle(
style: textStyle,
child: prefix!,
),
Flexible(
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: child,
),
),
],
),
if (helper != null)
Align(
alignment: AlignmentDirectional.centerStart,
child: DefaultTextStyle(
style: textStyle,
child: helper!,
),
),
if (error != null)
Align(
alignment: AlignmentDirectional.centerStart,
child: DefaultTextStyle(
style: const TextStyle(
color: CupertinoColors.destructiveRed,
fontWeight: FontWeight.w500,
),
child: error!,
),
),
],
),
);
}
}
| flutter/packages/flutter/lib/src/cupertino/form_row.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/form_row.dart",
"repo_id": "flutter",
"token_count": 2135
} | 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 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'button.dart';
import 'colors.dart';
import 'icons.dart';
import 'localizations.dart';
import 'text_field.dart';
export 'package:flutter/services.dart' show SmartDashesType, SmartQuotesType;
/// A [CupertinoTextField] that mimics the look and behavior of UIKit's
/// `UISearchTextField`.
///
/// This control defaults to showing the basic parts of a `UISearchTextField`,
/// like the 'Search' placeholder, prefix-ed Search icon, and suffix-ed
/// X-Mark icon.
///
/// To control the text that is displayed in the text field, use the
/// [controller]. For example, to set the initial value of the text field, use
/// a [controller] that already contains some text such as:
///
/// {@tool dartpad}
/// This examples shows how to provide initial text to a [CupertinoSearchTextField]
/// using the [controller] property.
///
/// ** See code in examples/api/lib/cupertino/search_field/cupertino_search_field.0.dart **
/// {@end-tool}
///
/// It is recommended to pass a [ValueChanged<String>] to both [onChanged] and
/// [onSubmitted] parameters in order to be notified once the value of the
/// field changes or is submitted by the keyboard:
///
/// {@tool dartpad}
/// This examples shows how to be notified of field changes or submitted text from
/// a [CupertinoSearchTextField].
///
/// ** See code in examples/api/lib/cupertino/search_field/cupertino_search_field.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * <https://developer.apple.com/design/human-interface-guidelines/ios/bars/search-bars/>
class CupertinoSearchTextField extends StatefulWidget {
/// Creates a [CupertinoTextField] that mimics the look and behavior of
/// UIKit's `UISearchTextField`.
///
/// Similar to [CupertinoTextField], to provide a prefilled text entry, pass
/// in a [TextEditingController] with an initial value to the [controller]
/// parameter.
///
/// The [onChanged] parameter takes a [ValueChanged<String>] which is invoked
/// upon a change in the text field's value.
///
/// The [onSubmitted] parameter takes a [ValueChanged<String>] which is
/// invoked when the keyboard submits.
///
/// To provide a hint placeholder text that appears when the text entry is
/// empty, pass a [String] to the [placeholder] parameter. This defaults to
/// 'Search'.
// TODO(DanielEdrisian): Localize the 'Search' placeholder.
///
/// The [style] and [placeholderStyle] properties allow changing the style of
/// the text and placeholder of the text field. [placeholderStyle] defaults
/// to the gray [CupertinoColors.secondaryLabel] iOS color.
///
/// To set the text field's background color and border radius, pass a
/// [BoxDecoration] to the [decoration] parameter. This defaults to the
/// default translucent tertiarySystemFill iOS color and 9 px corner radius.
// TODO(DanielEdrisian): Must make border radius continuous, see
// https://github.com/flutter/flutter/issues/13914.
///
/// The [itemColor] and [itemSize] properties allow changing the icon color
/// and icon size of the search icon (prefix) and X-Mark (suffix).
/// They default to [CupertinoColors.secondaryLabel] and `20.0`.
///
/// The [padding], [prefixInsets], and [suffixInsets] let you set the padding
/// insets for text, the search icon (prefix), and the X-Mark icon (suffix).
/// They default to values that replicate the `UISearchTextField` look. These
/// default fields were determined using the comparison tool in
/// https://github.com/flutter/platform_tests/.
///
/// To customize the prefix icon, pass a [Widget] to [prefixIcon]. This
/// defaults to the search icon.
///
/// To customize the suffix icon, pass an [Icon] to [suffixIcon]. This
/// defaults to the X-Mark.
///
/// To dictate when the X-Mark (suffix) should be visible, a.k.a. only on when
/// editing, not editing, on always, or on never, pass a
/// [OverlayVisibilityMode] to [suffixMode]. This defaults to only on when
/// editing.
///
/// To customize the X-Mark (suffix) action, pass a [VoidCallback] to
/// [onSuffixTap]. This defaults to clearing the text.
const CupertinoSearchTextField({
super.key,
this.controller,
this.onChanged,
this.onSubmitted,
this.style,
this.placeholder,
this.placeholderStyle,
this.decoration,
this.backgroundColor,
this.borderRadius,
this.keyboardType = TextInputType.text,
this.padding = const EdgeInsetsDirectional.fromSTEB(5.5, 8, 5.5, 8),
this.itemColor = CupertinoColors.secondaryLabel,
this.itemSize = 20.0,
this.prefixInsets = const EdgeInsetsDirectional.fromSTEB(6, 0, 0, 3),
this.prefixIcon = const Icon(CupertinoIcons.search),
this.suffixInsets = const EdgeInsetsDirectional.fromSTEB(0, 0, 5, 2),
this.suffixIcon = const Icon(CupertinoIcons.xmark_circle_fill),
this.suffixMode = OverlayVisibilityMode.editing,
this.onSuffixTap,
this.restorationId,
this.focusNode,
this.smartQuotesType,
this.smartDashesType,
this.enableIMEPersonalizedLearning = true,
this.autofocus = false,
this.onTap,
this.autocorrect = true,
this.enabled,
}) : assert(
!((decoration != null) && (backgroundColor != null)),
'Cannot provide both a background color and a decoration\n'
'To provide both, use "decoration: BoxDecoration(color: '
'backgroundColor)"',
),
assert(
!((decoration != null) && (borderRadius != null)),
'Cannot provide both a border radius and a decoration\n'
'To provide both, use "decoration: BoxDecoration(borderRadius: '
'borderRadius)"',
);
/// Controls the text being edited.
///
/// Similar to [CupertinoTextField], to provide a prefilled text entry, pass
/// in a [TextEditingController] with an initial value to the [controller]
/// parameter. Defaults to creating its own [TextEditingController].
final TextEditingController? controller;
/// Invoked upon user input.
final ValueChanged<String>? onChanged;
/// Invoked upon keyboard submission.
final ValueChanged<String>? onSubmitted;
/// Allows changing the style of the text.
///
/// Defaults to the gray [CupertinoColors.secondaryLabel] iOS color.
final TextStyle? style;
/// A hint placeholder text that appears when the text entry is empty.
///
/// Defaults to 'Search' localized in each supported language.
final String? placeholder;
/// Sets the style of the placeholder of the text field.
///
/// Defaults to the gray [CupertinoColors.secondaryLabel] iOS color.
final TextStyle? placeholderStyle;
/// Sets the decoration for the text field.
///
/// This property is automatically set using the [backgroundColor] and
/// [borderRadius] properties, which both have default values. Therefore,
/// [decoration] has a default value upon building the widget. It is designed
/// to mimic the look of a `UISearchTextField`.
final BoxDecoration? decoration;
/// Set the [decoration] property's background color.
///
/// Can't be set along with the [decoration]. Defaults to the translucent
/// [CupertinoColors.tertiarySystemFill] iOS color.
final Color? backgroundColor;
/// Sets the [decoration] property's border radius.
///
/// Can't be set along with the [decoration]. Defaults to 9 px circular
/// corner radius.
// TODO(DanielEdrisian): Must make border radius continuous, see
// https://github.com/flutter/flutter/issues/13914.
final BorderRadius? borderRadius;
/// The keyboard type for this search field.
///
/// Defaults to [TextInputType.text].
final TextInputType? keyboardType;
/// Sets the padding insets for the text and placeholder.
///
/// Defaults to padding that replicates the `UISearchTextField` look. The
/// inset values were determined using the comparison tool in
/// https://github.com/flutter/platform_tests/.
final EdgeInsetsGeometry padding;
/// Sets the color for the suffix and prefix icons.
///
/// Defaults to [CupertinoColors.secondaryLabel].
final Color itemColor;
/// Sets the base icon size for the suffix and prefix icons.
///
/// The size of the icon is scaled using the accessibility font scale
/// settings. Defaults to `20.0`.
final double itemSize;
/// Sets the padding insets for the suffix.
///
/// Defaults to padding that replicates the `UISearchTextField` suffix look.
/// The inset values were determined using the comparison tool in
/// https://github.com/flutter/platform_tests/.
final EdgeInsetsGeometry prefixInsets;
/// Sets a prefix widget.
///
/// Defaults to an [Icon] widget with the [CupertinoIcons.search] icon.
final Widget prefixIcon;
/// Sets the padding insets for the prefix.
///
/// Defaults to padding that replicates the `UISearchTextField` prefix look.
/// The inset values were determined using the comparison tool in
/// https://github.com/flutter/platform_tests/.
final EdgeInsetsGeometry suffixInsets;
/// Sets the suffix widget's icon.
///
/// Defaults to the X-Mark [CupertinoIcons.xmark_circle_fill]. "To change the
/// functionality of the suffix icon, provide a custom onSuffixTap callback
/// and specify an intuitive suffixIcon.
final Icon suffixIcon;
/// Dictates when the X-Mark (suffix) should be visible.
///
/// Defaults to only on when editing.
final OverlayVisibilityMode suffixMode;
/// Sets the X-Mark (suffix) action.
///
/// Defaults to clearing the text. The suffix action is customizable
/// so that users can override it with other functionality, that isn't
/// necessarily clearing text.
final VoidCallback? onSuffixTap;
/// {@macro flutter.material.textfield.restorationId}
final String? restorationId;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// {@macro flutter.widgets.editableText.autofocus}
final bool autofocus;
/// {@macro flutter.material.textfield.onTap}
final VoidCallback? onTap;
/// {@macro flutter.widgets.editableText.autocorrect}
final bool autocorrect;
/// Whether to allow the platform to automatically format quotes.
///
/// This flag only affects iOS, where it is equivalent to [`UITextSmartQuotesType`](https://developer.apple.com/documentation/uikit/uitextsmartquotestype?language=objc).
///
/// When set to [SmartQuotesType.enabled], it passes
/// [`UITextSmartQuotesTypeYes`](https://developer.apple.com/documentation/uikit/uitextsmartquotestype/uitextsmartquotestypeyes?language=objc),
/// and when set to [SmartQuotesType.disabled], it passes
/// [`UITextSmartQuotesTypeNo`](https://developer.apple.com/documentation/uikit/uitextsmartquotestype/uitextsmartquotestypeno?language=objc).
///
/// If set to null, [SmartQuotesType.enabled] will be used.
///
/// As an example of what this does, a standard vertical double quote
/// character will be automatically replaced by a left or right double quote
/// depending on its position in a word.
///
/// Defaults to null.
///
/// See also:
///
/// * [smartDashesType]
/// * <https://developer.apple.com/documentation/uikit/uitextinputtraits>
final SmartQuotesType? smartQuotesType;
/// Whether to allow the platform to automatically format dashes.
///
/// This flag only affects iOS versions 11 and above, where it is equivalent to [`UITextSmartDashesType`](https://developer.apple.com/documentation/uikit/uitextsmartdashestype?language=objc).
///
/// When set to [SmartDashesType.enabled], it passes
/// [`UITextSmartDashesTypeYes`](https://developer.apple.com/documentation/uikit/uitextsmartdashestype/uitextsmartdashestypeyes?language=objc),
/// and when set to [SmartDashesType.disabled], it passes
/// [`UITextSmartDashesTypeNo`](https://developer.apple.com/documentation/uikit/uitextsmartdashestype/uitextsmartdashestypeno?language=objc).
///
/// If set to null, [SmartDashesType.enabled] will be used.
///
/// As an example of what this does, two consecutive hyphen characters will be
/// automatically replaced with one en dash, and three consecutive hyphens
/// will become one em dash.
///
/// Defaults to null.
///
/// See also:
///
/// * [smartQuotesType]
/// * <https://developer.apple.com/documentation/uikit/uitextinputtraits>
final SmartDashesType? smartDashesType;
/// {@macro flutter.services.TextInputConfiguration.enableIMEPersonalizedLearning}
final bool enableIMEPersonalizedLearning;
/// Disables the text field when false.
///
/// Text fields in disabled states have a light grey background and don't
/// respond to touch events including the [prefixIcon] and [suffixIcon] button.
final bool? enabled;
@override
State<StatefulWidget> createState() => _CupertinoSearchTextFieldState();
}
class _CupertinoSearchTextFieldState extends State<CupertinoSearchTextField>
with RestorationMixin {
/// Default value for the border radius. Radius value was determined using the
/// comparison tool in https://github.com/flutter/platform_tests/.
final BorderRadius _kDefaultBorderRadius =
const BorderRadius.all(Radius.circular(9.0));
RestorableTextEditingController? _controller;
TextEditingController get _effectiveController =>
widget.controller ?? _controller!.value;
@override
void initState() {
super.initState();
if (widget.controller == null) {
_createLocalController();
}
}
@override
void didUpdateWidget(CupertinoSearchTextField oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller == null && oldWidget.controller != null) {
_createLocalController(oldWidget.controller!.value);
} else if (widget.controller != null && oldWidget.controller == null) {
unregisterFromRestoration(_controller!);
_controller!.dispose();
_controller = null;
}
}
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
if (_controller != null) {
_registerController();
}
}
@override
void dispose() {
super.dispose();
if (widget.controller == null) {
_controller?.dispose();
}
}
void _registerController() {
assert(_controller != null);
registerForRestoration(_controller!, 'controller');
}
void _createLocalController([TextEditingValue? value]) {
assert(_controller == null);
_controller = value == null
? RestorableTextEditingController()
: RestorableTextEditingController.fromValue(value);
if (!restorePending) {
_registerController();
}
}
@override
String? get restorationId => widget.restorationId;
void _defaultOnSuffixTap() {
final bool textChanged = _effectiveController.text.isNotEmpty;
_effectiveController.clear();
if (widget.onChanged != null && textChanged) {
widget.onChanged!(_effectiveController.text);
}
}
@override
Widget build(BuildContext context) {
final String placeholder = widget.placeholder ??
CupertinoLocalizations.of(context).searchTextFieldPlaceholderLabel;
final TextStyle placeholderStyle = widget.placeholderStyle ??
const TextStyle(color: CupertinoColors.systemGrey);
// The icon size will be scaled by a factor of the accessibility text scale,
// to follow the behavior of `UISearchTextField`.
final double scaledIconSize = MediaQuery.textScalerOf(context).scale(widget.itemSize);
// If decoration was not provided, create a decoration with the provided
// background color and border radius.
final BoxDecoration decoration = widget.decoration ??
BoxDecoration(
color: widget.backgroundColor ?? CupertinoColors.tertiarySystemFill,
borderRadius: widget.borderRadius ?? _kDefaultBorderRadius,
);
final IconThemeData iconThemeData = IconThemeData(
color: CupertinoDynamicColor.resolve(widget.itemColor, context),
size: scaledIconSize,
);
final Widget prefix = Padding(
padding: widget.prefixInsets,
child: IconTheme(
data: iconThemeData,
child: widget.prefixIcon,
),
);
final Widget suffix = Padding(
padding: widget.suffixInsets,
child: CupertinoButton(
onPressed: widget.onSuffixTap ?? _defaultOnSuffixTap,
minSize: 0,
padding: EdgeInsets.zero,
child: IconTheme(
data: iconThemeData,
child: widget.suffixIcon,
),
),
);
return CupertinoTextField(
controller: _effectiveController,
decoration: decoration,
style: widget.style,
prefix: prefix,
suffix: suffix,
keyboardType: widget.keyboardType,
onTap: widget.onTap,
enabled: widget.enabled ?? true,
suffixMode: widget.suffixMode,
placeholder: placeholder,
placeholderStyle: placeholderStyle,
padding: widget.padding,
onChanged: widget.onChanged,
onSubmitted: widget.onSubmitted,
focusNode: widget.focusNode,
autofocus: widget.autofocus,
autocorrect: widget.autocorrect,
smartQuotesType: widget.smartQuotesType,
smartDashesType: widget.smartDashesType,
enableIMEPersonalizedLearning: widget.enableIMEPersonalizedLearning,
textInputAction: TextInputAction.search,
);
}
}
| flutter/packages/flutter/lib/src/cupertino/search_field.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/search_field.dart",
"repo_id": "flutter",
"token_count": 5535
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
/// A mixin for [StatefulWidget]s that implements iOS-themed toggleable
/// controls (e.g.[CupertinoCheckbox]es).
///
/// This mixin implements the logic for toggling the control when tapped.
/// It does not have any opinion about the visual representation of the
/// toggleable widget. The visuals are defined by a [CustomPainter] passed to
/// the [buildToggleable]. [State] objects using this mixin should call that
/// method from their [build] method.
///
/// This mixin is used to implement the Cupertino components for
/// [CupertinoCheckbox] controls.
@optionalTypeArgs
mixin ToggleableStateMixin<S extends StatefulWidget> on TickerProviderStateMixin<S> {
/// Whether the [value] of this control can be changed by user interaction.
///
/// The control is considered interactive if the [onChanged] callback is
/// non-null. If the callback is null, then the control is disabled and
/// non-interactive. A disabled checkbox, for example, is displayed using a
/// grey color and its value cannot be changed.
bool get isInteractive => onChanged != null;
/// Called when the control changes value.
///
/// If the control is tapped, [onChanged] is called immediately with the new
/// value.
///
/// The control is considered interactive (see [isInteractive]) if this
/// callback is non-null. If the callback is null, then the control is
/// disabled and non-interactive. A disabled checkbox, for example, is
/// displayed using a grey color and its value cannot be changed.
ValueChanged<bool?>? get onChanged;
/// The [value] accessor returns false if this control is "inactive" (not
/// checked, off, or unselected).
///
/// If [value] is true then the control "active" (checked, on, or selected). If
/// tristate is true and value is null, then the control is considered to be
/// in its third or "indeterminate" state..
bool? get value;
/// If true, [value] can be true, false, or null, otherwise [value] must
/// be true or false.
///
/// When [tristate] is true and [value] is null, then the control is
/// considered to be in its third or "indeterminate" state.
bool get tristate;
/// The most recent [Offset] at which a pointer touched the Toggleable.
///
/// This is null if currently no pointer is touching the Toggleable or if
/// [isInteractive] is false.
Offset? get downPosition => _downPosition;
Offset? _downPosition;
void _handleTapDown(TapDownDetails details) {
if (isInteractive) {
setState(() {
_downPosition = details.localPosition;
});
}
}
void _handleTap([Intent? _]) {
if (!isInteractive) {
return;
}
switch (value) {
case false:
onChanged!(true);
case true:
onChanged!(tristate ? null : false);
case null:
onChanged!(false);
}
context.findRenderObject()!.sendSemanticsEvent(const TapSemanticEvent());
}
void _handleTapEnd([TapUpDetails? _]) {
if (_downPosition != null) {
setState(() { _downPosition = null; });
}
}
bool _focused = false;
void _handleFocusHighlightChanged(bool focused) {
if (focused != _focused) {
setState(() { _focused = focused; });
}
}
late final Map<Type, Action<Intent>> _actionMap = <Type, Action<Intent>>{
ActivateIntent: CallbackAction<ActivateIntent>(onInvoke: _handleTap),
};
/// Typically wraps a `painter` that draws the actual visuals of the
/// Toggleable with logic to toggle it.
///
/// Consider providing a subclass of [ToggleablePainter] as a `painter`.
///
/// This method must be called from the [build] method of the [State] class
/// that uses this mixin. The returned [Widget] must be returned from the
/// build method - potentially after wrapping it in other widgets.
Widget buildToggleable({
FocusNode? focusNode,
ValueChanged<bool>? onFocusChange,
bool autofocus = false,
required Size size,
required CustomPainter painter,
}) {
return FocusableActionDetector(
focusNode: focusNode,
autofocus: autofocus,
onFocusChange: onFocusChange,
enabled: isInteractive,
actions: _actionMap,
onShowFocusHighlight: _handleFocusHighlightChanged,
child: GestureDetector(
excludeFromSemantics: !isInteractive,
onTapDown: isInteractive ? _handleTapDown : null,
onTap: isInteractive ? _handleTap : null,
onTapUp: isInteractive ? _handleTapEnd : null,
onTapCancel: isInteractive ? _handleTapEnd : null,
child: Semantics(
enabled: isInteractive,
child: CustomPaint(
size: size,
painter: painter,
),
),
),
);
}
}
/// A base class for a [CustomPainter] that may be passed to
/// [ToggleableStateMixin.buildToggleable] to draw the visual representation of
/// a Toggleable.
///
/// Subclasses must implement the [paint] method to draw the actual visuals of
/// the Toggleable.
abstract class ToggleablePainter extends ChangeNotifier implements CustomPainter {
/// The color that should be used in the active state (i.e., when
/// [ToggleableStateMixin.value] is true).
///
/// For example, a checkbox should use this color when checked.
Color get activeColor => _activeColor!;
Color? _activeColor;
set activeColor(Color value) {
if (_activeColor == value) {
return;
}
_activeColor = value;
notifyListeners();
}
/// The color that should be used in the inactive state (i.e., when
/// [ToggleableStateMixin.value] is false).
///
/// For example, a checkbox should use this color when unchecked.
Color get inactiveColor => _inactiveColor!;
Color? _inactiveColor;
set inactiveColor(Color value) {
if (_inactiveColor == value) {
return;
}
_inactiveColor = value;
notifyListeners();
}
/// The color that should be used for the reaction when [isFocused] is true.
///
/// Used when the toggleable needs to change the reaction color/transparency,
/// when it has focus.
Color get focusColor => _focusColor!;
Color? _focusColor;
set focusColor(Color value) {
if (value == _focusColor) {
return;
}
_focusColor = value;
notifyListeners();
}
/// The [Offset] within the Toggleable at which a pointer touched the Toggleable.
///
/// This is null if currently no pointer is touching the Toggleable.
///
/// Usually set to [ToggleableStateMixin.downPosition].
Offset? get downPosition => _downPosition;
Offset? _downPosition;
set downPosition(Offset? value) {
if (value == _downPosition) {
return;
}
_downPosition = value;
notifyListeners();
}
/// True if this toggleable has the input focus.
bool get isFocused => _isFocused!;
bool? _isFocused;
set isFocused(bool? value) {
if (value == _isFocused) {
return;
}
_isFocused = value;
notifyListeners();
}
/// Determines whether the toggleable shows as active.
bool get isActive => _isActive!;
bool? _isActive;
set isActive(bool? value) {
if (value == _isActive) {
return;
}
_isActive = value;
notifyListeners();
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
@override
bool? hitTest(Offset position) => null;
@override
SemanticsBuilderCallback? get semanticsBuilder => null;
@override
bool shouldRebuildSemantics(covariant CustomPainter oldDelegate) => false;
@override
String toString() => describeIdentity(this);
}
| flutter/packages/flutter/lib/src/cupertino/toggleable.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/toggleable.dart",
"repo_id": "flutter",
"token_count": 2542
} | 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:async';
import 'dart:convert' show json;
import 'dart:developer' as developer;
import 'dart:io' show exit;
import 'dart:ui' as ui show Brightness, PlatformDispatcher, SingletonFlutterWindow, window;
// Before adding any more dart:ui imports, please read the README.
import 'package:meta/meta.dart';
import 'assertions.dart';
import 'basic_types.dart';
import 'constants.dart';
import 'debug.dart';
import 'object.dart';
import 'platform.dart';
import 'print.dart';
import 'service_extensions.dart';
import 'timeline.dart';
export 'dart:ui' show PlatformDispatcher, SingletonFlutterWindow, clampDouble;
export 'basic_types.dart' show AsyncCallback, AsyncValueGetter, AsyncValueSetter;
// Examples can assume:
// mixin BarBinding on BindingBase { }
/// Signature for service extensions.
///
/// The returned map must not contain the keys "type" or "method", as
/// they will be replaced before the value is sent to the client. The
/// "type" key will be set to the string `_extensionType` to indicate
/// that this is a return value from a service extension, and the
/// "method" key will be set to the full name of the method.
typedef ServiceExtensionCallback = Future<Map<String, dynamic>> Function(Map<String, String> parameters);
/// Base class for mixins that provide singleton services.
///
/// The Flutter engine ([dart:ui]) exposes some low-level services,
/// but these are typically not suitable for direct use, for example
/// because they only provide a single callback which an application
/// may wish to multiplex to allow multiple listeners.
///
/// Bindings provide the glue between these low-level APIs and the
/// higher-level framework APIs. They _bind_ the two together, whence
/// the name.
///
/// ## Implementing a binding mixin
///
/// A library would typically create a new binding mixin to expose a
/// feature in [dart:ui]. This is rare in general, but it is something
/// that an alternative framework would do, e.g. if a framework were
/// to replace the [widgets] library with an alternative API but still
/// wished to leverage the [services] and [foundation] libraries.
///
/// To create a binding mixin, declare a mixin `on` the [BindingBase] class
/// and whatever other bindings the concrete binding must implement for
/// this binding mixin to be useful.
///
/// The mixin is guaranteed to only be constructed once in the
/// lifetime of the app; this is handled by [initInstances].
///
/// A binding mixin must at a minimum implement the following features:
///
/// * The [initInstances] method, which must call `super.initInstances` and
/// set an `_instance` static field to `this`.
/// * An `instance` static getter, which must return that field using [checkInstance].
///
/// In addition, it should implement whatever singleton features the library needs.
///
/// As a general rule, the less can be placed in the binding, the
/// better. Prefer having APIs that takes objects rather than having
/// them refer to global singletons. Bindings are best limited to
/// exposing features that literally only exist once, for example, the
/// APIs in [dart:ui].
///
/// {@tool snippet}
///
/// Here is a basic example of a binding that implements these features. It relies on
/// another fictional binding called `BarBinding`.
///
/// ```dart
/// mixin FooBinding on BindingBase, BarBinding {
/// @override
/// void initInstances() {
/// super.initInstances();
/// _instance = this;
/// // ...binding initialization...
/// }
///
/// static FooBinding get instance => BindingBase.checkInstance(_instance);
/// static FooBinding? _instance;
///
/// // ...binding features...
/// }
/// ```
/// {@end-tool}
///
/// ## Implementing a binding class
///
/// The top-most layer used to write the application (e.g. the Flutter
/// [widgets] library) will have a concrete class that inherits from
/// [BindingBase] and uses all the various [BindingBase] mixins (such
/// as [ServicesBinding]). The [widgets] library in Flutter introduces
/// a binding called [WidgetsFlutterBinding].
///
/// A binding _class_ should mix in the relevant bindings from each
/// layer that it wishes to expose, and should have an
/// `ensureInitialized` method that constructs the class if that
/// layer's mixin's `_instance` field is null. This allows the binding
/// to be overridden by developers who have more specific needs, while
/// still allowing other code to call `ensureInitialized` when a binding
/// is needed.
///
/// {@tool snippet}
///
/// A typical binding class is shown below. The `ensureInitialized` method's
/// return type is the library's binding mixin, rather than the concrete
/// class.
///
/// ```dart
/// // continuing from previous example...
/// class FooLibraryBinding extends BindingBase with BarBinding, FooBinding {
/// static FooBinding ensureInitialized() {
/// if (FooBinding._instance == null) {
/// FooLibraryBinding();
/// }
/// return FooBinding.instance;
/// }
/// }
/// ```
/// {@end-tool}
abstract class BindingBase {
/// Default abstract constructor for bindings.
///
/// First calls [initInstances] to have bindings initialize their
/// instance pointers and other state, then calls
/// [initServiceExtensions] to have bindings initialize their
/// VM service extensions, if any.
BindingBase() {
if (!kReleaseMode) {
FlutterTimeline.startSync('Framework initialization');
}
assert(() {
_debugConstructed = true;
return true;
}());
assert(_debugInitializedType == null, 'Binding is already initialized to $_debugInitializedType');
initInstances();
assert(_debugInitializedType != null);
assert(!_debugServiceExtensionsRegistered);
initServiceExtensions();
assert(_debugServiceExtensionsRegistered);
if (!kReleaseMode) {
developer.postEvent('Flutter.FrameworkInitialization', <String, String>{});
FlutterTimeline.finishSync();
}
}
bool _debugConstructed = false;
static Type? _debugInitializedType;
static bool _debugServiceExtensionsRegistered = false;
/// Deprecated. Will be removed in a future version of Flutter.
///
/// This property has been deprecated to prepare for Flutter's upcoming
/// support for multiple views and multiple windows.
///
/// It represents the main view for applications where there is only one
/// view, such as applications designed for single-display mobile devices.
/// If the embedder supports multiple views, it points to the first view
/// created which is assumed to be the main view. It throws if no view has
/// been created yet or if the first view has been removed again.
///
/// The following options exists to migrate code that relies on accessing
/// this deprecated property:
///
/// If a [BuildContext] is available, consider looking up the current
/// [FlutterView] associated with that context via [View.of]. It gives access
/// to the same functionality as this deprecated property. However, the
/// platform-specific functionality has moved to the [PlatformDispatcher],
/// which may be accessed from the view returned by [View.of] via
/// [FlutterView.platformDispatcher]. Using [View.of] with a [BuildContext] is
/// the preferred option to migrate away from this deprecated [window]
/// property.
///
/// If no context is available to look up a [FlutterView], the
/// [platformDispatcher] exposed by this binding can be used directly for
/// platform-specific functionality. It also maintains a list of all available
/// [FlutterView]s in [PlatformDispatcher.views] to access view-specific
/// functionality without a context.
///
/// See also:
///
/// * [View.of] to access view-specific functionality on the [FlutterView]
/// associated with the provided [BuildContext].
/// * [FlutterView.platformDispatcher] to access platform-specific
/// functionality from a given [FlutterView].
/// * [platformDispatcher] on this binding to access the [PlatformDispatcher],
/// which provides platform-specific functionality.
@Deprecated(
'Look up the current FlutterView from the context via View.of(context) or consult the PlatformDispatcher directly instead. '
'Deprecated to prepare for the upcoming multi-window support. '
'This feature was deprecated after v3.7.0-32.0.pre.'
)
ui.SingletonFlutterWindow get window => ui.window;
/// The [ui.PlatformDispatcher] to which this binding is bound.
///
/// A number of additional bindings are defined as extensions of
/// [BindingBase], e.g., [ServicesBinding], [RendererBinding], and
/// [WidgetsBinding]. Each of these bindings define behaviors that interact
/// with a [ui.PlatformDispatcher], e.g., [ServicesBinding] registers
/// listeners with the [ChannelBuffers], [RendererBinding]
/// registers [ui.PlatformDispatcher.onMetricsChanged],
/// [ui.PlatformDispatcher.onTextScaleFactorChanged], and [SemanticsBinding]
/// registers [ui.PlatformDispatcher.onSemanticsEnabledChanged],
/// [ui.PlatformDispatcher.onSemanticsActionEvent], and
/// [ui.PlatformDispatcher.onAccessibilityFeaturesChanged] handlers.
///
/// Each of these other bindings could individually access a
/// [ui.PlatformDispatcher] statically, but that would preclude the ability to
/// test these behaviors with a fake platform dispatcher for verification
/// purposes. Therefore, [BindingBase] exposes this [ui.PlatformDispatcher]
/// for use by other bindings. A subclass of [BindingBase], such as
/// [TestWidgetsFlutterBinding], can override this accessor to return a
/// different [ui.PlatformDispatcher] implementation.
ui.PlatformDispatcher get platformDispatcher => ui.PlatformDispatcher.instance;
/// The initialization method. Subclasses override this method to hook into
/// the platform and otherwise configure their services. Subclasses must call
/// "super.initInstances()".
///
/// The binding is not fully initialized when this method runs (for
/// example, other binding mixins may not yet have run their
/// [initInstances] method). For this reason, code in this method
/// should avoid invoking callbacks or synchronously triggering any
/// code that would normally assume that the bindings are ready.
///
/// {@tool snippet}
///
/// By convention, if the service is to be provided as a singleton,
/// it should be exposed as `MixinClassName.instance`, a static
/// getter with a non-nullable return type that returns
/// `MixinClassName._instance`, a static field that is set by
/// `initInstances()`. To improve the developer experience, the
/// return value should actually be
/// `BindingBase.checkInstance(_instance)` (see [checkInstance]), as
/// in the example below.
///
/// ```dart
/// mixin BazBinding on BindingBase {
/// @override
/// void initInstances() {
/// super.initInstances();
/// _instance = this;
/// // ...binding initialization...
/// }
///
/// static BazBinding get instance => BindingBase.checkInstance(_instance);
/// static BazBinding? _instance;
///
/// // ...binding features...
/// }
/// ```
/// {@end-tool}
@protected
@mustCallSuper
void initInstances() {
assert(_debugInitializedType == null);
assert(() {
_debugInitializedType = runtimeType;
_debugBindingZone = Zone.current;
return true;
}());
}
/// A method that shows a useful error message if the given binding
/// instance is not initialized.
///
/// See [initInstances] for advice on using this method.
///
/// This method either returns the argument or throws an exception.
/// In release mode it always returns the argument.
///
/// The type argument `T` should be the kind of binding mixin (e.g.
/// `SchedulerBinding`) that is calling the method. It is used in
/// error messages.
@protected
static T checkInstance<T extends BindingBase>(T? instance) {
assert(() {
if (_debugInitializedType == null && instance == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Binding has not yet been initialized.'),
ErrorDescription('The "instance" getter on the $T binding mixin is only available once that binding has been initialized.'),
ErrorHint(
'Typically, this is done by calling "WidgetsFlutterBinding.ensureInitialized()" or "runApp()" (the '
'latter calls the former). Typically this call is done in the "void main()" method. The "ensureInitialized" method '
'is idempotent; calling it multiple times is not harmful. After calling that method, the "instance" getter will '
'return the binding.',
),
ErrorHint(
'In a test, one can call "TestWidgetsFlutterBinding.ensureInitialized()" as the first line in the test\'s "main()" method '
'to initialize the binding.',
),
ErrorHint(
'If $T is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, '
'but that mixes in the selected binding, and that is the class that must be constructed before using the "instance" getter.',
),
]);
}
if (instance == null) {
assert(_debugInitializedType == null);
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Binding mixin instance is null but bindings are already initialized.'),
ErrorDescription(
'The "instance" property of the $T binding mixin was accessed, but that binding was not initialized when '
'the "initInstances()" method was called.',
),
ErrorHint(
'This probably indicates that the $T mixin was not mixed into the class that was used to initialize the binding. '
'If this is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, '
'but that mixes in the selected binding. If this is a test binding, check that the binding being initialized '
'is the same as the one into which the test binding is mixed.',
),
ErrorHint(
'It is also possible that $T does not implement "initInstances()" to assign a value to "instance". See the '
'documentation of the BindingBase class for more details.',
),
ErrorHint(
'The binding that was initialized was of the type "$_debugInitializedType". '
),
]);
}
try {
if (instance._debugConstructed && _debugInitializedType == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Binding initialized without calling initInstances.'),
ErrorDescription('An instance of $T is non-null, but BindingBase.initInstances() has not yet been called.'),
ErrorHint(
'This could happen because a binding mixin was somehow used outside of the normal binding mechanisms, or because '
'the binding\'s initInstances() method did not call "super.initInstances()".',
),
ErrorHint(
'This could also happen if some code was invoked that used the binding while the binding was initializing, '
'for example if the "initInstances" method invokes a callback. Bindings should not invoke callbacks before '
'"initInstances" has completed.',
),
]);
}
if (!instance._debugConstructed) {
// The state of _debugInitializedType doesn't matter in this failure mode.
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Binding did not complete initialization.'),
ErrorDescription('An instance of $T is non-null, but the BindingBase() constructor has not yet been called.'),
ErrorHint(
'This could also happen if some code was invoked that used the binding while the binding was initializing, '
"for example if the binding's constructor itself invokes a callback. Bindings should not invoke callbacks "
'before "initInstances" has completed.',
),
]);
}
} on NoSuchMethodError {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Binding does not extend BindingBase'),
ErrorDescription('An instance of $T was created but the BindingBase constructor was not called.'),
ErrorHint(
'This could happen because the binding was implemented using "implements" rather than "extends" or "with". '
'Concrete binding classes must extend or mix in BindingBase.',
),
]);
}
return true;
}());
return instance!;
}
/// In debug builds, the type of the current binding, if any, or else null.
///
/// This may be useful in asserts to verify that the binding has not been initialized
/// before the point in the application code that wants to initialize the binding, or
/// to verify that the binding is the one that is expected.
///
/// For example, if an application uses [Zone]s to report uncaught exceptions, it may
/// need to ensure that `ensureInitialized()` has not yet been invoked on any binding
/// at the point where it configures the zone and initializes the binding.
///
/// If this returns null, the binding has not been initialized.
///
/// If this returns a non-null value, it returns the type of the binding instance.
///
/// To obtain the binding itself, consider the `instance` getter on the [BindingBase]
/// subclass or mixin.
///
/// This method only returns a useful value in debug builds. In release builds, the
/// return value is always null; to improve startup performance, the type of the
/// binding is not tracked in release builds.
///
/// See also:
///
/// * [BindingBase], whose class documentation describes the conventions for dealing
/// with bindings.
/// * [initInstances], whose documentation details how to create a binding mixin.
static Type? debugBindingType() {
return _debugInitializedType;
}
Zone? _debugBindingZone;
/// Whether [debugCheckZone] should throw (true) or just report the error (false).
///
/// Setting this to true makes it easier to catch cases where the zones are
/// misconfigured, by allowing debuggers to stop at the point of error.
///
/// Currently this defaults to false, to avoid suddenly breaking applications
/// that are affected by this check but appear to be working today. Applications
/// are encouraged to resolve any issues that cause the [debugCheckZone] message
/// to appear, as even if they appear to be working today, they are likely to be
/// hiding hard-to-find bugs, and are more brittle (likely to collect bugs in
/// the future).
///
/// To silence the message displayed by [debugCheckZone], ensure that the same
/// zone is used when calling `ensureInitialized()` as when calling the framework
/// in any other context (e.g. via [runApp]).
static bool debugZoneErrorsAreFatal = false;
/// Checks that the current [Zone] is the same as that which was used
/// to initialize the binding.
///
/// If the current zone ([Zone.current]) is not the zone that was active when
/// the binding was initialized, then this method generates a [FlutterError]
/// exception with detailed information. The exception is either thrown
/// directly, or reported via [FlutterError.reportError], depending on the
/// value of [BindingBase.debugZoneErrorsAreFatal].
///
/// To silence the message displayed by [debugCheckZone], ensure that the same
/// zone is used when calling `ensureInitialized()` as when calling the
/// framework in any other context (e.g. via [runApp]). For example, consider
/// keeping a reference to the zone used to initialize the binding, and using
/// [Zone.run] to use it again when calling into the framework.
///
/// ## Usage
///
/// The binding is considered initialized once [BindingBase.initInstances] has
/// run; if this is called before then, it will throw an [AssertionError].
///
/// The `entryPoint` parameter is the name of the API that is checking the
/// zones are consistent, for example, `'runApp'`.
///
/// This function always returns true (if it does not throw). It is expected
/// to be invoked via the binding instance, e.g.:
///
/// ```dart
/// void startup() {
/// WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized();
/// assert(binding.debugCheckZone('startup'));
/// // ...
/// }
/// ```
///
/// If the binding expects to be used with multiple zones, it should override
/// this method to return true always without throwing. (For example, the
/// bindings used with [flutter_test] do this as they make heavy use of zones
/// to drive the framework with an artificial clock and to catch errors and
/// report them as test failures.)
bool debugCheckZone(String entryPoint) {
assert(() {
assert(_debugBindingZone != null, 'debugCheckZone can only be used after the binding is fully initialized.');
if (Zone.current != _debugBindingZone) {
final Error message = FlutterError(
'Zone mismatch.\n'
'The Flutter bindings were initialized in a different zone than is now being used. '
'This will likely cause confusion and bugs as any zone-specific configuration will '
'inconsistently use the configuration of the original binding initialization zone '
'or this zone based on hard-to-predict factors such as which zone was active when '
'a particular callback was set.\n'
'It is important to use the same zone when calling `ensureInitialized` on the binding '
'as when calling `$entryPoint` later.\n'
'To make this ${ debugZoneErrorsAreFatal ? 'error non-fatal' : 'warning fatal' }, '
'set BindingBase.debugZoneErrorsAreFatal to ${!debugZoneErrorsAreFatal} before the '
'bindings are initialized (i.e. as the first statement in `void main() { }`).',
);
if (debugZoneErrorsAreFatal) {
throw message;
}
FlutterError.reportError(FlutterErrorDetails(
exception: message,
stack: StackTrace.current,
context: ErrorDescription('during $entryPoint'),
));
}
return true;
}());
return true;
}
/// Called when the binding is initialized, to register service
/// extensions.
///
/// Bindings that want to expose service extensions should overload
/// this method to register them using calls to
/// [registerSignalServiceExtension],
/// [registerBoolServiceExtension],
/// [registerNumericServiceExtension], and
/// [registerServiceExtension] (in increasing order of complexity).
///
/// Implementations of this method must call their superclass
/// implementation.
///
/// {@macro flutter.foundation.BindingBase.registerServiceExtension}
///
/// See also:
///
/// * <https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md#rpcs-requests-and-responses>
@protected
@mustCallSuper
void initServiceExtensions() {
assert(!_debugServiceExtensionsRegistered);
assert(() {
registerSignalServiceExtension(
name: FoundationServiceExtensions.reassemble.name,
callback: reassembleApplication,
);
return true;
}());
if (!kReleaseMode) {
if (!kIsWeb) {
registerSignalServiceExtension(
name: FoundationServiceExtensions.exit.name,
callback: _exitApplication,
);
}
// These service extensions are used in profile mode applications.
registerStringServiceExtension(
name: FoundationServiceExtensions.connectedVmServiceUri.name,
getter: () async => connectedVmServiceUri ?? '',
setter: (String uri) async {
connectedVmServiceUri = uri;
},
);
registerStringServiceExtension(
name: FoundationServiceExtensions.activeDevToolsServerAddress.name,
getter: () async => activeDevToolsServerAddress ?? '',
setter: (String serverAddress) async {
activeDevToolsServerAddress = serverAddress;
},
);
}
assert(() {
registerServiceExtension(
name: FoundationServiceExtensions.platformOverride.name,
callback: (Map<String, String> parameters) async {
if (parameters.containsKey('value')) {
final String value = parameters['value']!;
debugDefaultTargetPlatformOverride = null;
for (final TargetPlatform candidate in TargetPlatform.values) {
if (candidate.name == value) {
debugDefaultTargetPlatformOverride = candidate;
break;
}
}
_postExtensionStateChangedEvent(
FoundationServiceExtensions.platformOverride.name,
defaultTargetPlatform.name,
);
await reassembleApplication();
}
return <String, dynamic>{
'value': defaultTargetPlatform.name,
};
},
);
registerServiceExtension(
name: FoundationServiceExtensions.brightnessOverride.name,
callback: (Map<String, String> parameters) async {
if (parameters.containsKey('value')) {
debugBrightnessOverride = switch (parameters['value']) {
'Brightness.light' => ui.Brightness.light,
'Brightness.dark' => ui.Brightness.dark,
_ => null,
};
_postExtensionStateChangedEvent(
FoundationServiceExtensions.brightnessOverride.name,
(debugBrightnessOverride ?? platformDispatcher.platformBrightness).toString(),
);
await reassembleApplication();
}
return <String, dynamic>{
'value': (debugBrightnessOverride ?? platformDispatcher.platformBrightness).toString(),
};
},
);
return true;
}());
assert(() {
_debugServiceExtensionsRegistered = true;
return true;
}());
}
/// Whether [lockEvents] is currently locking events.
///
/// Binding subclasses that fire events should check this first, and if it is
/// set, queue events instead of firing them.
///
/// Events should be flushed when [unlocked] is called.
@protected
bool get locked => _lockCount > 0;
int _lockCount = 0;
/// Locks the dispatching of asynchronous events and callbacks until the
/// callback's future completes.
///
/// This causes input lag and should therefore be avoided when possible. It is
/// primarily intended for use during non-user-interactive time such as to
/// allow [reassembleApplication] to block input while it walks the tree
/// (which it partially does asynchronously).
///
/// The [Future] returned by the `callback` argument is returned by [lockEvents].
///
/// The [gestures] binding wraps [PlatformDispatcher.onPointerDataPacket] in
/// logic that honors this event locking mechanism. Similarly, tasks queued
/// using [SchedulerBinding.scheduleTask] will only start when events are not
/// [locked].
@protected
Future<void> lockEvents(Future<void> Function() callback) {
developer.TimelineTask? debugTimelineTask;
if (!kReleaseMode) {
debugTimelineTask = developer.TimelineTask()..start('Lock events');
}
_lockCount += 1;
final Future<void> future = callback();
future.whenComplete(() {
_lockCount -= 1;
if (!locked) {
if (!kReleaseMode) {
debugTimelineTask!.finish();
}
try {
unlocked();
} catch (error, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: error,
stack: stack,
library: 'foundation',
context: ErrorDescription('while handling pending events'),
));
}
}
});
return future;
}
/// Called by [lockEvents] when events get unlocked.
///
/// This should flush any events that were queued while [locked] was true.
@protected
@mustCallSuper
void unlocked() {
assert(!locked);
}
/// Cause the entire application to redraw, e.g. after a hot reload.
///
/// This is used by development tools when the application code has changed,
/// to cause the application to pick up any changed code. It can be triggered
/// manually by sending the `ext.flutter.reassemble` service extension signal.
///
/// This method is very computationally expensive and should not be used in
/// production code. There is never a valid reason to cause the entire
/// application to repaint in production. All aspects of the Flutter framework
/// know how to redraw when necessary. It is only necessary in development
/// when the code is literally changed on the fly (e.g. in hot reload) or when
/// debug flags are being toggled.
///
/// While this method runs, events are locked (e.g. pointer events are not
/// dispatched).
///
/// Subclasses (binding classes) should override [performReassemble] to react
/// to this method being called. This method itself should not be overridden.
Future<void> reassembleApplication() {
return lockEvents(performReassemble);
}
/// This method is called by [reassembleApplication] to actually cause the
/// application to reassemble, e.g. after a hot reload.
///
/// Bindings are expected to use this method to re-register anything that uses
/// closures, so that they do not keep pointing to old code, and to flush any
/// caches of previously computed values, in case the new code would compute
/// them differently. For example, the rendering layer triggers the entire
/// application to repaint when this is called.
///
/// Do not call this method directly. Instead, use [reassembleApplication].
@mustCallSuper
@protected
Future<void> performReassemble() {
FlutterError.resetErrorCount();
return Future<void>.value();
}
/// Registers a service extension method with the given name (full
/// name "ext.flutter.name"), which takes no arguments and returns
/// no value.
///
/// Calls the `callback` callback when the service extension is called.
///
/// {@macro flutter.foundation.BindingBase.registerServiceExtension}
@protected
void registerSignalServiceExtension({
required String name,
required AsyncCallback callback,
}) {
registerServiceExtension(
name: name,
callback: (Map<String, String> parameters) async {
await callback();
return <String, dynamic>{};
},
);
}
/// Registers a service extension method with the given name (full
/// name "ext.flutter.name"), which takes a single argument
/// "enabled" which can have the value "true" or the value "false"
/// or can be omitted to read the current value. (Any value other
/// than "true" is considered equivalent to "false". Other arguments
/// are ignored.)
///
/// Calls the `getter` callback to obtain the value when
/// responding to the service extension method being called.
///
/// Calls the `setter` callback with the new value when the
/// service extension method is called with a new value.
///
/// {@macro flutter.foundation.BindingBase.registerServiceExtension}
@protected
void registerBoolServiceExtension({
required String name,
required AsyncValueGetter<bool> getter,
required AsyncValueSetter<bool> setter,
}) {
registerServiceExtension(
name: name,
callback: (Map<String, String> parameters) async {
if (parameters.containsKey('enabled')) {
await setter(parameters['enabled'] == 'true');
_postExtensionStateChangedEvent(name, await getter() ? 'true' : 'false');
}
return <String, dynamic>{'enabled': await getter() ? 'true' : 'false'};
},
);
}
/// Registers a service extension method with the given name (full
/// name "ext.flutter.name"), which takes a single argument with the
/// same name as the method which, if present, must have a value
/// that can be parsed by [double.parse], and can be omitted to read
/// the current value. (Other arguments are ignored.)
///
/// Calls the `getter` callback to obtain the value when
/// responding to the service extension method being called.
///
/// Calls the `setter` callback with the new value when the
/// service extension method is called with a new value.
///
/// {@macro flutter.foundation.BindingBase.registerServiceExtension}
@protected
void registerNumericServiceExtension({
required String name,
required AsyncValueGetter<double> getter,
required AsyncValueSetter<double> setter,
}) {
registerServiceExtension(
name: name,
callback: (Map<String, String> parameters) async {
if (parameters.containsKey(name)) {
await setter(double.parse(parameters[name]!));
_postExtensionStateChangedEvent(name, (await getter()).toString());
}
return <String, dynamic>{name: (await getter()).toString()};
},
);
}
/// Sends an event when a service extension's state is changed.
///
/// Clients should listen for this event to stay aware of the current service
/// extension state. Any service extension that manages a state should call
/// this method on state change.
///
/// `value` reflects the newly updated service extension value.
///
/// This will be called automatically for service extensions registered via
/// [registerBoolServiceExtension], [registerNumericServiceExtension], or
/// [registerStringServiceExtension].
void _postExtensionStateChangedEvent(String name, dynamic value) {
postEvent(
'Flutter.ServiceExtensionStateChanged',
<String, dynamic>{
'extension': 'ext.flutter.$name',
'value': value,
},
);
}
/// All events dispatched by a [BindingBase] use this method instead of
/// calling [developer.postEvent] directly so that tests for [BindingBase]
/// can track which events were dispatched by overriding this method.
///
/// This is unrelated to the events managed by [lockEvents].
@protected
void postEvent(String eventKind, Map<String, dynamic> eventData) {
developer.postEvent(eventKind, eventData);
}
/// Registers a service extension method with the given name (full name
/// "ext.flutter.name"), which optionally takes a single argument with the
/// name "value". If the argument is omitted, the value is to be read,
/// otherwise it is to be set. Returns the current value.
///
/// Calls the `getter` callback to obtain the value when
/// responding to the service extension method being called.
///
/// Calls the `setter` callback with the new value when the
/// service extension method is called with a new value.
///
/// {@macro flutter.foundation.BindingBase.registerServiceExtension}
@protected
void registerStringServiceExtension({
required String name,
required AsyncValueGetter<String> getter,
required AsyncValueSetter<String> setter,
}) {
registerServiceExtension(
name: name,
callback: (Map<String, String> parameters) async {
if (parameters.containsKey('value')) {
await setter(parameters['value']!);
_postExtensionStateChangedEvent(name, await getter());
}
return <String, dynamic>{'value': await getter()};
},
);
}
/// Registers a service extension method with the given name (full name
/// "ext.flutter.name").
///
/// The given callback is called when the extension method is called. The
/// callback must return a [Future] that either eventually completes to a
/// return value in the form of a name/value map where the values can all be
/// converted to JSON using `json.encode()` (see [JsonEncoder]), or fails. In
/// case of failure, the failure is reported to the remote caller and is
/// dumped to the logs.
///
/// The returned map will be mutated.
///
/// {@template flutter.foundation.BindingBase.registerServiceExtension}
/// A registered service extension can only be activated if the vm-service
/// is included in the build, which only happens in debug and profile mode.
/// Although a service extension cannot be used in release mode its code may
/// still be included in the Dart snapshot and blow up binary size if it is
/// not wrapped in a guard that allows the tree shaker to remove it (see
/// sample code below).
///
/// {@tool snippet}
/// The following code registers a service extension that is only included in
/// debug builds.
///
/// ```dart
/// void myRegistrationFunction() {
/// assert(() {
/// // Register your service extension here.
/// return true;
/// }());
/// }
/// ```
/// {@end-tool}
///
/// {@tool snippet}
/// A service extension registered with the following code snippet is
/// available in debug and profile mode.
///
/// ```dart
/// void myOtherRegistrationFunction() {
/// // kReleaseMode is defined in the 'flutter/foundation.dart' package.
/// if (!kReleaseMode) {
/// // Register your service extension here.
/// }
/// }
/// ```
/// {@end-tool}
///
/// Both guards ensure that Dart's tree shaker can remove the code for the
/// service extension in release builds.
/// {@endtemplate}
@protected
void registerServiceExtension({
required String name,
required ServiceExtensionCallback callback,
}) {
final String methodName = 'ext.flutter.$name';
developer.registerExtension(methodName, (String method, Map<String, String> parameters) async {
assert(method == methodName);
assert(() {
if (debugInstrumentationEnabled) {
debugPrint('service extension method received: $method($parameters)');
}
return true;
}());
// VM service extensions are handled as "out of band" messages by the VM,
// which means they are handled at various times, generally ASAP.
// Notably, this includes being handled in the middle of microtask loops.
// While this makes sense for some service extensions (e.g. "dump current
// stack trace", which explicitly doesn't want to wait for a loop to
// complete), Flutter extensions need not be handled with such high
// priority. Further, handling them with such high priority exposes us to
// the possibility that they're handled in the middle of a frame, which
// breaks many assertions. As such, we ensure they we run the callbacks
// on the outer event loop here.
await debugInstrumentAction<void>('Wait for outer event loop', () {
return Future<void>.delayed(Duration.zero);
});
late Map<String, dynamic> result;
try {
result = await callback(parameters);
} catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
context: ErrorDescription('during a service extension callback for "$method"'),
));
return developer.ServiceExtensionResponse.error(
developer.ServiceExtensionResponse.extensionError,
json.encode(<String, String>{
'exception': exception.toString(),
'stack': stack.toString(),
'method': method,
}),
);
}
result['type'] = '_extensionType';
result['method'] = method;
return developer.ServiceExtensionResponse.result(json.encode(result));
});
}
@override
String toString() => '<${objectRuntimeType(this, 'BindingBase')}>';
}
/// Terminate the Flutter application.
Future<void> _exitApplication() async {
exit(0);
}
| flutter/packages/flutter/lib/src/foundation/binding.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/binding.dart",
"repo_id": "flutter",
"token_count": 12542
} | 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.
/// A collection of key/value pairs which provides efficient retrieval of
/// value by key.
///
/// This class implements a persistent map: extending this map with a new
/// key/value pair does not modify an existing instance but instead creates a
/// new instance.
///
/// Unlike [Map], this class does not support `null` as a key value and
/// implements only a functionality needed for a specific use case at the
/// core of the framework.
///
/// Underlying implementation uses a variation of *hash array mapped trie*
/// data structure with compressed (bitmap indexed) nodes.
///
/// See also:
///
/// * [Bagwell, Phil. Ideal hash trees.](https://infoscience.epfl.ch/record/64398);
/// * [Steindorfer, Michael J., and Jurgen J. Vinju. "Optimizing hash-array mapped tries for fast and lean immutable JVM collections."](https://dl.acm.org/doi/abs/10.1145/2814270.2814312);
/// * [Clojure's `PersistentHashMap`](https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/PersistentHashMap.java).
///
class PersistentHashMap<K extends Object, V> {
/// Creates an empty hash map.
const PersistentHashMap.empty() : this._(null);
const PersistentHashMap._(this._root);
final _TrieNode? _root;
/// If this map does not already contain the given [key] to [value]
/// mapping then create a new version of the map which contains
/// all mappings from the current one plus the given [key] to [value]
/// mapping.
PersistentHashMap<K, V> put(K key, V value) {
final _TrieNode newRoot =
(_root ?? _CompressedNode.empty).put(0, key, key.hashCode, value);
if (newRoot == _root) {
return this;
}
return PersistentHashMap<K, V>._(newRoot);
}
/// Returns value associated with the given [key] or `null` if [key]
/// is not in the map.
@pragma('dart2js:as:trust')
V? operator[](K key) {
// Unfortunately can not use unsafeCast<V?>(...) here because it leads
// to worse code generation on VM.
return _root?.get(0, key, key.hashCode) as V?;
}
}
/// Base class for nodes in a hash trie.
///
/// This trie is keyed by hash code bits using [hashBitsPerLevel] bits
/// at each level.
abstract class _TrieNode {
static const int hashBitsPerLevel = 5;
static const int hashBitsPerLevelMask = (1 << hashBitsPerLevel) - 1;
@pragma('dart2js:tryInline')
@pragma('vm:prefer-inline')
@pragma('wasm:prefer-inline')
static int trieIndex(int hash, int bitIndex) {
return (hash >>> bitIndex) & hashBitsPerLevelMask;
}
/// Insert [key] to [value] mapping into the trie using bits from [keyHash]
/// starting at [bitIndex].
_TrieNode put(int bitIndex, Object key, int keyHash, Object? value);
/// Lookup a value associated with the given [key] using bits from [keyHash]
/// starting at [bitIndex].
Object? get(int bitIndex, Object key, int keyHash);
}
/// A full (uncompressed) node in the trie.
///
/// It contains an array with `1<<_hashBitsPerLevel` elements which
/// are references to deeper nodes.
class _FullNode extends _TrieNode {
_FullNode(this.descendants);
static const int numElements = 1 << _TrieNode.hashBitsPerLevel;
// Caveat: this array is actually List<_TrieNode?> but typing it like that
// will introduce a type check when copying this array. For performance
// reasons we instead omit the type and use (implicit) casts when accessing
// it instead.
final List<Object?> descendants;
@override
_TrieNode put(int bitIndex, Object key, int keyHash, Object? value) {
final int index = _TrieNode.trieIndex(keyHash, bitIndex);
final _TrieNode node = _unsafeCast<_TrieNode?>(descendants[index]) ?? _CompressedNode.empty;
final _TrieNode newNode = node.put(bitIndex + _TrieNode.hashBitsPerLevel, key, keyHash, value);
return identical(newNode, node)
? this
: _FullNode(_copy(descendants)..[index] = newNode);
}
@override
Object? get(int bitIndex, Object key, int keyHash) {
final int index = _TrieNode.trieIndex(keyHash, bitIndex);
final _TrieNode? node = _unsafeCast<_TrieNode?>(descendants[index]);
return node?.get(bitIndex + _TrieNode.hashBitsPerLevel, key, keyHash);
}
}
/// Compressed node in the trie.
///
/// Instead of storing the full array of outgoing edges this node uses a
/// compressed representation:
///
/// * [_CompressedNode.occupied] has a bit set for indices which are occupied.
/// * furthermore, each occupied index can either be a `(key, value)` pair
/// representing an actual key/value mapping or a `(null, trieNode)` pair
/// representing a descendant node.
///
/// Keys and values are stored together in a single array (instead of two
/// parallel arrays) for performance reasons: this improves memory access
/// locality and reduces memory usage (two arrays of length N take slightly
/// more space than one array of length 2*N).
class _CompressedNode extends _TrieNode {
_CompressedNode(this.occupiedIndices, this.keyValuePairs);
_CompressedNode._empty() : this(0, _emptyArray);
factory _CompressedNode.single(int bitIndex, int keyHash, _TrieNode node) {
final int bit = 1 << _TrieNode.trieIndex(keyHash, bitIndex);
// A single (null, node) pair.
final List<Object?> keyValuePairs = _makeArray(2)
..[1] = node;
return _CompressedNode(bit, keyValuePairs);
}
static final _CompressedNode empty = _CompressedNode._empty();
// Caveat: do not replace with <Object?>[] or const <Object?>[] this will
// introduce polymorphism in the keyValuePairs field and significantly
// degrade performance on the VM because it will no longer be able to
// devirtualize method calls on keyValuePairs.
static final List<Object?> _emptyArray = _makeArray(0);
// This bitmap only uses 32bits due to [_TrieNode.hashBitsPerLevel] being `5`.
final int occupiedIndices;
final List<Object?> keyValuePairs;
@override
_TrieNode put(int bitIndex, Object key, int keyHash, Object? value) {
final int bit = 1 << _TrieNode.trieIndex(keyHash, bitIndex);
final int index = _compressedIndex(bit);
if ((occupiedIndices & bit) != 0) {
// Index is occupied.
final Object? keyOrNull = keyValuePairs[2 * index];
final Object? valueOrNode = keyValuePairs[2 * index + 1];
// Is this a (null, trieNode) pair?
if (identical(keyOrNull, null)) {
final _TrieNode newNode = _unsafeCast<_TrieNode>(valueOrNode).put(
bitIndex + _TrieNode.hashBitsPerLevel, key, keyHash, value);
if (newNode == valueOrNode) {
return this;
}
return _CompressedNode(
occupiedIndices, _copy(keyValuePairs)..[2 * index + 1] = newNode);
}
if (key == keyOrNull) {
// Found key/value pair with a matching key. If values match
// then avoid doing anything otherwise copy and update.
return identical(value, valueOrNode)
? this
: _CompressedNode(
occupiedIndices, _copy(keyValuePairs)..[2 * index + 1] = value);
}
// Two different keys at the same index, resolve collision.
final _TrieNode newNode = _resolveCollision(
bitIndex + _TrieNode.hashBitsPerLevel,
keyOrNull,
valueOrNode,
key,
keyHash,
value);
return _CompressedNode(
occupiedIndices,
_copy(keyValuePairs)
..[2 * index] = null
..[2 * index + 1] = newNode);
} else {
// Adding new key/value mapping.
final int occupiedCount = _bitCount(occupiedIndices);
if (occupiedCount >= 16) {
// Too many occupied: inflate compressed node into full node and
// update descendant at the corresponding index.
return _inflate(bitIndex)
..descendants[_TrieNode.trieIndex(keyHash, bitIndex)] =
_CompressedNode.empty.put(
bitIndex + _TrieNode.hashBitsPerLevel, key, keyHash, value);
} else {
// Grow keyValuePairs by inserting key/value pair at the given
// index.
final int prefixLength = 2 * index;
final int totalLength = 2 * occupiedCount;
final List<Object?> newKeyValuePairs = _makeArray(totalLength + 2);
for (int srcIndex = 0; srcIndex < prefixLength; srcIndex++) {
newKeyValuePairs[srcIndex] = keyValuePairs[srcIndex];
}
newKeyValuePairs[prefixLength] = key;
newKeyValuePairs[prefixLength + 1] = value;
for (int srcIndex = prefixLength, dstIndex = prefixLength + 2;
srcIndex < totalLength;
srcIndex++, dstIndex++) {
newKeyValuePairs[dstIndex] = keyValuePairs[srcIndex];
}
return _CompressedNode(occupiedIndices | bit, newKeyValuePairs);
}
}
}
@override
Object? get(int bitIndex, Object key, int keyHash) {
final int bit = 1 << _TrieNode.trieIndex(keyHash, bitIndex);
if ((occupiedIndices & bit) == 0) {
return null;
}
final int index = _compressedIndex(bit);
final Object? keyOrNull = keyValuePairs[2 * index];
final Object? valueOrNode = keyValuePairs[2 * index + 1];
if (keyOrNull == null) {
final _TrieNode node = _unsafeCast<_TrieNode>(valueOrNode);
return node.get(bitIndex + _TrieNode.hashBitsPerLevel, key, keyHash);
}
if (key == keyOrNull) {
return valueOrNode;
}
return null;
}
/// Convert this node into an equivalent [_FullNode].
_FullNode _inflate(int bitIndex) {
final List<Object?> nodes = _makeArray(_FullNode.numElements);
int srcIndex = 0;
for (int dstIndex = 0; dstIndex < _FullNode.numElements; dstIndex++) {
if (((occupiedIndices >>> dstIndex) & 1) != 0) {
final Object? keyOrNull = keyValuePairs[srcIndex];
if (keyOrNull == null) {
nodes[dstIndex] = keyValuePairs[srcIndex + 1];
} else {
nodes[dstIndex] = _CompressedNode.empty.put(
bitIndex + _TrieNode.hashBitsPerLevel,
keyOrNull,
keyValuePairs[srcIndex].hashCode,
keyValuePairs[srcIndex + 1]);
}
srcIndex += 2;
}
}
return _FullNode(nodes);
}
@pragma('dart2js:tryInline')
@pragma('vm:prefer-inline')
@pragma('wasm:prefer-inline')
int _compressedIndex(int bit) {
return _bitCount(occupiedIndices & (bit - 1));
}
static _TrieNode _resolveCollision(int bitIndex, Object existingKey,
Object? existingValue, Object key, int keyHash, Object? value) {
final int existingKeyHash = existingKey.hashCode;
// Check if this is a full hash collision and use _HashCollisionNode
// in this case.
return (existingKeyHash == keyHash)
? _HashCollisionNode.fromCollision(
keyHash, existingKey, existingValue, key, value)
: _CompressedNode.empty
.put(bitIndex, existingKey, existingKeyHash, existingValue)
.put(bitIndex, key, keyHash, value);
}
}
/// Trie node representing a full hash collision.
///
/// Stores a list of key/value pairs (where all keys have the same hash code).
class _HashCollisionNode extends _TrieNode {
_HashCollisionNode(this.hash, this.keyValuePairs);
factory _HashCollisionNode.fromCollision(
int keyHash, Object keyA, Object? valueA, Object keyB, Object? valueB) {
final List<Object?> list = _makeArray(4);
list[0] = keyA;
list[1] = valueA;
list[2] = keyB;
list[3] = valueB;
return _HashCollisionNode(keyHash, list);
}
final int hash;
final List<Object?> keyValuePairs;
@override
_TrieNode put(int bitIndex, Object key, int keyHash, Object? val) {
// Is this another full hash collision?
if (keyHash == hash) {
final int index = _indexOf(key);
if (index != -1) {
return identical(keyValuePairs[index + 1], val)
? this
: _HashCollisionNode(
keyHash, _copy(keyValuePairs)..[index + 1] = val);
}
final int length = keyValuePairs.length;
final List<Object?> newArray = _makeArray(length + 2);
for (int i = 0; i < length; i++) {
newArray[i] = keyValuePairs[i];
}
newArray[length] = key;
newArray[length + 1] = val;
return _HashCollisionNode(keyHash, newArray);
}
// Not a full hash collision, need to introduce a _CompressedNode which
// uses previously unused bits.
return _CompressedNode.single(bitIndex, hash, this)
.put(bitIndex, key, keyHash, val);
}
@override
Object? get(int bitIndex, Object key, int keyHash) {
final int index = _indexOf(key);
return index < 0 ? null : keyValuePairs[index + 1];
}
int _indexOf(Object key) {
final int length = keyValuePairs.length;
for (int i = 0; i < length; i += 2) {
if (key == keyValuePairs[i]) {
return i;
}
}
return -1;
}
}
/// Returns number of bits set in a 32bit integer.
///
/// dart2js safe because we work with 32bit integers.
@pragma('dart2js:tryInline')
@pragma('vm:prefer-inline')
@pragma('wasm:prefer-inline')
int _bitCount(int n) {
assert((n & 0xFFFFFFFF) == n);
n = n - ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >>> 2) & 0x33333333);
n = (n + (n >> 4)) & 0x0F0F0F0F;
n = n + (n >> 8);
n = n + (n >> 16);
return n & 0x0000003F;
}
/// Create a copy of the given array.
///
/// Caveat: do not replace with List.of or similar methods. They are
/// considerably slower.
@pragma('dart2js:tryInline')
@pragma('vm:prefer-inline')
@pragma('wasm:prefer-inline')
List<Object?> _copy(List<Object?> array) {
final List<Object?> clone = _makeArray(array.length);
for (int j = 0; j < array.length; j++) {
clone[j] = array[j];
}
return clone;
}
/// Create a fixed-length array of the given length filled with `null`.
///
/// We are using fixed length arrays because they are smaller and
/// faster to access on VM. Growable arrays are represented by 2 objects
/// (growable array instance pointing to a fixed array instance) and
/// consequently fixed length arrays are faster to allocated, require less
/// memory and are faster to access (less indirections).
@pragma('dart2js:tryInline')
@pragma('vm:prefer-inline')
@pragma('wasm:prefer-inline')
List<Object?> _makeArray(int length) {
return List<Object?>.filled(length, null);
}
/// This helper method becomes an no-op when compiled with dart2js on
/// with high level of optimizations enabled.
@pragma('dart2js:as:trust')
@pragma('dart2js:tryInline')
@pragma('vm:prefer-inline')
@pragma('wasm:prefer-inline')
T _unsafeCast<T>(Object? o) {
return o as T;
}
| flutter/packages/flutter/lib/src/foundation/persistent_hash_map.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/persistent_hash_map.dart",
"repo_id": "flutter",
"token_count": 5453
} | 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 'recognizer.dart';
export 'dart:ui' show PointerDeviceKind;
export 'events.dart' show PointerDownEvent, PointerEvent;
/// A gesture recognizer that eagerly claims victory in all gesture arenas.
///
/// This is typically passed in [AndroidView.gestureRecognizers] in order to immediately dispatch
/// all touch events inside the view bounds to the embedded Android view.
/// See [AndroidView.gestureRecognizers] for more details.
class EagerGestureRecognizer extends OneSequenceGestureRecognizer {
/// Create an eager gesture recognizer.
///
/// {@macro flutter.gestures.GestureRecognizer.supportedDevices}
EagerGestureRecognizer({
super.supportedDevices,
super.allowedButtonsFilter,
});
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
resolve(GestureDisposition.accepted);
stopTrackingPointer(event.pointer);
}
@override
String get debugDescription => 'eager';
@override
void didStopTrackingLastPointer(int pointer) { }
@override
void handleEvent(PointerEvent event) { }
}
| flutter/packages/flutter/lib/src/gestures/eager.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/gestures/eager.dart",
"repo_id": "flutter",
"token_count": 374
} | 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.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'constants.dart';
import 'events.dart';
import 'monodrag.dart';
import 'recognizer.dart';
import 'scale.dart';
import 'tap.dart';
// Examples can assume:
// void setState(VoidCallback fn) { }
// late String _last;
double _getGlobalDistance(PointerEvent event, OffsetPair? originPosition) {
assert(originPosition != null);
final Offset offset = event.position - originPosition!.global;
return offset.distance;
}
// The possible states of a [BaseTapAndDragGestureRecognizer].
//
// The recognizer advances from [ready] to [possible] when it starts tracking
// a pointer in [BaseTapAndDragGestureRecognizer.addAllowedPointer]. Where it advances
// from there depends on the sequence of pointer events that is tracked by the
// recognizer, following the initial [PointerDownEvent]:
//
// * If a [PointerUpEvent] has not been tracked, the recognizer stays in the [possible]
// state as long as it continues to track a pointer.
// * If a [PointerMoveEvent] is tracked that has moved a sufficient global distance
// from the initial [PointerDownEvent] and it came before a [PointerUpEvent], then
// this recognizer moves from the [possible] state to [accepted].
// * If a [PointerUpEvent] is tracked before the pointer has moved a sufficient global
// distance to be considered a drag, then this recognizer moves from the [possible]
// state to [ready].
// * If a [PointerCancelEvent] is tracked then this recognizer moves from its current
// state to [ready].
//
// Once the recognizer has stopped tracking any remaining pointers, the recognizer
// returns to the [ready] state.
enum _DragState {
// The recognizer is ready to start recognizing a drag.
ready,
// The sequence of pointer events seen thus far is consistent with a drag but
// it has not been accepted definitively.
possible,
// The sequence of pointer events has been accepted definitively as a drag.
accepted,
}
/// {@macro flutter.gestures.tap.GestureTapDownCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragDownDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onTapDown].
typedef GestureTapDragDownCallback = void Function(TapDragDownDetails details);
/// Details for [GestureTapDragDownCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onTapDown] callback.
/// * [TapDragUpDetails], the details for [GestureTapDragUpCallback].
/// * [TapDragStartDetails], the details for [GestureTapDragStartCallback].
/// * [TapDragUpdateDetails], the details for [GestureTapDragUpdateCallback].
/// * [TapDragEndDetails], the details for [GestureTapDragEndCallback].
class TapDragDownDetails with Diagnosticable {
/// Creates details for a [GestureTapDragDownCallback].
TapDragDownDetails({
required this.globalPosition,
required this.localPosition,
this.kind,
required this.consecutiveTapCount,
});
/// The global position at which the pointer contacted the screen.
final Offset globalPosition;
/// The local position at which the pointer contacted the screen.
final Offset localPosition;
/// The kind of the device that initiated the event.
final PointerDeviceKind? kind;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('globalPosition', globalPosition));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(DiagnosticsProperty<PointerDeviceKind?>('kind', kind));
properties.add(DiagnosticsProperty<int>('consecutiveTapCount', consecutiveTapCount));
}
}
/// {@macro flutter.gestures.tap.GestureTapUpCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragUpDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onTapUp].
typedef GestureTapDragUpCallback = void Function(TapDragUpDetails details);
/// Details for [GestureTapDragUpCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onTapUp] callback.
/// * [TapDragDownDetails], the details for [GestureTapDragDownCallback].
/// * [TapDragStartDetails], the details for [GestureTapDragStartCallback].
/// * [TapDragUpdateDetails], the details for [GestureTapDragUpdateCallback].
/// * [TapDragEndDetails], the details for [GestureTapDragEndCallback].
class TapDragUpDetails with Diagnosticable {
/// Creates details for a [GestureTapDragUpCallback].
TapDragUpDetails({
required this.kind,
required this.globalPosition,
required this.localPosition,
required this.consecutiveTapCount,
});
/// The global position at which the pointer contacted the screen.
final Offset globalPosition;
/// The local position at which the pointer contacted the screen.
final Offset localPosition;
/// The kind of the device that initiated the event.
final PointerDeviceKind kind;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('globalPosition', globalPosition));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(DiagnosticsProperty<PointerDeviceKind?>('kind', kind));
properties.add(DiagnosticsProperty<int>('consecutiveTapCount', consecutiveTapCount));
}
}
/// {@macro flutter.gestures.dragdetails.GestureDragStartCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragStartDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onDragStart].
typedef GestureTapDragStartCallback = void Function(TapDragStartDetails details);
/// Details for [GestureTapDragStartCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onDragStart] callback.
/// * [TapDragDownDetails], the details for [GestureTapDragDownCallback].
/// * [TapDragUpDetails], the details for [GestureTapDragUpCallback].
/// * [TapDragUpdateDetails], the details for [GestureTapDragUpdateCallback].
/// * [TapDragEndDetails], the details for [GestureTapDragEndCallback].
class TapDragStartDetails with Diagnosticable {
/// Creates details for a [GestureTapDragStartCallback].
TapDragStartDetails({
this.sourceTimeStamp,
required this.globalPosition,
required this.localPosition,
this.kind,
required this.consecutiveTapCount,
});
/// Recorded timestamp of the source pointer event that triggered the drag
/// event.
///
/// Could be null if triggered from proxied events such as accessibility.
final Duration? sourceTimeStamp;
/// The global position at which the pointer contacted the screen.
///
/// See also:
///
/// * [localPosition], which is the [globalPosition] transformed to the
/// coordinate space of the event receiver.
final Offset globalPosition;
/// The local position in the coordinate system of the event receiver at
/// which the pointer contacted the screen.
final Offset localPosition;
/// The kind of the device that initiated the event.
final PointerDeviceKind? kind;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Duration?>('sourceTimeStamp', sourceTimeStamp));
properties.add(DiagnosticsProperty<Offset>('globalPosition', globalPosition));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(DiagnosticsProperty<PointerDeviceKind?>('kind', kind));
properties.add(DiagnosticsProperty<int>('consecutiveTapCount', consecutiveTapCount));
}
}
/// {@macro flutter.gestures.dragdetails.GestureDragUpdateCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragUpdateDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onDragUpdate].
typedef GestureTapDragUpdateCallback = void Function(TapDragUpdateDetails details);
/// Details for [GestureTapDragUpdateCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onDragUpdate] callback.
/// * [TapDragDownDetails], the details for [GestureTapDragDownCallback].
/// * [TapDragUpDetails], the details for [GestureTapDragUpCallback].
/// * [TapDragStartDetails], the details for [GestureTapDragStartCallback].
/// * [TapDragEndDetails], the details for [GestureTapDragEndCallback].
class TapDragUpdateDetails with Diagnosticable {
/// Creates details for a [GestureTapDragUpdateCallback].
///
/// If [primaryDelta] is non-null, then its value must match one of the
/// coordinates of [delta] and the other coordinate must be zero.
TapDragUpdateDetails({
this.sourceTimeStamp,
this.delta = Offset.zero,
this.primaryDelta,
required this.globalPosition,
this.kind,
required this.localPosition,
required this.offsetFromOrigin,
required this.localOffsetFromOrigin,
required this.consecutiveTapCount,
}) : assert(
primaryDelta == null
|| (primaryDelta == delta.dx && delta.dy == 0.0)
|| (primaryDelta == delta.dy && delta.dx == 0.0),
);
/// Recorded timestamp of the source pointer event that triggered the drag
/// event.
///
/// Could be null if triggered from proxied events such as accessibility.
final Duration? sourceTimeStamp;
/// The amount the pointer has moved in the coordinate space of the event
/// receiver since the previous update.
///
/// If the [GestureTapDragUpdateCallback] is for a one-dimensional drag (e.g.,
/// a horizontal or vertical drag), then this offset contains only the delta
/// in that direction (i.e., the coordinate in the other direction is zero).
///
/// Defaults to zero if not specified in the constructor.
final Offset delta;
/// The amount the pointer has moved along the primary axis in the coordinate
/// space of the event receiver since the previous
/// update.
///
/// If the [GestureTapDragUpdateCallback] is for a one-dimensional drag (e.g.,
/// a horizontal or vertical drag), then this value contains the component of
/// [delta] along the primary axis (e.g., horizontal or vertical,
/// respectively). Otherwise, if the [GestureTapDragUpdateCallback] is for a
/// two-dimensional drag (e.g., a pan), then this value is null.
///
/// Defaults to null if not specified in the constructor.
final double? primaryDelta;
/// The pointer's global position when it triggered this update.
///
/// See also:
///
/// * [localPosition], which is the [globalPosition] transformed to the
/// coordinate space of the event receiver.
final Offset globalPosition;
/// The local position in the coordinate system of the event receiver at
/// which the pointer contacted the screen.
///
/// Defaults to [globalPosition] if not specified in the constructor.
final Offset localPosition;
/// The kind of the device that initiated the event.
final PointerDeviceKind? kind;
/// A delta offset from the point where the drag initially contacted
/// the screen to the point where the pointer is currently located in global
/// coordinates (the present [globalPosition]) when this callback is triggered.
///
/// When considering a [GestureRecognizer] that tracks the number of consecutive taps,
/// this offset is associated with the most recent [PointerDownEvent] that occurred.
final Offset offsetFromOrigin;
/// A local delta offset from the point where the drag initially contacted
/// the screen to the point where the pointer is currently located in local
/// coordinates (the present [localPosition]) when this callback is triggered.
///
/// When considering a [GestureRecognizer] that tracks the number of consecutive taps,
/// this offset is associated with the most recent [PointerDownEvent] that occurred.
final Offset localOffsetFromOrigin;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Duration?>('sourceTimeStamp', sourceTimeStamp));
properties.add(DiagnosticsProperty<Offset>('delta', delta));
properties.add(DiagnosticsProperty<double?>('primaryDelta', primaryDelta));
properties.add(DiagnosticsProperty<Offset>('globalPosition', globalPosition));
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(DiagnosticsProperty<PointerDeviceKind?>('kind', kind));
properties.add(DiagnosticsProperty<Offset>('offsetFromOrigin', offsetFromOrigin));
properties.add(DiagnosticsProperty<Offset>('localOffsetFromOrigin', localOffsetFromOrigin));
properties.add(DiagnosticsProperty<int>('consecutiveTapCount', consecutiveTapCount));
}
}
/// {@macro flutter.gestures.monodrag.GestureDragEndCallback}
///
/// The consecutive tap count at the time the pointer contacted the
/// screen is given by [TapDragEndDetails.consecutiveTapCount].
///
/// Used by [BaseTapAndDragGestureRecognizer.onDragEnd].
typedef GestureTapDragEndCallback = void Function(TapDragEndDetails endDetails);
/// Details for [GestureTapDragEndCallback], such as the number of
/// consecutive taps.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], which passes this information to its
/// [BaseTapAndDragGestureRecognizer.onDragEnd] callback.
/// * [TapDragDownDetails], the details for [GestureTapDragDownCallback].
/// * [TapDragUpDetails], the details for [GestureTapDragUpCallback].
/// * [TapDragStartDetails], the details for [GestureTapDragStartCallback].
/// * [TapDragUpdateDetails], the details for [GestureTapDragUpdateCallback].
class TapDragEndDetails with Diagnosticable {
/// Creates details for a [GestureTapDragEndCallback].
TapDragEndDetails({
this.velocity = Velocity.zero,
this.primaryVelocity,
required this.consecutiveTapCount,
}) : assert(
primaryVelocity == null
|| primaryVelocity == velocity.pixelsPerSecond.dx
|| primaryVelocity == velocity.pixelsPerSecond.dy,
);
/// The velocity the pointer was moving when it stopped contacting the screen.
///
/// Defaults to zero if not specified in the constructor.
final Velocity velocity;
/// The velocity the pointer was moving along the primary axis when it stopped
/// contacting the screen, in logical pixels per second.
///
/// If the [GestureTapDragEndCallback] is for a one-dimensional drag (e.g., a
/// horizontal or vertical drag), then this value contains the component of
/// [velocity] along the primary axis (e.g., horizontal or vertical,
/// respectively). Otherwise, if the [GestureTapDragEndCallback] is for a
/// two-dimensional drag (e.g., a pan), then this value is null.
///
/// Defaults to null if not specified in the constructor.
final double? primaryVelocity;
/// If this tap is in a series of taps, then this value represents
/// the number in the series this tap is.
final int consecutiveTapCount;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Velocity>('velocity', velocity));
properties.add(DiagnosticsProperty<double?>('primaryVelocity', primaryVelocity));
properties.add(DiagnosticsProperty<int>('consecutiveTapCount', consecutiveTapCount));
}
}
/// Signature for when the pointer that previously triggered a
/// [GestureTapDragDownCallback] did not complete.
///
/// Used by [BaseTapAndDragGestureRecognizer.onCancel].
typedef GestureCancelCallback = void Function();
// A mixin for [OneSequenceGestureRecognizer] that tracks the number of taps
// that occur in a series of [PointerEvent]s and the most recent set of
// [LogicalKeyboardKey]s pressed on the most recent tap down.
//
// A tap is tracked as part of a series of taps if:
//
// 1. The elapsed time between when a [PointerUpEvent] and the subsequent
// [PointerDownEvent] does not exceed [kDoubleTapTimeout].
// 2. The delta between the position tapped in the global coordinate system
// and the position that was tapped previously must be less than or equal
// to [kDoubleTapSlop].
//
// This mixin's state, i.e. the series of taps being tracked is reset when
// a tap is tracked that does not meet any of the specifications stated above.
mixin _TapStatusTrackerMixin on OneSequenceGestureRecognizer {
// Public state available to [OneSequenceGestureRecognizer].
// The [PointerDownEvent] that was most recently tracked in [addAllowedPointer].
//
// This value will be null if a [PointerDownEvent] has not been tracked yet in
// [addAllowedPointer] or the timer between two taps has elapsed.
//
// This value is only reset when the timer between a [PointerUpEvent] and the
// [PointerDownEvent] times out or when a new [PointerDownEvent] is tracked in
// [addAllowedPointer].
PointerDownEvent? get currentDown => _down;
// The [PointerUpEvent] that was most recently tracked in [handleEvent].
//
// This value will be null if a [PointerUpEvent] has not been tracked yet in
// [handleEvent] or the timer between two taps has elapsed.
//
// This value is only reset when the timer between a [PointerUpEvent] and the
// [PointerDownEvent] times out or when a new [PointerDownEvent] is tracked in
// [addAllowedPointer].
PointerUpEvent? get currentUp => _up;
// The number of consecutive taps that the most recently tracked [PointerDownEvent]
// in [currentDown] represents.
//
// This value defaults to zero, meaning a tap series is not currently being tracked.
//
// When this value is greater than zero it means [addAllowedPointer] has run
// and at least one [PointerDownEvent] belongs to the current series of taps
// being tracked.
//
// [addAllowedPointer] will either increment this value by `1` or set the value to `1`
// depending if the new [PointerDownEvent] is determined to be in the same series as the
// tap that preceded it. If too much time has elapsed between two taps, the recognizer has lost
// in the arena, the gesture has been cancelled, or the recognizer is being disposed then
// this value will be set to `0`, and a new series will begin.
int get consecutiveTapCount => _consecutiveTapCount;
// The upper limit for the [consecutiveTapCount]. When this limit is reached
// all tap related state is reset and a new tap series is tracked.
//
// If this value is null, [consecutiveTapCount] can grow infinitely large.
int? get maxConsecutiveTap;
// Private tap state tracked.
PointerDownEvent? _down;
PointerUpEvent? _up;
int _consecutiveTapCount = 0;
OffsetPair? _originPosition;
int? _previousButtons;
// For timing taps.
Timer? _consecutiveTapTimer;
Offset? _lastTapOffset;
/// {@template flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.onTapTrackStart}
/// Callback used to indicate that a tap tracking has started upon
/// a [PointerDownEvent].
/// {@endtemplate}
VoidCallback? onTapTrackStart;
/// {@template flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.onTapTrackReset}
/// Callback used to indicate that a tap tracking has been reset which
/// happens on the next [PointerDownEvent] after the timer between two taps
/// elapses, the recognizer loses the arena, the gesture is cancelled or
/// the recognizer is disposed of.
/// {@endtemplate}
VoidCallback? onTapTrackReset;
// When tracking a tap, the [consecutiveTapCount] is incremented if the given tap
// falls under the tolerance specifications and reset to 1 if not.
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
if (_consecutiveTapTimer != null && !_consecutiveTapTimer!.isActive) {
_tapTrackerReset();
}
if (maxConsecutiveTap == _consecutiveTapCount) {
_tapTrackerReset();
}
_up = null;
if (_down != null && !_representsSameSeries(event)) {
// The given tap does not match the specifications of the series of taps being tracked,
// reset the tap count and related state.
_consecutiveTapCount = 1;
} else {
_consecutiveTapCount += 1;
}
_consecutiveTapTimerStop();
// `_down` must be assigned in this method instead of [handleEvent],
// because [acceptGesture] might be called before [handleEvent],
// which may rely on `_down` to initiate a callback.
_trackTap(event);
}
@override
void handleEvent(PointerEvent event) {
if (event is PointerMoveEvent) {
final double computedSlop = computeHitSlop(event.kind, gestureSettings);
final bool isSlopPastTolerance = _getGlobalDistance(event, _originPosition) > computedSlop;
if (isSlopPastTolerance) {
_consecutiveTapTimerStop();
_previousButtons = null;
_lastTapOffset = null;
}
} else if (event is PointerUpEvent) {
_up = event;
if (_down != null) {
_consecutiveTapTimerStop();
_consecutiveTapTimerStart();
}
} else if (event is PointerCancelEvent) {
_tapTrackerReset();
}
}
@override
void rejectGesture(int pointer) {
_tapTrackerReset();
}
@override
void dispose() {
_tapTrackerReset();
super.dispose();
}
void _trackTap(PointerDownEvent event) {
_down = event;
_previousButtons = event.buttons;
_lastTapOffset = event.position;
_originPosition = OffsetPair(local: event.localPosition, global: event.position);
onTapTrackStart?.call();
}
bool _hasSameButton(int buttons) {
assert(_previousButtons != null);
if (buttons == _previousButtons!) {
return true;
} else {
return false;
}
}
bool _isWithinConsecutiveTapTolerance(Offset secondTapOffset) {
if (_lastTapOffset == null) {
return false;
}
final Offset difference = secondTapOffset - _lastTapOffset!;
return difference.distance <= kDoubleTapSlop;
}
bool _representsSameSeries(PointerDownEvent event) {
return _consecutiveTapTimer != null
&& _isWithinConsecutiveTapTolerance(event.position)
&& _hasSameButton(event.buttons);
}
void _consecutiveTapTimerStart() {
_consecutiveTapTimer ??= Timer(kDoubleTapTimeout, _consecutiveTapTimerTimeout);
}
void _consecutiveTapTimerStop() {
if (_consecutiveTapTimer != null) {
_consecutiveTapTimer!.cancel();
_consecutiveTapTimer = null;
}
}
void _consecutiveTapTimerTimeout() {
// The consecutive tap timer may time out before a tap down/tap up event is
// fired. In this case we should not reset the tap tracker state immediately.
// Instead we should reset the tap tracker on the next call to [addAllowedPointer],
// if the timer is no longer active.
}
void _tapTrackerReset() {
// The timer has timed out, i.e. the time between a [PointerUpEvent] and the subsequent
// [PointerDownEvent] exceeded the duration of [kDoubleTapTimeout], so the tap belonging
// to the [PointerDownEvent] cannot be considered part of the same tap series as the
// previous [PointerUpEvent].
_consecutiveTapTimerStop();
_previousButtons = null;
_originPosition = null;
_lastTapOffset = null;
_consecutiveTapCount = 0;
_down = null;
_up = null;
onTapTrackReset?.call();
}
}
/// A base class for gesture recognizers that recognize taps and movements.
///
/// Takes on the responsibilities of [TapGestureRecognizer] and
/// [DragGestureRecognizer] in one [GestureRecognizer].
///
/// ### Gesture arena behavior
///
/// [BaseTapAndDragGestureRecognizer] competes on the pointer events of
/// [kPrimaryButton] only when it has at least one non-null `onTap*`
/// or `onDrag*` callback.
///
/// It will declare defeat if it determines that a gesture is not a
/// tap (e.g. if the pointer is dragged too far while it's contacting the
/// screen) or a drag (e.g. if the pointer was not dragged far enough to
/// be considered a drag.
///
/// This recognizer will not immediately declare victory for every tap that it
/// recognizes, but it declares victory for every drag.
///
/// The recognizer will declare victory when all other recognizer's in
/// the arena have lost, if the timer of [kPressTimeout] elapses and a tap
/// series greater than 1 is being tracked, or until the pointer has moved
/// a sufficient global distance from the origin to be considered a drag.
///
/// If this recognizer loses the arena (either by declaring defeat or by
/// another recognizer declaring victory) while the pointer is contacting the
/// screen, it will fire [onCancel] instead of [onTapUp] or [onDragEnd].
///
/// ### When competing with `TapGestureRecognizer` and `DragGestureRecognizer`
///
/// Similar to [TapGestureRecognizer] and [DragGestureRecognizer],
/// [BaseTapAndDragGestureRecognizer] will not aggressively declare victory when it detects
/// a tap, so when it is competing with those gesture recognizers and others it has a chance
/// of losing.
///
/// When competing against [TapGestureRecognizer], if the pointer does not move past the tap
/// tolerance, then the recognizer that entered the arena first will win. In this case the
/// gesture detected is a tap. If the pointer does travel past the tap tolerance then this
/// recognizer will be declared winner by default. The gesture detected in this case is a drag.
///
/// When competing against [DragGestureRecognizer], if the pointer does not move a sufficient
/// global distance to be considered a drag, the recognizers will tie in the arena. If the
/// pointer does travel enough distance then the recognizer that entered the arena
/// first will win. The gesture detected in this case is a drag.
///
/// {@tool dartpad}
/// This example shows how to use the [TapAndPanGestureRecognizer] along with a
/// [RawGestureDetector] to scale a Widget.
///
/// ** See code in examples/api/lib/gestures/tap_and_drag/tap_and_drag.0.dart **
/// {@end-tool}
///
/// {@tool snippet}
///
/// This example shows how to hook up [TapAndPanGestureRecognizer]s' to nested
/// [RawGestureDetector]s'. It assumes that the code is being used inside a [State]
/// object with a `_last` field that is then displayed as the child of the gesture detector.
///
/// In this example, if the pointer has moved past the drag threshold, then the
/// the first [TapAndPanGestureRecognizer] instance to receive the [PointerEvent]
/// will win the arena because the recognizer will immediately declare victory.
///
/// The first one to receive the event in the example will depend on where on both
/// containers the pointer lands first. If your pointer begins in the overlapping
/// area of both containers, then the inner-most widget will receive the event first.
/// If your pointer begins in the yellow container then it will be the first to
/// receive the event.
///
/// If the pointer has not moved past the drag threshold, then the first recognizer
/// to enter the arena will win (i.e. they both tie and the gesture arena will call
/// [GestureArenaManager.sweep] so the first member of the arena will win).
///
/// ```dart
/// RawGestureDetector(
/// gestures: <Type, GestureRecognizerFactory>{
/// TapAndPanGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapAndPanGestureRecognizer>(
/// () => TapAndPanGestureRecognizer(),
/// (TapAndPanGestureRecognizer instance) {
/// instance
/// ..onTapDown = (TapDragDownDetails details) { setState(() { _last = 'down_a'; }); }
/// ..onDragStart = (TapDragStartDetails details) { setState(() { _last = 'drag_start_a'; }); }
/// ..onDragUpdate = (TapDragUpdateDetails details) { setState(() { _last = 'drag_update_a'; }); }
/// ..onDragEnd = (TapDragEndDetails details) { setState(() { _last = 'drag_end_a'; }); }
/// ..onTapUp = (TapDragUpDetails details) { setState(() { _last = 'up_a'; }); }
/// ..onCancel = () { setState(() { _last = 'cancel_a'; }); };
/// },
/// ),
/// },
/// child: Container(
/// width: 300.0,
/// height: 300.0,
/// color: Colors.yellow,
/// alignment: Alignment.center,
/// child: RawGestureDetector(
/// gestures: <Type, GestureRecognizerFactory>{
/// TapAndPanGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapAndPanGestureRecognizer>(
/// () => TapAndPanGestureRecognizer(),
/// (TapAndPanGestureRecognizer instance) {
/// instance
/// ..onTapDown = (TapDragDownDetails details) { setState(() { _last = 'down_b'; }); }
/// ..onDragStart = (TapDragStartDetails details) { setState(() { _last = 'drag_start_b'; }); }
/// ..onDragUpdate = (TapDragUpdateDetails details) { setState(() { _last = 'drag_update_b'; }); }
/// ..onDragEnd = (TapDragEndDetails details) { setState(() { _last = 'drag_end_b'; }); }
/// ..onTapUp = (TapDragUpDetails details) { setState(() { _last = 'up_b'; }); }
/// ..onCancel = () { setState(() { _last = 'cancel_b'; }); };
/// },
/// ),
/// },
/// child: Container(
/// width: 150.0,
/// height: 150.0,
/// color: Colors.blue,
/// child: Text(_last),
/// ),
/// ),
/// ),
/// )
/// ```
/// {@end-tool}
sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognizer with _TapStatusTrackerMixin {
/// Creates a tap and drag gesture recognizer.
///
/// {@macro flutter.gestures.GestureRecognizer.supportedDevices}
BaseTapAndDragGestureRecognizer({
super.debugOwner,
super.supportedDevices,
super.allowedButtonsFilter,
}) : _deadline = kPressTimeout,
dragStartBehavior = DragStartBehavior.start;
/// Configure the behavior of offsets passed to [onDragStart].
///
/// If set to [DragStartBehavior.start], the [onDragStart] callback will be called
/// with the position of the pointer at the time this gesture recognizer won
/// the arena. If [DragStartBehavior.down], [onDragStart] 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].
///
/// See also:
///
/// * [DragGestureRecognizer.dragStartBehavior], which includes more details and an example.
DragStartBehavior dragStartBehavior;
/// The frequency at which the [onDragUpdate] callback is called.
///
/// The value defaults to null, meaning there is no delay for [onDragUpdate] callback.
Duration? dragUpdateThrottleFrequency;
/// An upper bound for the amount of taps that can belong to one tap series.
///
/// When this limit is reached the series of taps being tracked by this
/// recognizer will be reset.
@override
int? maxConsecutiveTap;
/// {@macro flutter.gestures.tap.TapGestureRecognizer.onTapDown}
///
/// This triggers after the down event, once a short timeout ([kPressTimeout]) has
/// elapsed, or once the gestures has won the arena, whichever comes first.
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [TapDragDownDetails] object.
///
/// {@template flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
/// The number of consecutive taps, and the keys that were pressed on tap down
/// are also provided in the callback's `details` argument.
/// {@endtemplate}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragDownDetails], which is passed as an argument to this callback.
GestureTapDragDownCallback? onTapDown;
/// {@macro flutter.gestures.tap.TapGestureRecognizer.onTapUp}
///
/// This triggers on the up event, if the recognizer wins the arena with it
/// or has previously won.
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [TapDragUpDetails] object.
///
/// {@macro flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragUpDetails], which is passed as an argument to this callback.
GestureTapDragUpCallback? onTapUp;
/// {@macro flutter.gestures.monodrag.DragGestureRecognizer.onStart}
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [TapDragStartDetails] object. The [dragStartBehavior]
/// determines this position.
///
/// {@macro flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragStartDetails], which is passed as an argument to this callback.
GestureTapDragStartCallback? onDragStart;
/// {@macro flutter.gestures.monodrag.DragGestureRecognizer.onUpdate}
///
/// The distance traveled by the pointer since the last update is provided in
/// the callback's `details` argument, which is a [TapDragUpdateDetails] object.
///
/// {@macro flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragUpdateDetails], which is passed as an argument to this callback.
GestureTapDragUpdateCallback? onDragUpdate;
/// {@macro flutter.gestures.monodrag.DragGestureRecognizer.onEnd}
///
/// The velocity is provided in the callback's `details` argument, which is a
/// [TapDragEndDetails] object.
///
/// {@macro flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.tapStatusTrackerData}
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [TapDragEndDetails], which is passed as an argument to this callback.
GestureTapDragEndCallback? onDragEnd;
/// The pointer that previously triggered [onTapDown] did not complete.
///
/// This is called when a [PointerCancelEvent] is tracked when the [onTapDown] callback
/// was previously called.
///
/// It may also be called if a [PointerUpEvent] is tracked after the pointer has moved
/// past the tap tolerance but not past the drag tolerance, and the recognizer has not
/// yet won the arena.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
GestureCancelCallback? onCancel;
// Tap related state.
bool _pastSlopTolerance = false;
bool _sentTapDown = false;
bool _wonArenaForPrimaryPointer = false;
// Primary pointer being tracked by this recognizer.
int? _primaryPointer;
Timer? _deadlineTimer;
// The recognizer will call [onTapDown] after this amount of time has elapsed
// since starting to track the primary pointer.
//
// [onTapDown] will not be called if the primary pointer is
// accepted, rejected, or all pointers are up or canceled before [_deadline].
final Duration _deadline;
// Drag related state.
_DragState _dragState = _DragState.ready;
PointerEvent? _start;
late OffsetPair _initialPosition;
late double _globalDistanceMoved;
late double _globalDistanceMovedAllAxes;
OffsetPair? _correctedPosition;
// For drag update throttle.
TapDragUpdateDetails? _lastDragUpdateDetails;
Timer? _dragUpdateThrottleTimer;
final Set<int> _acceptedActivePointers = <int>{};
Offset _getDeltaForDetails(Offset delta);
double? _getPrimaryValueFromOffset(Offset value);
bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind);
// Drag updates may require throttling to avoid excessive updating, such as for text layouts in text
// fields. The frequency of invocations is controlled by the [dragUpdateThrottleFrequency].
//
// Once the drag gesture ends, any pending drag update will be fired
// immediately. See [_checkDragEnd].
void _handleDragUpdateThrottled() {
assert(_lastDragUpdateDetails != null);
if (onDragUpdate != null) {
invokeCallback<void>('onDragUpdate', () => onDragUpdate!(_lastDragUpdateDetails!));
}
_dragUpdateThrottleTimer = null;
_lastDragUpdateDetails = null;
}
@override
bool isPointerAllowed(PointerEvent event) {
if (_primaryPointer == null) {
switch (event.buttons) {
case kPrimaryButton:
if (onTapDown == null &&
onDragStart == null &&
onDragUpdate == null &&
onDragEnd == null &&
onTapUp == null &&
onCancel == null) {
return false;
}
default:
return false;
}
} else {
if (event.pointer != _primaryPointer) {
return false;
}
}
return super.isPointerAllowed(event as PointerDownEvent);
}
@override
void addAllowedPointer(PointerDownEvent event) {
if (_dragState == _DragState.ready) {
super.addAllowedPointer(event);
_primaryPointer = event.pointer;
_globalDistanceMoved = 0.0;
_globalDistanceMovedAllAxes = 0.0;
_dragState = _DragState.possible;
_initialPosition = OffsetPair(global: event.position, local: event.localPosition);
_deadlineTimer = Timer(_deadline, () => _didExceedDeadlineWithEvent(event));
}
}
@override
void handleNonAllowedPointer(PointerDownEvent event) {
// There can be multiple drags simultaneously. Their effects are combined.
if (event.buttons != kPrimaryButton) {
if (!_wonArenaForPrimaryPointer) {
super.handleNonAllowedPointer(event);
}
}
}
@override
void acceptGesture(int pointer) {
if (pointer != _primaryPointer) {
return;
}
_stopDeadlineTimer();
assert(!_acceptedActivePointers.contains(pointer));
_acceptedActivePointers.add(pointer);
// Called when this recognizer is accepted by the [GestureArena].
if (currentDown != null) {
_checkTapDown(currentDown!);
}
_wonArenaForPrimaryPointer = true;
// resolve(GestureDisposition.accepted) will be called when the [PointerMoveEvent] has
// moved a sufficient global distance.
if (_start != null) {
assert(_dragState == _DragState.accepted);
assert(currentUp == null);
_acceptDrag(_start!);
}
if (currentUp != null) {
_checkTapUp(currentUp!);
}
}
@override
void didStopTrackingLastPointer(int pointer) {
switch (_dragState) {
case _DragState.ready:
_checkCancel();
resolve(GestureDisposition.rejected);
case _DragState.possible:
if (_pastSlopTolerance) {
// This means the pointer was not accepted as a tap.
if (_wonArenaForPrimaryPointer) {
// If the recognizer has already won the arena for the primary pointer being tracked
// but the pointer has exceeded the tap tolerance, then the pointer is accepted as a
// drag gesture.
if (currentDown != null) {
if (!_acceptedActivePointers.remove(pointer)) {
resolvePointer(pointer, GestureDisposition.rejected);
}
_dragState = _DragState.accepted;
_acceptDrag(currentDown!);
_checkDragEnd();
}
} else {
_checkCancel();
resolve(GestureDisposition.rejected);
}
} else {
// The pointer is accepted as a tap.
if (currentUp != null) {
_checkTapUp(currentUp!);
}
}
case _DragState.accepted:
// For the case when the pointer has been accepted as a drag.
// Meaning [_checkTapDown] and [_checkDragStart] have already ran.
_checkDragEnd();
}
_stopDeadlineTimer();
_dragState = _DragState.ready;
_pastSlopTolerance = false;
}
@override
void handleEvent(PointerEvent event) {
if (event.pointer != _primaryPointer) {
return;
}
super.handleEvent(event);
if (event is PointerMoveEvent) {
// Receiving a [PointerMoveEvent], does not automatically mean the pointer
// being tracked is doing a drag gesture. There is some drift that can happen
// between the initial [PointerDownEvent] and subsequent [PointerMoveEvent]s.
// Accessing [_pastSlopTolerance] lets us know if our tap has moved past the
// acceptable tolerance. If the pointer does not move past this tolerance than
// it is not considered a drag.
//
// To be recognized as a drag, the [PointerMoveEvent] must also have moved
// a sufficient global distance from the initial [PointerDownEvent] to be
// accepted as a drag. This logic is handled in [_hasSufficientGlobalDistanceToAccept].
//
// The recognizer will also detect the gesture as a drag when the pointer
// has been accepted and it has moved past the [slopTolerance] but has not moved
// a sufficient global distance from the initial position to be considered a drag.
// In this case since the gesture cannot be a tap, it defaults to a drag.
final double computedSlop = computeHitSlop(event.kind, gestureSettings);
_pastSlopTolerance = _pastSlopTolerance || _getGlobalDistance(event, _initialPosition) > computedSlop;
if (_dragState == _DragState.accepted) {
_checkDragUpdate(event);
} else if (_dragState == _DragState.possible) {
if (_start == null) {
// Only check for a drag if the start of a drag was not already identified.
_checkDrag(event);
}
// This can occur when the recognizer is accepted before a [PointerMoveEvent] has been
// received that moves the pointer a sufficient global distance to be considered a drag.
if (_start != null) {
_acceptDrag(_start!);
}
}
} else if (event is PointerUpEvent) {
if (_dragState == _DragState.possible) {
// The drag has not been accepted before a [PointerUpEvent], therefore the recognizer
// attempts to recognize a tap.
stopTrackingIfPointerNoLongerDown(event);
} else if (_dragState == _DragState.accepted) {
_giveUpPointer(event.pointer);
}
} else if (event is PointerCancelEvent) {
_dragState = _DragState.ready;
_giveUpPointer(event.pointer);
}
}
@override
void rejectGesture(int pointer) {
if (pointer != _primaryPointer) {
return;
}
super.rejectGesture(pointer);
_stopDeadlineTimer();
_giveUpPointer(pointer);
_resetTaps();
_resetDragUpdateThrottle();
}
@override
void dispose() {
_stopDeadlineTimer();
_resetDragUpdateThrottle();
super.dispose();
}
@override
String get debugDescription => 'tap_and_drag';
void _acceptDrag(PointerEvent event) {
if (!_wonArenaForPrimaryPointer) {
return;
}
if (dragStartBehavior == DragStartBehavior.start) {
_initialPosition = _initialPosition + OffsetPair(global: event.delta, local: event.localDelta);
}
_checkDragStart(event);
if (event.localDelta != Offset.zero) {
final Matrix4? localToGlobal = event.transform != null ? Matrix4.tryInvert(event.transform!) : null;
final Offset correctedLocalPosition = _initialPosition.local + event.localDelta;
final Offset globalUpdateDelta = PointerEvent.transformDeltaViaPositions(
untransformedEndPosition: correctedLocalPosition,
untransformedDelta: event.localDelta,
transform: localToGlobal,
);
final OffsetPair updateDelta = OffsetPair(local: event.localDelta, global: globalUpdateDelta);
_correctedPosition = _initialPosition + updateDelta; // Only adds delta for down behaviour
_checkDragUpdate(event);
_correctedPosition = null;
}
}
void _checkDrag(PointerMoveEvent event) {
final Matrix4? localToGlobalTransform = event.transform == null ? null : Matrix4.tryInvert(event.transform!);
final Offset movedLocally = _getDeltaForDetails(event.localDelta);
_globalDistanceMoved += PointerEvent.transformDeltaViaPositions(
transform: localToGlobalTransform,
untransformedDelta: movedLocally,
untransformedEndPosition: event.localPosition
).distance * (_getPrimaryValueFromOffset(movedLocally) ?? 1).sign;
_globalDistanceMovedAllAxes += PointerEvent.transformDeltaViaPositions(
transform: localToGlobalTransform,
untransformedDelta: event.localDelta,
untransformedEndPosition: event.localPosition
).distance * 1.sign;
if (_hasSufficientGlobalDistanceToAccept(event.kind)
|| (_wonArenaForPrimaryPointer && _globalDistanceMovedAllAxes.abs() > computePanSlop(event.kind, gestureSettings))) {
_start = event;
_dragState = _DragState.accepted;
if (!_wonArenaForPrimaryPointer) {
resolve(GestureDisposition.accepted);
}
}
}
void _checkTapDown(PointerDownEvent event) {
if (_sentTapDown) {
return;
}
final TapDragDownDetails details = TapDragDownDetails(
globalPosition: event.position,
localPosition: event.localPosition,
kind: getKindForPointer(event.pointer),
consecutiveTapCount: consecutiveTapCount,
);
if (onTapDown != null) {
invokeCallback('onTapDown', () => onTapDown!(details));
}
_sentTapDown = true;
}
void _checkTapUp(PointerUpEvent event) {
if (!_wonArenaForPrimaryPointer) {
return;
}
final TapDragUpDetails upDetails = TapDragUpDetails(
kind: event.kind,
globalPosition: event.position,
localPosition: event.localPosition,
consecutiveTapCount: consecutiveTapCount,
);
if (onTapUp != null) {
invokeCallback('onTapUp', () => onTapUp!(upDetails));
}
_resetTaps();
if (!_acceptedActivePointers.remove(event.pointer)) {
resolvePointer(event.pointer, GestureDisposition.rejected);
}
}
void _checkDragStart(PointerEvent event) {
if (onDragStart != null) {
final TapDragStartDetails details = TapDragStartDetails(
sourceTimeStamp: event.timeStamp,
globalPosition: _initialPosition.global,
localPosition: _initialPosition.local,
kind: getKindForPointer(event.pointer),
consecutiveTapCount: consecutiveTapCount,
);
invokeCallback<void>('onDragStart', () => onDragStart!(details));
}
_start = null;
}
void _checkDragUpdate(PointerEvent event) {
final Offset globalPosition = _correctedPosition != null ? _correctedPosition!.global : event.position;
final Offset localPosition = _correctedPosition != null ? _correctedPosition!.local : event.localPosition;
final TapDragUpdateDetails details = TapDragUpdateDetails(
sourceTimeStamp: event.timeStamp,
delta: event.localDelta,
globalPosition: globalPosition,
kind: getKindForPointer(event.pointer),
localPosition: localPosition,
offsetFromOrigin: globalPosition - _initialPosition.global,
localOffsetFromOrigin: localPosition - _initialPosition.local,
consecutiveTapCount: consecutiveTapCount,
);
if (dragUpdateThrottleFrequency != null) {
_lastDragUpdateDetails = details;
// Only schedule a new timer if there's not one pending.
_dragUpdateThrottleTimer ??= Timer(dragUpdateThrottleFrequency!, _handleDragUpdateThrottled);
} else {
if (onDragUpdate != null) {
invokeCallback<void>('onDragUpdate', () => onDragUpdate!(details));
}
}
}
void _checkDragEnd() {
if (_dragUpdateThrottleTimer != null) {
// If there's already an update scheduled, trigger it immediately and
// cancel the timer.
_dragUpdateThrottleTimer!.cancel();
_handleDragUpdateThrottled();
}
final TapDragEndDetails endDetails =
TapDragEndDetails(
primaryVelocity: 0.0,
consecutiveTapCount: consecutiveTapCount,
);
if (onDragEnd != null) {
invokeCallback<void>('onDragEnd', () => onDragEnd!(endDetails));
}
_resetTaps();
_resetDragUpdateThrottle();
}
void _checkCancel() {
if (!_sentTapDown) {
// Do not fire tap cancel if [onTapDown] was never called.
return;
}
if (onCancel != null) {
invokeCallback('onCancel', onCancel!);
}
_resetDragUpdateThrottle();
_resetTaps();
}
void _didExceedDeadlineWithEvent(PointerDownEvent event) {
_didExceedDeadline();
}
void _didExceedDeadline() {
if (currentDown != null) {
_checkTapDown(currentDown!);
if (consecutiveTapCount > 1) {
// If our consecutive tap count is greater than 1, i.e. is a double tap or greater,
// then this recognizer declares victory to prevent the [LongPressGestureRecognizer]
// from declaring itself the winner if a double tap is held for too long.
resolve(GestureDisposition.accepted);
}
}
}
void _giveUpPointer(int pointer) {
stopTrackingPointer(pointer);
// If the pointer was never accepted, then it is rejected since this recognizer is no longer
// interested in winning the gesture arena for it.
if (!_acceptedActivePointers.remove(pointer)) {
resolvePointer(pointer, GestureDisposition.rejected);
}
}
void _resetTaps() {
_sentTapDown = false;
_wonArenaForPrimaryPointer = false;
_primaryPointer = null;
}
void _resetDragUpdateThrottle() {
if (dragUpdateThrottleFrequency == null) {
return;
}
_lastDragUpdateDetails = null;
if (_dragUpdateThrottleTimer != null) {
_dragUpdateThrottleTimer!.cancel();
_dragUpdateThrottleTimer = null;
}
}
void _stopDeadlineTimer() {
if (_deadlineTimer != null) {
_deadlineTimer!.cancel();
_deadlineTimer = null;
}
}
}
/// Recognizes taps along with movement in the horizontal direction.
///
/// Before this recognizer has won the arena for the primary pointer being tracked,
/// it will only accept a drag on the horizontal axis. If a drag is detected after
/// this recognizer has won the arena then it will accept a drag on any axis.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], for the class that provides the main
/// implementation details of this recognizer.
/// * [TapAndPanGestureRecognizer], for a similar recognizer that accepts a drag
/// on any axis regardless if the recognizer has won the arena for the primary
/// pointer being tracked.
/// * [HorizontalDragGestureRecognizer], for a similar recognizer that only recognizes
/// horizontal movement.
class TapAndHorizontalDragGestureRecognizer extends BaseTapAndDragGestureRecognizer {
/// Create a gesture recognizer for interactions in the horizontal axis.
///
/// {@macro flutter.gestures.GestureRecognizer.supportedDevices}
TapAndHorizontalDragGestureRecognizer({
super.debugOwner,
super.supportedDevices,
});
@override
bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind) {
return _globalDistanceMoved.abs() > computeHitSlop(pointerDeviceKind, gestureSettings);
}
@override
Offset _getDeltaForDetails(Offset delta) => Offset(delta.dx, 0.0);
@override
double _getPrimaryValueFromOffset(Offset value) => value.dx;
@override
String get debugDescription => 'tap and horizontal drag';
}
/// {@template flutter.gestures.selectionrecognizers.TapAndPanGestureRecognizer}
/// Recognizes taps along with both horizontal and vertical movement.
///
/// This recognizer will accept a drag on any axis, regardless if it has won the
/// arena for the primary pointer being tracked.
///
/// See also:
///
/// * [BaseTapAndDragGestureRecognizer], for the class that provides the main
/// implementation details of this recognizer.
/// * [TapAndHorizontalDragGestureRecognizer], for a similar recognizer that
/// only accepts horizontal drags before it has won the arena for the primary
/// pointer being tracked.
/// * [PanGestureRecognizer], for a similar recognizer that only recognizes
/// movement.
/// {@endtemplate}
class TapAndPanGestureRecognizer extends BaseTapAndDragGestureRecognizer {
/// Create a gesture recognizer for interactions on a plane.
TapAndPanGestureRecognizer({
super.debugOwner,
super.supportedDevices,
});
@override
bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind) {
return _globalDistanceMoved.abs() > computePanSlop(pointerDeviceKind, gestureSettings);
}
@override
Offset _getDeltaForDetails(Offset delta) => delta;
@override
double? _getPrimaryValueFromOffset(Offset value) => null;
@override
String get debugDescription => 'tap and pan';
}
@Deprecated(
'Use TapAndPanGestureRecognizer instead. '
'TapAndPanGestureRecognizer works exactly the same but has a more disambiguated name from BaseTapAndDragGestureRecognizer. '
'This feature was deprecated after v3.9.0-19.0.pre.'
)
/// {@macro flutter.gestures.selectionrecognizers.TapAndPanGestureRecognizer}
class TapAndDragGestureRecognizer extends BaseTapAndDragGestureRecognizer {
/// Create a gesture recognizer for interactions on a plane.
@Deprecated(
'Use TapAndPanGestureRecognizer instead. '
'TapAndPanGestureRecognizer works exactly the same but has a more disambiguated name from BaseTapAndDragGestureRecognizer. '
'This feature was deprecated after v3.9.0-19.0.pre.'
)
TapAndDragGestureRecognizer({
super.debugOwner,
super.supportedDevices,
});
@override
bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind) {
return _globalDistanceMoved.abs() > computePanSlop(pointerDeviceKind, gestureSettings);
}
@override
Offset _getDeltaForDetails(Offset delta) => delta;
@override
double? _getPrimaryValueFromOffset(Offset value) => null;
@override
String get debugDescription => 'tap and pan';
}
| flutter/packages/flutter/lib/src/gestures/tap_and_drag.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/gestures/tap_and_drag.dart",
"repo_id": "flutter",
"token_count": 17711
} | 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.
// 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 _$home_menu = _AnimatedIconData(
Size(48.0, 48.0),
<_PathFrames>[
_PathFrames(
opacities: <double>[
0.0,
0.0,
0.0,
0.0,
0.0,
0.634146341463,
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(41.961602748986124, 36.01074618636323),
Offset(41.61012274691143, 36.52041429443682),
Offset(40.73074694162982, 37.67330625857439),
Offset(38.95361640675702, 39.597004636313734),
Offset(35.56126879040947, 42.254157368159426),
Offset(29.45217770721976, 44.90815523939214),
Offset(20.31425476555182, 45.290666483987),
Offset(11.333081294378362, 41.505038353879655),
Offset(5.639760014140567, 35.39204919789558),
Offset(3.1052482171005202, 29.50332128779013),
Offset(2.404116971035613, 24.703586146049652),
Offset(2.598975684223376, 21.02118219738726),
Offset(3.169562607312212, 18.258042555457294),
Offset(3.8457725409130035, 16.209986341924132),
Offset(4.491857018848872, 14.709706425920167),
Offset(5.042760982134354, 13.631765527094924),
Offset(5.471212748718976, 12.884189626374933),
Offset(5.770140143051716, 12.400456609777674),
Offset(5.943251827328922, 12.132774431470317),
Offset(5.999943741061273, 12.046959719775653),
Offset(5.9999999999999964, 12.046875000000004),
],
),
_PathCubicTo(
<Offset>[
Offset(41.961602748986124, 36.01074618636323),
Offset(41.61012274691143, 36.52041429443682),
Offset(40.73074694162982, 37.67330625857439),
Offset(38.95361640675702, 39.597004636313734),
Offset(35.56126879040947, 42.254157368159426),
Offset(29.45217770721976, 44.90815523939214),
Offset(20.31425476555182, 45.290666483987),
Offset(11.333081294378362, 41.505038353879655),
Offset(5.639760014140567, 35.39204919789558),
Offset(3.1052482171005202, 29.50332128779013),
Offset(2.404116971035613, 24.703586146049652),
Offset(2.598975684223376, 21.02118219738726),
Offset(3.169562607312212, 18.258042555457294),
Offset(3.8457725409130035, 16.209986341924132),
Offset(4.491857018848872, 14.709706425920167),
Offset(5.042760982134354, 13.631765527094924),
Offset(5.471212748718976, 12.884189626374933),
Offset(5.770140143051716, 12.400456609777674),
Offset(5.943251827328922, 12.132774431470317),
Offset(5.999943741061273, 12.046959719775653),
Offset(5.9999999999999964, 12.046875000000004),
],
<Offset>[
Offset(41.97427088111201, 32.057641484479724),
Offset(41.73604180244445, 32.56929525585058),
Offset(41.121377806968006, 33.73952883824795),
Offset(39.81729775857236, 35.739382079848234),
Offset(37.1732602008072, 38.64463095068733),
Offset(32.08695737071304, 41.96110020250069),
Offset(23.93217304852415, 43.69759882586336),
Offset(15.2830121061518, 41.66392148019527),
Offset(9.234232376942689, 37.03733509970011),
Offset(6.058741440847815, 32.130881951771805),
Offset(4.6970485662914285, 27.923782097401467),
Offset(4.310954600883996, 24.584372545170346),
Offset(4.402665831815483, 22.013925101989418),
Offset(4.698295162721713, 20.070090284168355),
Offset(5.0503340012927325, 18.62318323378621),
Offset(5.38119368862878, 17.57037702974403),
Offset(5.652345022660288, 16.833162703639687),
Offset(5.847293032367528, 16.35282864404965),
Offset(5.962087095621268, 16.085854559458284),
Offset(5.999962347024592, 16.000084719731866),
Offset(5.9999999999999964, 16.000000000000004),
],
<Offset>[
Offset(41.97427088111201, 32.057641484479724),
Offset(41.73604180244445, 32.56929525585058),
Offset(41.121377806968006, 33.73952883824795),
Offset(39.81729775857236, 35.739382079848234),
Offset(37.1732602008072, 38.64463095068733),
Offset(32.08695737071304, 41.96110020250069),
Offset(23.93217304852415, 43.69759882586336),
Offset(15.2830121061518, 41.66392148019527),
Offset(9.234232376942689, 37.03733509970011),
Offset(6.058741440847815, 32.130881951771805),
Offset(4.6970485662914285, 27.923782097401467),
Offset(4.310954600883996, 24.584372545170346),
Offset(4.402665831815483, 22.013925101989418),
Offset(4.698295162721713, 20.070090284168355),
Offset(5.0503340012927325, 18.62318323378621),
Offset(5.38119368862878, 17.57037702974403),
Offset(5.652345022660288, 16.833162703639687),
Offset(5.847293032367528, 16.35282864404965),
Offset(5.962087095621268, 16.085854559458284),
Offset(5.999962347024592, 16.000084719731866),
Offset(5.9999999999999964, 16.000000000000004),
],
),
_PathCubicTo(
<Offset>[
Offset(41.97427088111201, 32.057641484479724),
Offset(41.73604180244445, 32.56929525585058),
Offset(41.121377806968006, 33.73952883824795),
Offset(39.81729775857236, 35.739382079848234),
Offset(37.1732602008072, 38.64463095068733),
Offset(32.08695737071304, 41.96110020250069),
Offset(23.93217304852415, 43.69759882586336),
Offset(15.2830121061518, 41.66392148019527),
Offset(9.234232376942689, 37.03733509970011),
Offset(6.058741440847815, 32.130881951771805),
Offset(4.6970485662914285, 27.923782097401467),
Offset(4.310954600883996, 24.584372545170346),
Offset(4.402665831815483, 22.013925101989418),
Offset(4.698295162721713, 20.070090284168355),
Offset(5.0503340012927325, 18.62318323378621),
Offset(5.38119368862878, 17.57037702974403),
Offset(5.652345022660288, 16.833162703639687),
Offset(5.847293032367528, 16.35282864404965),
Offset(5.962087095621268, 16.085854559458284),
Offset(5.999962347024592, 16.000084719731866),
Offset(5.9999999999999964, 16.000000000000004),
],
<Offset>[
Offset(5.9744557303626635, 31.942276360297758),
Offset(5.75430953010175, 31.42258575407952),
Offset(5.297570785497186, 30.182163171294633),
Offset(4.687011710760039, 27.874078385846133),
Offset(4.3023160669901515, 23.964677553231365),
Offset(5.248954188903129, 17.96690121163705),
Offset(9.424552952409986, 10.750232327965165),
Offset(16.729916149753336, 5.693010055981826),
Offset(24.217389364126984, 4.303484017106875),
Offset(29.987199029044564, 5.234248009029647),
Offset(34.02246940389847, 7.042697530328738),
Offset(36.75992915144614, 8.993860987913147),
Offset(38.606434160708815, 10.7844000851691),
Offset(39.851178494463575, 12.30640601283526),
Offset(40.68926904209655, 13.537290081412095),
Offset(41.24902334121195, 14.488365346885672),
Offset(41.61453462747447, 15.183641916442898),
Offset(41.840435984789025, 15.650218932651905),
Offset(41.96167845880022, 15.914327056906625),
Offset(41.99996234662585, 15.999915280445354),
Offset(42.0, 15.999999999999996),
],
<Offset>[
Offset(5.9744557303626635, 31.942276360297758),
Offset(5.75430953010175, 31.42258575407952),
Offset(5.297570785497186, 30.182163171294633),
Offset(4.687011710760039, 27.874078385846133),
Offset(4.3023160669901515, 23.964677553231365),
Offset(5.248954188903129, 17.96690121163705),
Offset(9.424552952409986, 10.750232327965165),
Offset(16.729916149753336, 5.693010055981826),
Offset(24.217389364126984, 4.303484017106875),
Offset(29.987199029044564, 5.234248009029647),
Offset(34.02246940389847, 7.042697530328738),
Offset(36.75992915144614, 8.993860987913147),
Offset(38.606434160708815, 10.7844000851691),
Offset(39.851178494463575, 12.30640601283526),
Offset(40.68926904209655, 13.537290081412095),
Offset(41.24902334121195, 14.488365346885672),
Offset(41.61453462747447, 15.183641916442898),
Offset(41.840435984789025, 15.650218932651905),
Offset(41.96167845880022, 15.914327056906625),
Offset(41.99996234662585, 15.999915280445354),
Offset(42.0, 15.999999999999996),
],
),
_PathCubicTo(
<Offset>[
Offset(5.9744557303626635, 31.942276360297758),
Offset(5.75430953010175, 31.42258575407952),
Offset(5.297570785497186, 30.182163171294633),
Offset(4.687011710760039, 27.874078385846133),
Offset(4.3023160669901515, 23.964677553231365),
Offset(5.248954188903129, 17.96690121163705),
Offset(9.424552952409986, 10.750232327965165),
Offset(16.729916149753336, 5.693010055981826),
Offset(24.217389364126984, 4.303484017106875),
Offset(29.987199029044564, 5.234248009029647),
Offset(34.02246940389847, 7.042697530328738),
Offset(36.75992915144614, 8.993860987913147),
Offset(38.606434160708815, 10.7844000851691),
Offset(39.851178494463575, 12.30640601283526),
Offset(40.68926904209655, 13.537290081412095),
Offset(41.24902334121195, 14.488365346885672),
Offset(41.61453462747447, 15.183641916442898),
Offset(41.840435984789025, 15.650218932651905),
Offset(41.96167845880022, 15.914327056906625),
Offset(41.99996234662585, 15.999915280445354),
Offset(42.0, 15.999999999999996),
],
<Offset>[
Offset(5.96181263407102, 35.88756860229611),
Offset(5.628639326457137, 35.36589625701638),
Offset(4.907711917916583, 34.10816632794454),
Offset(3.825037239086633, 31.72407718231862),
Offset(2.6935104103679173, 27.567070519285533),
Offset(2.6193815998436385, 20.90813202908801),
Offset(5.813784705570013, 12.34015163103323),
Offset(12.787791525354942, 5.534440927939556),
Offset(20.630020701646604, 2.66144966846797),
Offset(27.039542748427206, 2.6118801526843),
Offset(31.73406929400877, 3.8288656025961956),
Offset(35.05133359232832, 5.4377125182877375),
Offset(37.37576789909982, 7.035940231416685),
Offset(39.00034069997069, 8.453930734508514),
Offset(40.13189576910416, 9.631547417435115),
Offset(40.91125947405842, 10.557537661435477),
Offset(41.43376032245399, 11.242473133797246),
Offset(41.76343557153906, 11.705657910305364),
Offset(41.94288041435826, 11.969059340238793),
Offset(41.9999437774332, 12.054602780489052),
Offset(42.0, 12.054687499999996),
],
<Offset>[
Offset(5.96181263407102, 35.88756860229611),
Offset(5.628639326457137, 35.36589625701638),
Offset(4.907711917916583, 34.10816632794454),
Offset(3.825037239086633, 31.72407718231862),
Offset(2.6935104103679173, 27.567070519285533),
Offset(2.6193815998436385, 20.90813202908801),
Offset(5.813784705570013, 12.34015163103323),
Offset(12.787791525354942, 5.534440927939556),
Offset(20.630020701646604, 2.66144966846797),
Offset(27.039542748427206, 2.6118801526843),
Offset(31.73406929400877, 3.8288656025961956),
Offset(35.05133359232832, 5.4377125182877375),
Offset(37.37576789909982, 7.035940231416685),
Offset(39.00034069997069, 8.453930734508514),
Offset(40.13189576910416, 9.631547417435115),
Offset(40.91125947405842, 10.557537661435477),
Offset(41.43376032245399, 11.242473133797246),
Offset(41.76343557153906, 11.705657910305364),
Offset(41.94288041435826, 11.969059340238793),
Offset(41.9999437774332, 12.054602780489052),
Offset(42.0, 12.054687499999996),
],
),
_PathCubicTo(
<Offset>[
Offset(5.96181263407102, 35.88756860229611),
Offset(5.628639326457137, 35.36589625701638),
Offset(4.907711917916583, 34.10816632794454),
Offset(3.825037239086633, 31.72407718231862),
Offset(2.6935104103679173, 27.567070519285533),
Offset(2.6193815998436385, 20.90813202908801),
Offset(5.813784705570013, 12.34015163103323),
Offset(12.787791525354942, 5.534440927939556),
Offset(20.630020701646604, 2.66144966846797),
Offset(27.039542748427206, 2.6118801526843),
Offset(31.73406929400877, 3.8288656025961956),
Offset(35.05133359232832, 5.4377125182877375),
Offset(37.37576789909982, 7.035940231416685),
Offset(39.00034069997069, 8.453930734508514),
Offset(40.13189576910416, 9.631547417435115),
Offset(40.91125947405842, 10.557537661435477),
Offset(41.43376032245399, 11.242473133797246),
Offset(41.76343557153906, 11.705657910305364),
Offset(41.94288041435826, 11.969059340238793),
Offset(41.9999437774332, 12.054602780489052),
Offset(42.0, 12.054687499999996),
],
<Offset>[
Offset(41.961602748986124, 36.01074618636323),
Offset(41.61012274691143, 36.52041429443682),
Offset(40.73074694162982, 37.67330625857439),
Offset(38.95361640675702, 39.597004636313734),
Offset(35.56126879040947, 42.254157368159426),
Offset(29.45217770721976, 44.90815523939214),
Offset(20.31425476555182, 45.290666483987),
Offset(11.333081294378362, 41.505038353879655),
Offset(5.639760014140567, 35.39204919789558),
Offset(3.1052482171005202, 29.50332128779013),
Offset(2.404116971035613, 24.703586146049652),
Offset(2.598975684223376, 21.02118219738726),
Offset(3.169562607312212, 18.258042555457294),
Offset(3.8457725409130035, 16.209986341924132),
Offset(4.491857018848872, 14.709706425920167),
Offset(5.042760982134354, 13.631765527094924),
Offset(5.471212748718976, 12.884189626374933),
Offset(5.770140143051716, 12.400456609777674),
Offset(5.943251827328922, 12.132774431470317),
Offset(5.999943741061273, 12.046959719775653),
Offset(5.9999999999999964, 12.046875000000004),
],
<Offset>[
Offset(41.961602748986124, 36.01074618636323),
Offset(41.61012274691143, 36.52041429443682),
Offset(40.73074694162982, 37.67330625857439),
Offset(38.95361640675702, 39.597004636313734),
Offset(35.56126879040947, 42.254157368159426),
Offset(29.45217770721976, 44.90815523939214),
Offset(20.31425476555182, 45.290666483987),
Offset(11.333081294378362, 41.505038353879655),
Offset(5.639760014140567, 35.39204919789558),
Offset(3.1052482171005202, 29.50332128779013),
Offset(2.404116971035613, 24.703586146049652),
Offset(2.598975684223376, 21.02118219738726),
Offset(3.169562607312212, 18.258042555457294),
Offset(3.8457725409130035, 16.209986341924132),
Offset(4.491857018848872, 14.709706425920167),
Offset(5.042760982134354, 13.631765527094924),
Offset(5.471212748718976, 12.884189626374933),
Offset(5.770140143051716, 12.400456609777674),
Offset(5.943251827328922, 12.132774431470317),
Offset(5.999943741061273, 12.046959719775653),
Offset(5.9999999999999964, 12.046875000000004),
],
),
_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,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(38.005915505011714, 22.044873132716152),
Offset(38.49527667048537, 22.460937675484836),
Offset(39.29605291379161, 23.509087727219047),
Offset(40.090934628235715, 25.55307837508503),
Offset(40.245484311889584, 29.064745081245363),
Offset(38.450753318138695, 34.23676198345152),
Offset(33.0728907045072, 39.641976680762035),
Offset(25.27493194621109, 42.06583927008458),
Offset(18.326968788774145, 41.199323151695744),
Offset(13.530028647165079, 38.7776757262709),
Offset(10.497349834922744, 36.06973233007009),
Offset(8.641652255677663, 33.59797658699316),
Offset(7.521978336487795, 31.514971860015343),
Offset(6.854874126980906, 29.834780098541096),
Offset(6.463082099174432, 28.52288741178727),
Offset(6.237308044978324, 27.533663044350465),
Offset(6.1105452413260615, 26.82265981608807),
Offset(6.04246239664468, 26.35092390861118),
Offset(6.009733624107838, 26.085741049230215),
Offset(6.000009413493068, 26.000084719621103),
Offset(6.0, 26.000000000000004),
],
),
_PathCubicTo(
<Offset>[
Offset(38.005915505011714, 22.044873132716152),
Offset(38.49527667048537, 22.460937675484836),
Offset(39.29605291379161, 23.509087727219047),
Offset(40.090934628235715, 25.55307837508503),
Offset(40.245484311889584, 29.064745081245363),
Offset(38.450753318138695, 34.23676198345152),
Offset(33.0728907045072, 39.641976680762035),
Offset(25.27493194621109, 42.06583927008458),
Offset(18.326968788774145, 41.199323151695744),
Offset(13.530028647165079, 38.7776757262709),
Offset(10.497349834922744, 36.06973233007009),
Offset(8.641652255677663, 33.59797658699316),
Offset(7.521978336487795, 31.514971860015343),
Offset(6.854874126980906, 29.834780098541096),
Offset(6.463082099174432, 28.52288741178727),
Offset(6.237308044978324, 27.533663044350465),
Offset(6.1105452413260615, 26.82265981608807),
Offset(6.04246239664468, 26.35092390861118),
Offset(6.009733624107838, 26.085741049230215),
Offset(6.000009413493068, 26.000084719621103),
Offset(6.0, 26.000000000000004),
],
<Offset>[
Offset(10.006902842119626, 21.955147406089473),
Offset(9.632135496378087, 21.541092072032644),
Offset(9.099209938092097, 20.510489270395304),
Offset(8.782988004431196, 18.54355650849138),
Offset(9.385621621161075, 15.282927792774965),
Offset(12.215268791957268, 10.781237663014041),
Offset(18.587927795299567, 6.746065530872357),
Offset(26.721835989812625, 6.094927845871137),
Offset(33.31012577595844, 8.46547206910251),
Offset(37.45848623536183, 11.881041783528742),
Offset(39.822770672529785, 15.188647762997359),
Offset(41.090626806239804, 18.007465029735965),
Offset(41.72574666538112, 20.285446843195025),
Offset(42.007757458722764, 22.071095827208),
Offset(42.102017139978244, 23.436994259413154),
Offset(42.10513769756149, 24.451651361492107),
Offset(42.07273484614025, 25.17313902889128),
Offset(42.03560534906618, 25.64831419721343),
Offset(42.00932498728679, 25.914213546678557),
Offset(42.000009413094325, 25.99991528033459),
Offset(42.0, 25.999999999999996),
],
<Offset>[
Offset(10.006902842119626, 21.955147406089473),
Offset(9.632135496378087, 21.541092072032644),
Offset(9.099209938092097, 20.510489270395304),
Offset(8.782988004431196, 18.54355650849138),
Offset(9.385621621161075, 15.282927792774965),
Offset(12.215268791957268, 10.781237663014041),
Offset(18.587927795299567, 6.746065530872357),
Offset(26.721835989812625, 6.094927845871137),
Offset(33.31012577595844, 8.46547206910251),
Offset(37.45848623536183, 11.881041783528742),
Offset(39.822770672529785, 15.188647762997359),
Offset(41.090626806239804, 18.007465029735965),
Offset(41.72574666538112, 20.285446843195025),
Offset(42.007757458722764, 22.071095827208),
Offset(42.102017139978244, 23.436994259413154),
Offset(42.10513769756149, 24.451651361492107),
Offset(42.07273484614025, 25.17313902889128),
Offset(42.03560534906618, 25.64831419721343),
Offset(42.00932498728679, 25.914213546678557),
Offset(42.000009413094325, 25.99991528033459),
Offset(42.0, 25.999999999999996),
],
),
_PathCubicTo(
<Offset>[
Offset(10.006902842119626, 21.955147406089473),
Offset(9.632135496378087, 21.541092072032644),
Offset(9.099209938092097, 20.510489270395304),
Offset(8.782988004431196, 18.54355650849138),
Offset(9.385621621161075, 15.282927792774965),
Offset(12.215268791957268, 10.781237663014041),
Offset(18.587927795299567, 6.746065530872357),
Offset(26.721835989812625, 6.094927845871137),
Offset(33.31012577595844, 8.46547206910251),
Offset(37.45848623536183, 11.881041783528742),
Offset(39.822770672529785, 15.188647762997359),
Offset(41.090626806239804, 18.007465029735965),
Offset(41.72574666538112, 20.285446843195025),
Offset(42.007757458722764, 22.071095827208),
Offset(42.102017139978244, 23.436994259413154),
Offset(42.10513769756149, 24.451651361492107),
Offset(42.07273484614025, 25.17313902889128),
Offset(42.03560534906618, 25.64831419721343),
Offset(42.00932498728679, 25.914213546678557),
Offset(42.000009413094325, 25.99991528033459),
Offset(42.0, 25.999999999999996),
],
<Offset>[
Offset(9.991126102962665, 26.878296385119686),
Offset(9.478546725862362, 26.36043822046848),
Offset(8.639473946578361, 25.14017735498227),
Offset(7.81032131475563, 22.887960789223563),
Offset(7.650884598609569, 19.167302777578165),
Offset(9.48709191219624, 13.832759399890797),
Offset(14.921172139995065, 8.360637610125773),
Offset(22.72506805378891, 5.934160729915408),
Offset(29.673031211225855, 6.800676848304256),
Offset(34.46997135283492, 9.222324273729102),
Offset(37.502650165077256, 11.930267669929911),
Offset(39.35834774432234, 14.402023413006837),
Offset(40.47802166351221, 16.485028139984657),
Offset(41.1451258730191, 18.165219901458904),
Offset(41.53691790082557, 19.47711258821273),
Offset(41.76269195502168, 20.466336955649535),
Offset(41.889454758673935, 21.17734018391193),
Offset(41.95753760335532, 21.64907609138882),
Offset(41.99026637589216, 21.914258950769785),
Offset(41.99999058650693, 21.999915280378897),
Offset(42.0, 21.999999999999996),
],
<Offset>[
Offset(9.991126102962665, 26.878296385119686),
Offset(9.478546725862362, 26.36043822046848),
Offset(8.639473946578361, 25.14017735498227),
Offset(7.81032131475563, 22.887960789223563),
Offset(7.650884598609569, 19.167302777578165),
Offset(9.48709191219624, 13.832759399890797),
Offset(14.921172139995065, 8.360637610125773),
Offset(22.72506805378891, 5.934160729915408),
Offset(29.673031211225855, 6.800676848304256),
Offset(34.46997135283492, 9.222324273729102),
Offset(37.502650165077256, 11.930267669929911),
Offset(39.35834774432234, 14.402023413006837),
Offset(40.47802166351221, 16.485028139984657),
Offset(41.1451258730191, 18.165219901458904),
Offset(41.53691790082557, 19.47711258821273),
Offset(41.76269195502168, 20.466336955649535),
Offset(41.889454758673935, 21.17734018391193),
Offset(41.95753760335532, 21.64907609138882),
Offset(41.99026637589216, 21.914258950769785),
Offset(41.99999058650693, 21.999915280378897),
Offset(42.0, 21.999999999999996),
],
),
_PathCubicTo(
<Offset>[
Offset(9.991126102962665, 26.878296385119686),
Offset(9.478546725862362, 26.36043822046848),
Offset(8.639473946578361, 25.14017735498227),
Offset(7.81032131475563, 22.887960789223563),
Offset(7.650884598609569, 19.167302777578165),
Offset(9.48709191219624, 13.832759399890797),
Offset(14.921172139995065, 8.360637610125773),
Offset(22.72506805378891, 5.934160729915408),
Offset(29.673031211225855, 6.800676848304256),
Offset(34.46997135283492, 9.222324273729102),
Offset(37.502650165077256, 11.930267669929911),
Offset(39.35834774432234, 14.402023413006837),
Offset(40.47802166351221, 16.485028139984657),
Offset(41.1451258730191, 18.165219901458904),
Offset(41.53691790082557, 19.47711258821273),
Offset(41.76269195502168, 20.466336955649535),
Offset(41.889454758673935, 21.17734018391193),
Offset(41.95753760335532, 21.64907609138882),
Offset(41.99026637589216, 21.914258950769785),
Offset(41.99999058650693, 21.999915280378897),
Offset(42.0, 21.999999999999996),
],
<Offset>[
Offset(37.99013876585475, 26.968022111746365),
Offset(38.34168789996964, 27.280283823920673),
Offset(38.83631692227788, 28.138775811806013),
Offset(39.118267938560145, 29.897482655817214),
Offset(38.51074728933807, 32.949120066048565),
Offset(35.722576438377665, 37.28828372032828),
Offset(29.406135049202696, 41.25654876001545),
Offset(21.278164010187375, 41.90507215412886),
Offset(14.689874224041562, 39.53452793089749),
Offset(10.541513764638172, 36.118958216471256),
Offset(8.177229327470219, 32.81135223700264),
Offset(6.909373193760196, 29.992534970264035),
Offset(6.274253334618873, 27.714553156804975),
Offset(5.992242541277232, 25.928904172792),
Offset(5.897982860021752, 24.563005740586846),
Offset(5.894862302438508, 23.548348638507893),
Offset(5.927265153859754, 22.82686097110872),
Offset(5.964394650933819, 22.35168580278657),
Offset(5.990675012713211, 22.085786453321443),
Offset(5.999990586905675, 22.00008471966541),
Offset(6.0, 22.000000000000004),
],
<Offset>[
Offset(37.99013876585475, 26.968022111746365),
Offset(38.34168789996964, 27.280283823920673),
Offset(38.83631692227788, 28.138775811806013),
Offset(39.118267938560145, 29.897482655817214),
Offset(38.51074728933807, 32.949120066048565),
Offset(35.722576438377665, 37.28828372032828),
Offset(29.406135049202696, 41.25654876001545),
Offset(21.278164010187375, 41.90507215412886),
Offset(14.689874224041562, 39.53452793089749),
Offset(10.541513764638172, 36.118958216471256),
Offset(8.177229327470219, 32.81135223700264),
Offset(6.909373193760196, 29.992534970264035),
Offset(6.274253334618873, 27.714553156804975),
Offset(5.992242541277232, 25.928904172792),
Offset(5.897982860021752, 24.563005740586846),
Offset(5.894862302438508, 23.548348638507893),
Offset(5.927265153859754, 22.82686097110872),
Offset(5.964394650933819, 22.35168580278657),
Offset(5.990675012713211, 22.085786453321443),
Offset(5.999990586905675, 22.00008471966541),
Offset(6.0, 22.000000000000004),
],
),
_PathCubicTo(
<Offset>[
Offset(37.99013876585475, 26.968022111746365),
Offset(38.34168789996964, 27.280283823920673),
Offset(38.83631692227788, 28.138775811806013),
Offset(39.118267938560145, 29.897482655817214),
Offset(38.51074728933807, 32.949120066048565),
Offset(35.722576438377665, 37.28828372032828),
Offset(29.406135049202696, 41.25654876001545),
Offset(21.278164010187375, 41.90507215412886),
Offset(14.689874224041562, 39.53452793089749),
Offset(10.541513764638172, 36.118958216471256),
Offset(8.177229327470219, 32.81135223700264),
Offset(6.909373193760196, 29.992534970264035),
Offset(6.274253334618873, 27.714553156804975),
Offset(5.992242541277232, 25.928904172792),
Offset(5.897982860021752, 24.563005740586846),
Offset(5.894862302438508, 23.548348638507893),
Offset(5.927265153859754, 22.82686097110872),
Offset(5.964394650933819, 22.35168580278657),
Offset(5.990675012713211, 22.085786453321443),
Offset(5.999990586905675, 22.00008471966541),
Offset(6.0, 22.000000000000004),
],
<Offset>[
Offset(38.005915505011714, 22.044873132716152),
Offset(38.49527667048537, 22.460937675484836),
Offset(39.29605291379161, 23.509087727219047),
Offset(40.090934628235715, 25.55307837508503),
Offset(40.245484311889584, 29.064745081245363),
Offset(38.450753318138695, 34.23676198345152),
Offset(33.0728907045072, 39.641976680762035),
Offset(25.27493194621109, 42.06583927008458),
Offset(18.326968788774145, 41.199323151695744),
Offset(13.530028647165079, 38.7776757262709),
Offset(10.497349834922744, 36.06973233007009),
Offset(8.641652255677663, 33.59797658699316),
Offset(7.521978336487795, 31.514971860015343),
Offset(6.854874126980906, 29.834780098541096),
Offset(6.463082099174432, 28.52288741178727),
Offset(6.237308044978324, 27.533663044350465),
Offset(6.1105452413260615, 26.82265981608807),
Offset(6.04246239664468, 26.35092390861118),
Offset(6.009733624107838, 26.085741049230215),
Offset(6.000009413493068, 26.000084719621103),
Offset(6.0, 26.000000000000004),
],
<Offset>[
Offset(38.005915505011714, 22.044873132716152),
Offset(38.49527667048537, 22.460937675484836),
Offset(39.29605291379161, 23.509087727219047),
Offset(40.090934628235715, 25.55307837508503),
Offset(40.245484311889584, 29.064745081245363),
Offset(38.450753318138695, 34.23676198345152),
Offset(33.0728907045072, 39.641976680762035),
Offset(25.27493194621109, 42.06583927008458),
Offset(18.326968788774145, 41.199323151695744),
Offset(13.530028647165079, 38.7776757262709),
Offset(10.497349834922744, 36.06973233007009),
Offset(8.641652255677663, 33.59797658699316),
Offset(7.521978336487795, 31.514971860015343),
Offset(6.854874126980906, 29.834780098541096),
Offset(6.463082099174432, 28.52288741178727),
Offset(6.237308044978324, 27.533663044350465),
Offset(6.1105452413260615, 26.82265981608807),
Offset(6.04246239664468, 26.35092390861118),
Offset(6.009733624107838, 26.085741049230215),
Offset(6.000009413493068, 26.000084719621103),
Offset(6.0, 26.000000000000004),
],
),
_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,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(20.176179763180997, 21.987735903833876),
Offset(20.55193618727129, 21.88909752977205),
Offset(21.227655124257208, 21.71486474263169),
Offset(22.13567600845661, 21.53308372554798),
Offset(23.226514419921436, 21.464181986077985),
Offset(24.4102783754196, 21.684041595886637),
Offset(25.440842849032627, 22.309300738195095),
Offset(26.03642252837242, 23.134721894037483),
Offset(26.21244881576038, 23.97183703919535),
Offset(26.123327546035636, 24.622256415770117),
Offset(25.931014482213666, 25.0802342265462),
Offset(25.71921080582189, 25.392852152910002),
Offset(25.5230666408985, 25.604989383797584),
Offset(25.3554718074648, 25.748833638139686),
Offset(25.21948374988762, 25.846234627148135),
Offset(25.114174554400172, 25.911632280813432),
Offset(25.037072414338468, 25.95453414453137),
Offset(24.98527999526863, 25.9811477091939),
Offset(24.955944954391757, 25.995467904751596),
Offset(24.946435804885212, 25.999995545483056),
Offset(24.946426391602, 26.0),
],
),
_PathCubicTo(
<Offset>[
Offset(20.176179763180997, 21.987735903833876),
Offset(20.55193618727129, 21.88909752977205),
Offset(21.227655124257208, 21.71486474263169),
Offset(22.13567600845661, 21.53308372554798),
Offset(23.226514419921436, 21.464181986077985),
Offset(24.4102783754196, 21.684041595886637),
Offset(25.440842849032627, 22.309300738195095),
Offset(26.03642252837242, 23.134721894037483),
Offset(26.21244881576038, 23.97183703919535),
Offset(26.123327546035636, 24.622256415770117),
Offset(25.931014482213666, 25.0802342265462),
Offset(25.71921080582189, 25.392852152910002),
Offset(25.5230666408985, 25.604989383797584),
Offset(25.3554718074648, 25.748833638139686),
Offset(25.21948374988762, 25.846234627148135),
Offset(25.114174554400172, 25.911632280813432),
Offset(25.037072414338468, 25.95453414453137),
Offset(24.98527999526863, 25.9811477091939),
Offset(24.955944954391757, 25.995467904751596),
Offset(24.946435804885212, 25.999995545483056),
Offset(24.946426391602, 26.0),
],
<Offset>[
Offset(10.006902842149625, 21.95514740608957),
Offset(9.632135496348102, 21.541092072031688),
Offset(9.099209938111999, 20.510489270397283),
Offset(8.78298800447023, 18.543556508500117),
Offset(9.385621621133684, 15.282927792762731),
Offset(12.215268791942359, 10.781237663000711),
Offset(18.58792779526773, 6.746065530800053),
Offset(26.721835989812707, 6.094927845869137),
Offset(33.31012577595927, 8.465472069100691),
Offset(37.458486235363154, 11.881041783527248),
Offset(39.82277067253141, 15.1886477629962),
Offset(41.09062680624161, 18.007465029735098),
Offset(41.72574666538303, 20.2854468431944),
Offset(42.007757458724726, 22.07109582720757),
Offset(42.10201713998023, 23.43699425941287),
Offset(42.105137697563485, 24.451651361491937),
Offset(42.07273484614225, 25.173139028891192),
Offset(42.03560534906818, 25.64831419721339),
Offset(42.00932498728879, 25.91421354667855),
Offset(42.00000941309632, 25.99991528033459),
Offset(42.000000000002004, 25.999999999999996),
],
<Offset>[
Offset(10.006902842149625, 21.95514740608957),
Offset(9.632135496348102, 21.541092072031688),
Offset(9.099209938111999, 20.510489270397283),
Offset(8.78298800447023, 18.543556508500117),
Offset(9.385621621133684, 15.282927792762731),
Offset(12.215268791942359, 10.781237663000711),
Offset(18.58792779526773, 6.746065530800053),
Offset(26.721835989812707, 6.094927845869137),
Offset(33.31012577595927, 8.465472069100691),
Offset(37.458486235363154, 11.881041783527248),
Offset(39.82277067253141, 15.1886477629962),
Offset(41.09062680624161, 18.007465029735098),
Offset(41.72574666538303, 20.2854468431944),
Offset(42.007757458724726, 22.07109582720757),
Offset(42.10201713998023, 23.43699425941287),
Offset(42.105137697563485, 24.451651361491937),
Offset(42.07273484614225, 25.173139028891192),
Offset(42.03560534906818, 25.64831419721339),
Offset(42.00932498728879, 25.91421354667855),
Offset(42.00000941309632, 25.99991528033459),
Offset(42.000000000002004, 25.999999999999996),
],
),
_PathCubicTo(
<Offset>[
Offset(10.006902842149625, 21.95514740608957),
Offset(9.632135496348102, 21.541092072031688),
Offset(9.099209938111999, 20.510489270397283),
Offset(8.78298800447023, 18.543556508500117),
Offset(9.385621621133684, 15.282927792762731),
Offset(12.215268791942359, 10.781237663000711),
Offset(18.58792779526773, 6.746065530800053),
Offset(26.721835989812707, 6.094927845869137),
Offset(33.31012577595927, 8.465472069100691),
Offset(37.458486235363154, 11.881041783527248),
Offset(39.82277067253141, 15.1886477629962),
Offset(41.09062680624161, 18.007465029735098),
Offset(41.72574666538303, 20.2854468431944),
Offset(42.007757458724726, 22.07109582720757),
Offset(42.10201713998023, 23.43699425941287),
Offset(42.105137697563485, 24.451651361491937),
Offset(42.07273484614225, 25.173139028891192),
Offset(42.03560534906818, 25.64831419721339),
Offset(42.00932498728879, 25.91421354667855),
Offset(42.00000941309632, 25.99991528033459),
Offset(42.000000000002004, 25.999999999999996),
],
<Offset>[
Offset(9.950103066904006, 39.679580365751406),
Offset(9.115564488520917, 37.75018397768418),
Offset(7.7454464103988485, 34.143319828138715),
Offset(6.441070390954248, 29.003703867586243),
Offset(6.213866824197122, 22.385033086525855),
Offset(8.625212439492824, 14.796789248890494),
Offset(14.838843583186215, 8.396889109087798),
Offset(22.72506805378899, 5.934160729913408),
Offset(29.67303121122669, 6.800676848302437),
Offset(34.469971352836254, 9.222324273727608),
Offset(37.50265016507888, 11.930267669928751),
Offset(39.35834774432414, 14.40202341300597),
Offset(40.478021663514106, 16.48502813998403),
Offset(41.145125873021044, 18.165219901458475),
Offset(41.53691790082755, 19.47711258821245),
Offset(41.76269195502367, 20.46633695564936),
Offset(41.88945475867594, 21.177340183911838),
Offset(41.95753760335732, 21.649076091388782),
Offset(41.990266375894166, 21.914258950769778),
Offset(41.99999058650893, 21.999915280378897),
Offset(42.000000000002004, 21.999999999999996),
],
<Offset>[
Offset(9.950103066904006, 39.679580365751406),
Offset(9.115564488520917, 37.75018397768418),
Offset(7.7454464103988485, 34.143319828138715),
Offset(6.441070390954248, 29.003703867586243),
Offset(6.213866824197122, 22.385033086525855),
Offset(8.625212439492824, 14.796789248890494),
Offset(14.838843583186215, 8.396889109087798),
Offset(22.72506805378899, 5.934160729913408),
Offset(29.67303121122669, 6.800676848302437),
Offset(34.469971352836254, 9.222324273727608),
Offset(37.50265016507888, 11.930267669928751),
Offset(39.35834774432414, 14.40202341300597),
Offset(40.478021663514106, 16.48502813998403),
Offset(41.145125873021044, 18.165219901458475),
Offset(41.53691790082755, 19.47711258821245),
Offset(41.76269195502367, 20.46633695564936),
Offset(41.88945475867594, 21.177340183911838),
Offset(41.95753760335732, 21.649076091388782),
Offset(41.990266375894166, 21.914258950769778),
Offset(41.99999058650893, 21.999915280378897),
Offset(42.000000000002004, 21.999999999999996),
],
),
_PathCubicTo(
<Offset>[
Offset(9.950103066904006, 39.679580365751406),
Offset(9.115564488520917, 37.75018397768418),
Offset(7.7454464103988485, 34.143319828138715),
Offset(6.441070390954248, 29.003703867586243),
Offset(6.213866824197122, 22.385033086525855),
Offset(8.625212439492824, 14.796789248890494),
Offset(14.838843583186215, 8.396889109087798),
Offset(22.72506805378899, 5.934160729913408),
Offset(29.67303121122669, 6.800676848302437),
Offset(34.469971352836254, 9.222324273727608),
Offset(37.50265016507888, 11.930267669928751),
Offset(39.35834774432414, 14.40202341300597),
Offset(40.478021663514106, 16.48502813998403),
Offset(41.145125873021044, 18.165219901458475),
Offset(41.53691790082755, 19.47711258821245),
Offset(41.76269195502367, 20.46633695564936),
Offset(41.88945475867594, 21.177340183911838),
Offset(41.95753760335732, 21.649076091388782),
Offset(41.990266375894166, 21.914258950769778),
Offset(41.99999058650893, 21.999915280378897),
Offset(42.000000000002004, 21.999999999999996),
],
<Offset>[
Offset(20.119379987935375, 39.71216886349571),
Offset(20.035365179444106, 38.098189435424544),
Offset(19.873891596544055, 35.347695300373125),
Offset(19.793758394940628, 31.993231084634104),
Offset(20.054759622984875, 28.566287279841106),
Offset(20.820222022970064, 25.699593181776418),
Offset(21.69175863695111, 23.96012431648284),
Offset(22.0396545923487, 22.973954778081758),
Offset(22.575354251027797, 22.307041818397096),
Offset(23.13481266350873, 21.963538905970477),
Offset(23.61089397476114, 21.82185413347875),
Offset(23.986931743904425, 21.787410536180875),
Offset(24.275341639029573, 21.804570680587215),
Offset(24.49284022176112, 21.842957712390593),
Offset(24.65438451073494, 21.88635295594771),
Offset(24.771728811860356, 21.926317874970856),
Offset(24.853792326872156, 21.958735299552014),
Offset(24.90721224955777, 21.981909603369285),
Offset(24.93688634299713, 21.995513308842824),
Offset(24.946416978297822, 21.99999554552736),
Offset(24.946426391602, 22.0),
],
<Offset>[
Offset(20.119379987935375, 39.71216886349571),
Offset(20.035365179444106, 38.098189435424544),
Offset(19.873891596544055, 35.347695300373125),
Offset(19.793758394940628, 31.993231084634104),
Offset(20.054759622984875, 28.566287279841106),
Offset(20.820222022970064, 25.699593181776418),
Offset(21.69175863695111, 23.96012431648284),
Offset(22.0396545923487, 22.973954778081758),
Offset(22.575354251027797, 22.307041818397096),
Offset(23.13481266350873, 21.963538905970477),
Offset(23.61089397476114, 21.82185413347875),
Offset(23.986931743904425, 21.787410536180875),
Offset(24.275341639029573, 21.804570680587215),
Offset(24.49284022176112, 21.842957712390593),
Offset(24.65438451073494, 21.88635295594771),
Offset(24.771728811860356, 21.926317874970856),
Offset(24.853792326872156, 21.958735299552014),
Offset(24.90721224955777, 21.981909603369285),
Offset(24.93688634299713, 21.995513308842824),
Offset(24.946416978297822, 21.99999554552736),
Offset(24.946426391602, 22.0),
],
),
_PathCubicTo(
<Offset>[
Offset(20.119379987935375, 39.71216886349571),
Offset(20.035365179444106, 38.098189435424544),
Offset(19.873891596544055, 35.347695300373125),
Offset(19.793758394940628, 31.993231084634104),
Offset(20.054759622984875, 28.566287279841106),
Offset(20.820222022970064, 25.699593181776418),
Offset(21.69175863695111, 23.96012431648284),
Offset(22.0396545923487, 22.973954778081758),
Offset(22.575354251027797, 22.307041818397096),
Offset(23.13481266350873, 21.963538905970477),
Offset(23.61089397476114, 21.82185413347875),
Offset(23.986931743904425, 21.787410536180875),
Offset(24.275341639029573, 21.804570680587215),
Offset(24.49284022176112, 21.842957712390593),
Offset(24.65438451073494, 21.88635295594771),
Offset(24.771728811860356, 21.926317874970856),
Offset(24.853792326872156, 21.958735299552014),
Offset(24.90721224955777, 21.981909603369285),
Offset(24.93688634299713, 21.995513308842824),
Offset(24.946416978297822, 21.99999554552736),
Offset(24.946426391602, 22.0),
],
<Offset>[
Offset(20.176179763180997, 21.987735903833876),
Offset(20.55193618727129, 21.88909752977205),
Offset(21.227655124257208, 21.71486474263169),
Offset(22.13567600845661, 21.53308372554798),
Offset(23.226514419921436, 21.464181986077985),
Offset(24.410278375419598, 21.684041595886633),
Offset(25.440842849032627, 22.309300738195095),
Offset(26.03642252837242, 23.134721894037487),
Offset(26.21244881576038, 23.971837039195353),
Offset(26.123327546035632, 24.622256415770117),
Offset(25.931014482213666, 25.0802342265462),
Offset(25.71921080582189, 25.392852152910002),
Offset(25.5230666408985, 25.604989383797584),
Offset(25.3554718074648, 25.748833638139686),
Offset(25.21948374988762, 25.846234627148135),
Offset(25.114174554400172, 25.911632280813432),
Offset(25.037072414338468, 25.95453414453137),
Offset(24.98527999526863, 25.9811477091939),
Offset(24.955944954391757, 25.995467904751596),
Offset(24.946435804885212, 25.999995545483056),
Offset(24.946426391602, 26.0),
],
<Offset>[
Offset(20.176179763180997, 21.987735903833876),
Offset(20.55193618727129, 21.88909752977205),
Offset(21.227655124257208, 21.71486474263169),
Offset(22.13567600845661, 21.53308372554798),
Offset(23.226514419921436, 21.464181986077985),
Offset(24.410278375419598, 21.684041595886633),
Offset(25.440842849032627, 22.309300738195095),
Offset(26.03642252837242, 23.134721894037487),
Offset(26.21244881576038, 23.971837039195353),
Offset(26.123327546035632, 24.622256415770117),
Offset(25.931014482213666, 25.0802342265462),
Offset(25.71921080582189, 25.392852152910002),
Offset(25.5230666408985, 25.604989383797584),
Offset(25.3554718074648, 25.748833638139686),
Offset(25.21948374988762, 25.846234627148135),
Offset(25.114174554400172, 25.911632280813432),
Offset(25.037072414338468, 25.95453414453137),
Offset(24.98527999526863, 25.9811477091939),
Offset(24.955944954391757, 25.995467904751596),
Offset(24.946435804885212, 25.999995545483056),
Offset(24.946426391602, 26.0),
],
),
_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,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(27.83663858395034, 22.012284634971753),
Offset(27.57547597959216, 22.112932217745428),
Offset(27.1676077276265, 22.304712254982665),
Offset(26.73824662421029, 22.56355115802843),
Offset(26.404591513129226, 22.883490887942344),
Offset(26.255743734676358, 23.33395805057893),
Offset(26.21997565073384, 24.078741473347776),
Offset(25.9603454076513, 25.02604522191824),
Offset(25.424645748972203, 25.692958181602904),
Offset(24.865187336491275, 26.036461094029523),
Offset(24.38910602523886, 26.17814586652125),
Offset(24.013068256095575, 26.212589463819125),
Offset(23.724658360970427, 26.195429319412785),
Offset(23.50715977823888, 26.157042287609407),
Offset(23.34561548926506, 26.11364704405229),
Offset(23.228271188139644, 26.073682125029144),
Offset(23.14620767312784, 26.041264700447986),
Offset(23.092787750442234, 26.018090396630715),
Offset(23.063113657002866, 26.004486691157176),
Offset(23.053583021702178, 26.00000445447264),
Offset(23.053573608398, 26.0),
],
),
_PathCubicTo(
<Offset>[
Offset(27.83663858395034, 22.012284634971753),
Offset(27.57547597959216, 22.112932217745428),
Offset(27.1676077276265, 22.304712254982665),
Offset(26.73824662421029, 22.56355115802843),
Offset(26.404591513129226, 22.883490887942344),
Offset(26.255743734676358, 23.33395805057893),
Offset(26.21997565073384, 24.078741473347776),
Offset(25.9603454076513, 25.02604522191824),
Offset(25.424645748972203, 25.692958181602904),
Offset(24.865187336491275, 26.036461094029523),
Offset(24.38910602523886, 26.17814586652125),
Offset(24.013068256095575, 26.212589463819125),
Offset(23.724658360970427, 26.195429319412785),
Offset(23.50715977823888, 26.157042287609407),
Offset(23.34561548926506, 26.11364704405229),
Offset(23.228271188139644, 26.073682125029144),
Offset(23.14620767312784, 26.041264700447986),
Offset(23.092787750442234, 26.018090396630715),
Offset(23.063113657002866, 26.004486691157176),
Offset(23.053583021702178, 26.00000445447264),
Offset(23.053573608398, 26.0),
],
<Offset>[
Offset(38.00591550498171, 22.044873132716056),
Offset(38.49527667051535, 22.460937675485788),
Offset(39.29605291377171, 23.50908772721707),
Offset(40.09093462819668, 25.55307837507629),
Offset(40.245484311916975, 29.0647450812576),
Offset(38.4507533181536, 34.23676198346485),
Offset(33.07289070449873, 39.64197668074282),
Offset(25.27493194621101, 42.065839270086585),
Offset(18.32696878877331, 41.19932315169756),
Offset(13.530028647163753, 38.77767572627239),
Offset(10.497349834921115, 36.06973233007125),
Offset(8.641652255675858, 33.59797658699403),
Offset(7.521978336485894, 31.51497186001597),
Offset(6.854874126978952, 29.834780098541525),
Offset(6.463082099172453, 28.52288741178755),
Offset(6.237308044976331, 27.53366304435064),
Offset(6.110545241324058, 26.822659816088162),
Offset(6.042462396642684, 26.350923908611218),
Offset(6.009733624105834, 26.085741049230222),
Offset(6.0000094134910675, 26.000084719621103),
Offset(5.999999999998, 26.000000000000004),
],
<Offset>[
Offset(38.00591550498171, 22.044873132716056),
Offset(38.49527667051535, 22.460937675485788),
Offset(39.29605291377171, 23.50908772721707),
Offset(40.09093462819668, 25.55307837507629),
Offset(40.245484311916975, 29.0647450812576),
Offset(38.4507533181536, 34.23676198346485),
Offset(33.07289070449873, 39.64197668074282),
Offset(25.27493194621101, 42.065839270086585),
Offset(18.32696878877331, 41.19932315169756),
Offset(13.530028647163753, 38.77767572627239),
Offset(10.497349834921115, 36.06973233007125),
Offset(8.641652255675858, 33.59797658699403),
Offset(7.521978336485894, 31.51497186001597),
Offset(6.854874126978952, 29.834780098541525),
Offset(6.463082099172453, 28.52288741178755),
Offset(6.237308044976331, 27.53366304435064),
Offset(6.110545241324058, 26.822659816088162),
Offset(6.042462396642684, 26.350923908611218),
Offset(6.009733624105834, 26.085741049230222),
Offset(6.0000094134910675, 26.000084719621103),
Offset(5.999999999998, 26.000000000000004),
],
),
_PathCubicTo(
<Offset>[
Offset(38.00591550498171, 22.044873132716056),
Offset(38.49527667051535, 22.460937675485788),
Offset(39.29605291377171, 23.50908772721707),
Offset(40.09093462819668, 25.55307837507629),
Offset(40.245484311916975, 29.0647450812576),
Offset(38.4507533181536, 34.23676198346485),
Offset(33.07289070449873, 39.64197668074282),
Offset(25.27493194621101, 42.065839270086585),
Offset(18.32696878877331, 41.19932315169756),
Offset(13.530028647163753, 38.77767572627239),
Offset(10.497349834921115, 36.06973233007125),
Offset(8.641652255675858, 33.59797658699403),
Offset(7.521978336485894, 31.51497186001597),
Offset(6.854874126978952, 29.834780098541525),
Offset(6.463082099172453, 28.52288741178755),
Offset(6.237308044976331, 27.53366304435064),
Offset(6.110545241324058, 26.822659816088162),
Offset(6.042462396642684, 26.350923908611218),
Offset(6.009733624105834, 26.085741049230222),
Offset(6.0000094134910675, 26.000084719621103),
Offset(5.999999999998, 26.000000000000004),
],
<Offset>[
Offset(37.94911572973609, 39.76930609237789),
Offset(37.978705662688164, 38.67002958113828),
Offset(37.94228938605856, 37.14191828495851),
Offset(37.74901701468069, 36.01322573416242),
Offset(37.073729514980414, 36.166850375020715),
Offset(34.860696965704065, 38.25231356935464),
Offset(29.32380649241722, 41.29280025903057),
Offset(21.278164010187293, 41.90507215413086),
Offset(14.689874224040729, 39.53452793089931),
Offset(10.541513764636846, 36.11895821647275),
Offset(8.17722932746859, 32.8113522370038),
Offset(6.909373193758391, 29.992534970264902),
Offset(6.274253334616972, 27.7145531568056),
Offset(5.992242541275278, 25.92890417279243),
Offset(5.8979828600197735, 24.56300574058713),
Offset(5.894862302436515, 23.548348638508063),
Offset(5.92726515385775, 22.826860971108808),
Offset(5.964394650931823, 22.35168580278661),
Offset(5.990675012711208, 22.08578645332145),
Offset(5.9999905869036745, 22.00008471966541),
Offset(5.999999999998, 22.000000000000004),
],
<Offset>[
Offset(37.94911572973609, 39.76930609237789),
Offset(37.978705662688164, 38.67002958113828),
Offset(37.94228938605856, 37.14191828495851),
Offset(37.74901701468069, 36.01322573416242),
Offset(37.073729514980414, 36.166850375020715),
Offset(34.860696965704065, 38.25231356935464),
Offset(29.32380649241722, 41.29280025903057),
Offset(21.278164010187293, 41.90507215413086),
Offset(14.689874224040729, 39.53452793089931),
Offset(10.541513764636846, 36.11895821647275),
Offset(8.17722932746859, 32.8113522370038),
Offset(6.909373193758391, 29.992534970264902),
Offset(6.274253334616972, 27.7145531568056),
Offset(5.992242541275278, 25.92890417279243),
Offset(5.8979828600197735, 24.56300574058713),
Offset(5.894862302436515, 23.548348638508063),
Offset(5.92726515385775, 22.826860971108808),
Offset(5.964394650931823, 22.35168580278661),
Offset(5.990675012711208, 22.08578645332145),
Offset(5.9999905869036745, 22.00008471966541),
Offset(5.999999999998, 22.000000000000004),
],
),
_PathCubicTo(
<Offset>[
Offset(37.94911572973609, 39.76930609237789),
Offset(37.978705662688164, 38.67002958113828),
Offset(37.94228938605856, 37.14191828495851),
Offset(37.74901701468069, 36.01322573416242),
Offset(37.073729514980414, 36.166850375020715),
Offset(34.860696965704065, 38.25231356935464),
Offset(29.32380649241722, 41.29280025903057),
Offset(21.278164010187293, 41.90507215413086),
Offset(14.689874224040729, 39.53452793089931),
Offset(10.541513764636846, 36.11895821647275),
Offset(8.17722932746859, 32.8113522370038),
Offset(6.909373193758391, 29.992534970264902),
Offset(6.274253334616972, 27.7145531568056),
Offset(5.992242541275278, 25.92890417279243),
Offset(5.8979828600197735, 24.56300574058713),
Offset(5.894862302436515, 23.548348638508063),
Offset(5.92726515385775, 22.826860971108808),
Offset(5.964394650931823, 22.35168580278661),
Offset(5.990675012711208, 22.08578645332145),
Offset(5.9999905869036745, 22.00008471966541),
Offset(5.999999999998, 22.000000000000004),
],
<Offset>[
Offset(27.779838808704717, 39.73671759463359),
Offset(27.058904971764974, 38.322024123397924),
Offset(25.813844199913348, 35.937542812724104),
Offset(24.396329010694313, 33.02369851711455),
Offset(23.23283671619266, 29.985596181705468),
Offset(22.665687382226825, 27.349509636468714),
Offset(22.470891438652323, 25.72956505163552),
Offset(21.96357747162758, 24.86527810596251),
Offset(21.78755118423962, 24.028162960804647),
Offset(21.876672453964368, 23.377743584229883),
Offset(22.068985517786334, 22.9197657734538),
Offset(22.28078919417811, 22.607147847089998),
Offset(22.4769333591015, 22.395010616202416),
Offset(22.6445281925352, 22.251166361860314),
Offset(22.78051625011238, 22.153765372851865),
Offset(22.885825445599828, 22.088367719186568),
Offset(22.96292758566153, 22.04546585546863),
Offset(23.014720004731373, 22.0188522908061),
Offset(23.04405504560824, 22.004532095248404),
Offset(23.053564195114788, 22.000004454516944),
Offset(23.053573608398, 22.0),
],
<Offset>[
Offset(27.779838808704717, 39.73671759463359),
Offset(27.058904971764974, 38.322024123397924),
Offset(25.813844199913348, 35.937542812724104),
Offset(24.396329010694313, 33.02369851711455),
Offset(23.23283671619266, 29.985596181705468),
Offset(22.665687382226825, 27.349509636468714),
Offset(22.470891438652323, 25.72956505163552),
Offset(21.96357747162758, 24.86527810596251),
Offset(21.78755118423962, 24.028162960804647),
Offset(21.876672453964368, 23.377743584229883),
Offset(22.068985517786334, 22.9197657734538),
Offset(22.28078919417811, 22.607147847089998),
Offset(22.4769333591015, 22.395010616202416),
Offset(22.6445281925352, 22.251166361860314),
Offset(22.78051625011238, 22.153765372851865),
Offset(22.885825445599828, 22.088367719186568),
Offset(22.96292758566153, 22.04546585546863),
Offset(23.014720004731373, 22.0188522908061),
Offset(23.04405504560824, 22.004532095248404),
Offset(23.053564195114788, 22.000004454516944),
Offset(23.053573608398, 22.0),
],
),
_PathCubicTo(
<Offset>[
Offset(27.779838808704717, 39.73671759463359),
Offset(27.058904971764974, 38.322024123397924),
Offset(25.813844199913348, 35.937542812724104),
Offset(24.396329010694313, 33.02369851711455),
Offset(23.23283671619266, 29.985596181705468),
Offset(22.665687382226825, 27.349509636468714),
Offset(22.470891438652323, 25.72956505163552),
Offset(21.96357747162758, 24.86527810596251),
Offset(21.78755118423962, 24.028162960804647),
Offset(21.876672453964368, 23.377743584229883),
Offset(22.068985517786334, 22.9197657734538),
Offset(22.28078919417811, 22.607147847089998),
Offset(22.4769333591015, 22.395010616202416),
Offset(22.6445281925352, 22.251166361860314),
Offset(22.78051625011238, 22.153765372851865),
Offset(22.885825445599828, 22.088367719186568),
Offset(22.96292758566153, 22.04546585546863),
Offset(23.014720004731373, 22.0188522908061),
Offset(23.04405504560824, 22.004532095248404),
Offset(23.053564195114788, 22.000004454516944),
Offset(23.053573608398, 22.0),
],
<Offset>[
Offset(27.83663858395034, 22.012284634971753),
Offset(27.57547597959216, 22.112932217745428),
Offset(27.1676077276265, 22.304712254982665),
Offset(26.738246624210294, 22.56355115802843),
Offset(26.404591513129223, 22.883490887942344),
Offset(26.25574373467636, 23.333958050578932),
Offset(26.21997565073384, 24.078741473347776),
Offset(25.9603454076513, 25.02604522191824),
Offset(25.424645748972203, 25.692958181602904),
Offset(24.865187336491275, 26.036461094029523),
Offset(24.38910602523886, 26.17814586652125),
Offset(24.013068256095575, 26.212589463819125),
Offset(23.724658360970427, 26.195429319412785),
Offset(23.50715977823888, 26.157042287609407),
Offset(23.34561548926506, 26.11364704405229),
Offset(23.228271188139644, 26.073682125029144),
Offset(23.14620767312784, 26.041264700447986),
Offset(23.092787750442234, 26.018090396630715),
Offset(23.063113657002866, 26.004486691157176),
Offset(23.053583021702178, 26.00000445447264),
Offset(23.053573608398, 26.0),
],
<Offset>[
Offset(27.83663858395034, 22.012284634971753),
Offset(27.57547597959216, 22.112932217745428),
Offset(27.1676077276265, 22.304712254982665),
Offset(26.738246624210294, 22.56355115802843),
Offset(26.404591513129223, 22.883490887942344),
Offset(26.25574373467636, 23.333958050578932),
Offset(26.21997565073384, 24.078741473347776),
Offset(25.9603454076513, 25.02604522191824),
Offset(25.424645748972203, 25.692958181602904),
Offset(24.865187336491275, 26.036461094029523),
Offset(24.38910602523886, 26.17814586652125),
Offset(24.013068256095575, 26.212589463819125),
Offset(23.724658360970427, 26.195429319412785),
Offset(23.50715977823888, 26.157042287609407),
Offset(23.34561548926506, 26.11364704405229),
Offset(23.228271188139644, 26.073682125029144),
Offset(23.14620767312784, 26.041264700447986),
Offset(23.092787750442234, 26.018090396630715),
Offset(23.063113657002866, 26.004486691157176),
Offset(23.053583021702178, 26.00000445447264),
Offset(23.053573608398, 26.0),
],
),
_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,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(23.684125337085877, 6.32904503029285),
Offset(24.757855588582725, 6.522328815913423),
Offset(27.574407323116677, 7.305175651642309),
Offset(34.29718691345236, 10.565460438397327),
Offset(42.96465562696383, 18.312204872266342),
Offset(45.05615687407709, 26.45166424954756),
Offset(42.23233332042143, 35.60390079418309),
Offset(35.26685178627038, 42.467757059973906),
Offset(27.4197052006056, 45.36131120369138),
Offset(21.001315853482343, 45.424469500769995),
Offset(16.29765110355406, 44.215682562738714),
Offset(12.97234991047133, 42.61158062881598),
Offset(10.641290841160107, 41.016018618041265),
Offset(9.0114530912401, 39.59946991291384),
Offset(7.875830197056132, 38.422591589788325),
Offset(7.093422401327867, 37.49694905895691),
Offset(6.568745459991835, 36.81215692853645),
Offset(6.237631760921833, 36.34901917317271),
Offset(6.057380152594408, 36.08562753900215),
Offset(6.000056479961543, 36.00008471951035),
Offset(6.0000000000000036, 36.00000000000001),
],
),
_PathCubicTo(
<Offset>[
Offset(23.684125337085877, 6.32904503029285),
Offset(24.757855588582725, 6.522328815913423),
Offset(27.574407323116677, 7.305175651642309),
Offset(34.29718691345236, 10.565460438397327),
Offset(42.96465562696383, 18.312204872266342),
Offset(45.05615687407709, 26.45166424954756),
Offset(42.23233332042143, 35.60390079418309),
Offset(35.26685178627038, 42.467757059973906),
Offset(27.4197052006056, 45.36131120369138),
Offset(21.001315853482343, 45.424469500769995),
Offset(16.29765110355406, 44.215682562738714),
Offset(12.97234991047133, 42.61158062881598),
Offset(10.641290841160107, 41.016018618041265),
Offset(9.0114530912401, 39.59946991291384),
Offset(7.875830197056132, 38.422591589788325),
Offset(7.093422401327867, 37.49694905895691),
Offset(6.568745459991835, 36.81215692853645),
Offset(6.237631760921833, 36.34901917317271),
Offset(6.057380152594408, 36.08562753900215),
Offset(6.000056479961543, 36.00008471951035),
Offset(6.0000000000000036, 36.00000000000001),
],
<Offset>[
Offset(23.689243079011977, 6.329061430625194),
Offset(23.64011618905085, 6.48670734054237),
Offset(23.133765296901146, 6.8642122589514845),
Offset(19.98658162330333, 7.361465557774245),
Offset(15.467378257263233, 6.032096680033179),
Offset(19.194942220379907, 3.3307514773626146),
Offset(27.75047360634506, 2.715037120490525),
Offset(36.713755829871914, 6.4968456357604545),
Offset(42.40286218778989, 12.627460121098146),
Offset(44.92977344167909, 18.52783555802784),
Offset(45.6230719411611, 23.334597995665984),
Offset(45.42132446103347, 27.02106907155878),
Offset(44.84505917005344, 29.786493601220947),
Offset(44.16433642298196, 31.835785641580745),
Offset(43.51476523785995, 33.33669843741421),
Offset(42.96125205391104, 34.41493737609855),
Offset(42.530935064806016, 35.16263614133967),
Offset(42.23077471334334, 35.64640946177496),
Offset(42.056971515773355, 35.91410003645049),
Offset(42.0000564795628, 35.99991528022383),
Offset(42.0, 35.99999999999999),
],
<Offset>[
Offset(23.689243079011977, 6.329061430625194),
Offset(23.64011618905085, 6.48670734054237),
Offset(23.133765296901146, 6.8642122589514845),
Offset(19.98658162330333, 7.361465557774245),
Offset(15.467378257263233, 6.032096680033179),
Offset(19.194942220379907, 3.3307514773626146),
Offset(27.75047360634506, 2.715037120490525),
Offset(36.713755829871914, 6.4968456357604545),
Offset(42.40286218778989, 12.627460121098146),
Offset(44.92977344167909, 18.52783555802784),
Offset(45.6230719411611, 23.334597995665984),
Offset(45.42132446103347, 27.02106907155878),
Offset(44.84505917005344, 29.786493601220947),
Offset(44.16433642298196, 31.835785641580745),
Offset(43.51476523785995, 33.33669843741421),
Offset(42.96125205391104, 34.41493737609855),
Offset(42.530935064806016, 35.16263614133967),
Offset(42.23077471334334, 35.64640946177496),
Offset(42.056971515773355, 35.91410003645049),
Offset(42.0000564795628, 35.99991528022383),
Offset(42.0, 35.99999999999999),
],
),
_PathCubicTo(
<Offset>[
Offset(23.689243079011977, 6.329061430625194),
Offset(23.64011618905085, 6.48670734054237),
Offset(23.133765296901146, 6.8642122589514845),
Offset(19.98658162330333, 7.361465557774245),
Offset(15.467378257263233, 6.032096680033179),
Offset(19.194942220379907, 3.3307514773626146),
Offset(27.75047360634506, 2.715037120490525),
Offset(36.713755829871914, 6.4968456357604545),
Offset(42.40286218778989, 12.627460121098146),
Offset(44.92977344167909, 18.52783555802784),
Offset(45.6230719411611, 23.334597995665984),
Offset(45.42132446103347, 27.02106907155878),
Offset(44.84505917005344, 29.786493601220947),
Offset(44.16433642298196, 31.835785641580745),
Offset(43.51476523785995, 33.33669843741421),
Offset(42.96125205391104, 34.41493737609855),
Offset(42.530935064806016, 35.16263614133967),
Offset(42.23077471334334, 35.64640946177496),
Offset(42.056971515773355, 35.91410003645049),
Offset(42.0000564795628, 35.99991528022383),
Offset(42.0, 35.99999999999999),
],
<Offset>[
Offset(4.256210085244433, 23.724986123422013),
Offset(4.334340540250139, 22.918290544448126),
Offset(4.683893395049303, 20.897955670871653),
Offset(6.165631658910659, 16.538261784200643),
Offset(10.04725752347015, 10.401464969282092),
Offset(15.676813589860602, 6.207875011618711),
Offset(24.053924042171055, 4.3051387362291464),
Offset(32.7169878938482, 6.336078519804726),
Offset(38.76576762305731, 10.962664900299892),
Offset(41.94125855915219, 15.869118048228197),
Offset(43.30295143370857, 20.076217902598536),
Offset(43.689045399116004, 23.415627454829654),
Offset(43.59733416818452, 25.98607489801058),
Offset(43.30170483727829, 27.92990971583165),
Offset(42.94966599870727, 29.37681676621379),
Offset(42.618806311371216, 30.429622970255974),
Offset(42.347654977339715, 31.166837296360313),
Offset(42.15270696763247, 31.64717135595035),
Offset(42.03791290437873, 31.914145440541716),
Offset(42.00003765297541, 31.999915280268137),
Offset(42.0, 31.999999999999996),
],
<Offset>[
Offset(4.256210085244433, 23.724986123422013),
Offset(4.334340540250139, 22.918290544448126),
Offset(4.683893395049303, 20.897955670871653),
Offset(6.165631658910659, 16.538261784200643),
Offset(10.04725752347015, 10.401464969282092),
Offset(15.676813589860602, 6.207875011618711),
Offset(24.053924042171055, 4.3051387362291464),
Offset(32.7169878938482, 6.336078519804726),
Offset(38.76576762305731, 10.962664900299892),
Offset(41.94125855915219, 15.869118048228197),
Offset(43.30295143370857, 20.076217902598536),
Offset(43.689045399116004, 23.415627454829654),
Offset(43.59733416818452, 25.98607489801058),
Offset(43.30170483727829, 27.92990971583165),
Offset(42.94966599870727, 29.37681676621379),
Offset(42.618806311371216, 30.429622970255974),
Offset(42.347654977339715, 31.166837296360313),
Offset(42.15270696763247, 31.64717135595035),
Offset(42.03791290437873, 31.914145440541716),
Offset(42.00003765297541, 31.999915280268137),
Offset(42.0, 31.999999999999996),
],
),
_PathCubicTo(
<Offset>[
Offset(4.256210085244433, 23.724986123422013),
Offset(4.334340540250139, 22.918290544448126),
Offset(4.683893395049303, 20.897955670871653),
Offset(6.165631658910659, 16.538261784200643),
Offset(10.04725752347015, 10.401464969282092),
Offset(15.676813589860602, 6.207875011618711),
Offset(24.053924042171055, 4.3051387362291464),
Offset(32.7169878938482, 6.336078519804726),
Offset(38.76576762305731, 10.962664900299892),
Offset(41.94125855915219, 15.869118048228197),
Offset(43.30295143370857, 20.076217902598536),
Offset(43.689045399116004, 23.415627454829654),
Offset(43.59733416818452, 25.98607489801058),
Offset(43.30170483727829, 27.92990971583165),
Offset(42.94966599870727, 29.37681676621379),
Offset(42.618806311371216, 30.429622970255974),
Offset(42.347654977339715, 31.166837296360313),
Offset(42.15270696763247, 31.64717135595035),
Offset(42.03791290437873, 31.914145440541716),
Offset(42.00003765297541, 31.999915280268137),
Offset(42.0, 31.999999999999996),
],
<Offset>[
Offset(43.99436998801117, 23.85233115929924),
Offset(43.935955265272696, 24.180362852333243),
Offset(43.76617309606209, 24.778893280638325),
Offset(43.45759773349659, 24.887543031835328),
Offset(43.476142398493316, 25.33059113299948),
Offset(42.61623543783426, 30.292746160199744),
Offset(38.56421880483555, 37.258579505338574),
Offset(31.270083850246664, 42.30698994401817),
Offset(23.782610635873013, 43.696515982893125),
Offset(18.012800970955436, 42.76575199097035),
Offset(13.977530596101534, 40.95730246967126),
Offset(11.240070848553863, 39.00613901208685),
Offset(9.393565839291185, 37.2155999148309),
Offset(8.148821505536425, 35.693593987164746),
Offset(7.310730957903452, 34.462709918587905),
Offset(6.750976658788051, 33.51163465311433),
Offset(6.385465372525527, 32.8163580835571),
Offset(6.159564015210972, 32.3497810673481),
Offset(6.038321541199782, 32.08567294309337),
Offset(6.00003765337415, 32.00008471955465),
Offset(6.0000000000000036, 32.00000000000001),
],
<Offset>[
Offset(43.99436998801117, 23.85233115929924),
Offset(43.935955265272696, 24.180362852333243),
Offset(43.76617309606209, 24.778893280638325),
Offset(43.45759773349659, 24.887543031835328),
Offset(43.476142398493316, 25.33059113299948),
Offset(42.61623543783426, 30.292746160199744),
Offset(38.56421880483555, 37.258579505338574),
Offset(31.270083850246664, 42.30698994401817),
Offset(23.782610635873013, 43.696515982893125),
Offset(18.012800970955436, 42.76575199097035),
Offset(13.977530596101534, 40.95730246967126),
Offset(11.240070848553863, 39.00613901208685),
Offset(9.393565839291185, 37.2155999148309),
Offset(8.148821505536425, 35.693593987164746),
Offset(7.310730957903452, 34.462709918587905),
Offset(6.750976658788051, 33.51163465311433),
Offset(6.385465372525527, 32.8163580835571),
Offset(6.159564015210972, 32.3497810673481),
Offset(6.038321541199782, 32.08567294309337),
Offset(6.00003765337415, 32.00008471955465),
Offset(6.0000000000000036, 32.00000000000001),
],
),
_PathCubicTo(
<Offset>[
Offset(43.99436998801117, 23.85233115929924),
Offset(43.935955265272696, 24.180362852333243),
Offset(43.76617309606209, 24.778893280638325),
Offset(43.45759773349659, 24.887543031835328),
Offset(43.476142398493316, 25.33059113299948),
Offset(42.61623543783426, 30.292746160199744),
Offset(38.56421880483555, 37.258579505338574),
Offset(31.270083850246664, 42.30698994401817),
Offset(23.782610635873013, 43.696515982893125),
Offset(18.012800970955436, 42.76575199097035),
Offset(13.977530596101534, 40.95730246967126),
Offset(11.240070848553863, 39.00613901208685),
Offset(9.393565839291185, 37.2155999148309),
Offset(8.148821505536425, 35.693593987164746),
Offset(7.310730957903452, 34.462709918587905),
Offset(6.750976658788051, 33.51163465311433),
Offset(6.385465372525527, 32.8163580835571),
Offset(6.159564015210972, 32.3497810673481),
Offset(6.038321541199782, 32.08567294309337),
Offset(6.00003765337415, 32.00008471955465),
Offset(6.0000000000000036, 32.00000000000001),
],
<Offset>[
Offset(23.684125337090187, 6.329045030292864),
Offset(24.757855588602716, 6.52232881591406),
Offset(27.574407323047023, 7.305175651635392),
Offset(34.29718691345236, 10.565460438397327),
Offset(42.96465562689078, 18.312204872233718),
Offset(45.05615687408604, 26.45166424955556),
Offset(42.232333320435735, 35.60390079421558),
Offset(35.26685178627038, 42.467757059973906),
Offset(27.4197052006056, 45.36131120369138),
Offset(21.001315853482343, 45.424469500769995),
Offset(16.29765110355406, 44.215682562738714),
Offset(12.97234991047133, 42.61158062881598),
Offset(10.641290841160107, 41.016018618041265),
Offset(9.0114530912401, 39.59946991291384),
Offset(7.875830197056132, 38.422591589788325),
Offset(7.093422401327867, 37.49694905895691),
Offset(6.568745459991835, 36.81215692853645),
Offset(6.237631760921833, 36.34901917317271),
Offset(6.057380152594408, 36.08562753900215),
Offset(6.000056479961543, 36.00008471951035),
Offset(6.0000000000000036, 36.00000000000001),
],
<Offset>[
Offset(23.684125337090187, 6.329045030292864),
Offset(24.757855588602716, 6.52232881591406),
Offset(27.574407323047023, 7.305175651635392),
Offset(34.29718691345236, 10.565460438397327),
Offset(42.96465562689078, 18.312204872233718),
Offset(45.05615687408604, 26.45166424955556),
Offset(42.232333320435735, 35.60390079421558),
Offset(35.26685178627038, 42.467757059973906),
Offset(27.4197052006056, 45.36131120369138),
Offset(21.001315853482343, 45.424469500769995),
Offset(16.29765110355406, 44.215682562738714),
Offset(12.97234991047133, 42.61158062881598),
Offset(10.641290841160107, 41.016018618041265),
Offset(9.0114530912401, 39.59946991291384),
Offset(7.875830197056132, 38.422591589788325),
Offset(7.093422401327867, 37.49694905895691),
Offset(6.568745459991835, 36.81215692853645),
Offset(6.237631760921833, 36.34901917317271),
Offset(6.057380152594408, 36.08562753900215),
Offset(6.000056479961543, 36.00008471951035),
Offset(6.0000000000000036, 36.00000000000001),
],
),
_PathClose(
),
],
),
],
);
| flutter/packages/flutter/lib/src/material/animated_icons/data/home_menu.g.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/animated_icons/data/home_menu.g.dart",
"repo_id": "flutter",
"token_count": 49507
} | 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 'dart:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// Overrides the default properties values for descendant [Badge] widgets.
///
/// Descendant widgets obtain the current [BadgeThemeData] object
/// using `BadgeTheme.of(context)`. Instances of [BadgeThemeData] can
/// be customized with [BadgeThemeData.copyWith].
///
/// Typically a [BadgeThemeData] is specified as part of the
/// overall [Theme] with [ThemeData.badgeTheme].
///
/// All [BadgeThemeData] properties are `null` by default.
/// When null, the [Badge] will use the values from [ThemeData]
/// if they exist, otherwise it will provide its own defaults.
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
@immutable
class BadgeThemeData with Diagnosticable {
/// Creates the set of color, style, and size properties used to configure [Badge].
const BadgeThemeData({
this.backgroundColor,
this.textColor,
this.smallSize,
this.largeSize,
this.textStyle,
this.padding,
this.alignment,
this.offset,
});
/// Overrides the default value for [Badge.backgroundColor].
final Color? backgroundColor;
/// Overrides the default value for [Badge.textColor].
final Color? textColor;
/// Overrides the default value for [Badge.smallSize].
final double? smallSize;
/// Overrides the default value for [Badge.largeSize].
final double? largeSize;
/// Overrides the default value for [Badge.textStyle].
final TextStyle? textStyle;
/// Overrides the default value for [Badge.padding].
final EdgeInsetsGeometry? padding;
/// Overrides the default value for [Badge.alignment].
final AlignmentGeometry? alignment;
/// Overrides the default value for [Badge.offset].
final Offset? offset;
/// Creates a copy of this object but with the given fields replaced with the
/// new values.
BadgeThemeData copyWith({
Color? backgroundColor,
Color? textColor,
double? smallSize,
double? largeSize,
TextStyle? textStyle,
EdgeInsetsGeometry? padding,
AlignmentGeometry? alignment,
Offset? offset,
}) {
return BadgeThemeData(
backgroundColor: backgroundColor ?? this.backgroundColor,
textColor: textColor ?? this.textColor,
smallSize: smallSize ?? this.smallSize,
largeSize: largeSize ?? this.largeSize,
textStyle: textStyle ?? this.textStyle,
padding: padding ?? this.padding,
alignment: alignment ?? this.alignment,
offset: offset ?? this.offset,
);
}
/// Linearly interpolate between two [Badge] themes.
static BadgeThemeData lerp(BadgeThemeData? a, BadgeThemeData? b, double t) {
if (identical(a, b) && a != null) {
return a;
}
return BadgeThemeData(
backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t),
textColor: Color.lerp(a?.textColor, b?.textColor, t),
smallSize: lerpDouble(a?.smallSize, b?.smallSize, t),
largeSize: lerpDouble(a?.largeSize, b?.largeSize, t),
textStyle: TextStyle.lerp(a?.textStyle, b?.textStyle, t),
padding: EdgeInsetsGeometry.lerp(a?.padding, b?.padding, t),
alignment: AlignmentGeometry.lerp(a?.alignment, b?.alignment, t),
offset: Offset.lerp(a?.offset, b?.offset, t),
);
}
@override
int get hashCode => Object.hash(
backgroundColor,
textColor,
smallSize,
largeSize,
textStyle,
padding,
alignment,
offset,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is BadgeThemeData
&& other.backgroundColor == backgroundColor
&& other.textColor == textColor
&& other.smallSize == smallSize
&& other.largeSize == largeSize
&& other.textStyle == textStyle
&& other.padding == padding
&& other.alignment == alignment
&& other.offset == offset;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null));
properties.add(ColorProperty('textColor', textColor, defaultValue: null));
properties.add(DoubleProperty('smallSize', smallSize, defaultValue: null));
properties.add(DoubleProperty('largeSize', largeSize, defaultValue: null));
properties.add(DiagnosticsProperty<TextStyle>('textStyle', textStyle, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: null));
properties.add(DiagnosticsProperty<Offset>('offset', offset, defaultValue: null));
}
}
/// An inherited widget that overrides the default color style, and size
/// parameters for [Badge]s in this widget's subtree.
///
/// Values specified here override the defaults for [Badge] properties which
/// are not given an explicit non-null value.
class BadgeTheme extends InheritedTheme {
/// Creates a theme that overrides the default color parameters for [Badge]s
/// in this widget's subtree.
const BadgeTheme({
super.key,
required this.data,
required super.child,
});
/// Specifies the default color and size overrides for descendant [Badge] widgets.
final BadgeThemeData data;
/// The closest instance of this class that encloses the given context.
///
/// If there is no enclosing [BadgeTheme] widget, then
/// [ThemeData.badgeTheme] is used.
///
/// Typical usage is as follows:
///
/// ```dart
/// BadgeThemeData theme = BadgeTheme.of(context);
/// ```
static BadgeThemeData of(BuildContext context) {
final BadgeTheme? badgeTheme = context.dependOnInheritedWidgetOfExactType<BadgeTheme>();
return badgeTheme?.data ?? Theme.of(context).badgeTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return BadgeTheme(data: data, child: child);
}
@override
bool updateShouldNotify(BadgeTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/badge_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/badge_theme.dart",
"repo_id": "flutter",
"token_count": 2087
} | 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 'package:flutter/widgets.dart';
import 'card_theme.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'material.dart';
import 'theme.dart';
enum _CardVariant { elevated, filled, outlined }
/// A Material Design card: a panel with slightly rounded corners and an
/// elevation shadow.
///
/// A card is a sheet of [Material] used to represent some related information,
/// for example an album, a geographical location, a meal, contact details, etc.
///
/// This is what it looks like when run:
///
/// 
///
/// {@tool dartpad}
/// This sample shows creation of a [Card] widget that shows album information
/// and two actions.
///
/// ** See code in examples/api/lib/material/card/card.0.dart **
/// {@end-tool}
///
/// Sometimes the primary action area of a card is the card itself. Cards can be
/// one large touch target that shows a detail screen when tapped.
///
/// {@tool dartpad}
/// This sample shows creation of a [Card] widget that can be tapped. When
/// tapped this [Card]'s [InkWell] displays an "ink splash" that fills the
/// entire card.
///
/// ** See code in examples/api/lib/material/card/card.1.dart **
/// {@end-tool}
///
/// Material Design 3 introduced new types of cards. The default [Card] is the
/// elevated card. To create a filled card, use [Card.filled]; to create a outlined
/// card, use [Card.outlined].
/// {@tool dartpad}
/// This sample shows creation of [Card] widgets for elevated, filled and
/// outlined types, as described in: https://m3.material.io/components/cards/overview
///
/// ** See code in examples/api/lib/material/card/card.2.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ListTile], to display icons and text in a card.
/// * [showDialog], to display a modal card.
/// * <https://material.io/design/components/cards.html>
/// * <https://m3.material.io/components/cards>
class Card extends StatelessWidget {
/// Creates a Material Design card.
///
/// The [elevation] must be null or non-negative.
const Card({
super.key,
this.color,
this.shadowColor,
this.surfaceTintColor,
this.elevation,
this.shape,
this.borderOnForeground = true,
this.margin,
this.clipBehavior,
this.child,
this.semanticContainer = true,
}) : assert(elevation == null || elevation >= 0.0),
_variant = _CardVariant.elevated;
/// Create a filled variant of Card.
///
/// Filled cards provide subtle separation from the background. This has less
/// emphasis than elevated(default) or outlined cards.
const Card.filled({
super.key,
this.color,
this.shadowColor,
this.surfaceTintColor,
this.elevation,
this.shape,
this.borderOnForeground = true,
this.margin,
this.clipBehavior,
this.child,
this.semanticContainer = true,
}) : assert(elevation == null || elevation >= 0.0),
_variant = _CardVariant.filled;
/// Create an outlined variant of Card.
///
/// Outlined cards have a visual boundary around the container. This can
/// provide greater emphasis than the other types.
const Card.outlined({
super.key,
this.color,
this.shadowColor,
this.surfaceTintColor,
this.elevation,
this.shape,
this.borderOnForeground = true,
this.margin,
this.clipBehavior,
this.child,
this.semanticContainer = true,
}) : assert(elevation == null || elevation >= 0.0),
_variant = _CardVariant.outlined;
/// The card's background color.
///
/// Defines the card's [Material.color].
///
/// If this property is null then the ambient [CardTheme.color] is used. If that is null,
/// and [ThemeData.useMaterial3] is true, then [ColorScheme.surfaceContainerLow] of
/// [ThemeData.colorScheme] is used. Otherwise, [ThemeData.cardColor] is used.
final Color? color;
/// The color to paint the shadow below the card.
///
/// If null then the ambient [CardTheme]'s shadowColor is used.
/// If that's null too, then the overall theme's [ThemeData.shadowColor]
/// (default black) is used.
final Color? shadowColor;
/// The color used as an overlay on [color] to indicate elevation.
///
/// 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.
///
/// If this is null, no overlay will be applied. Otherwise this color
/// will be composited on top of [color] with an opacity related
/// to [elevation] and used to paint the background of the card.
///
/// The default is [Colors.transparent].
///
/// See [Material.surfaceTintColor] for more details on how this
/// overlay is applied.
final Color? surfaceTintColor;
/// The z-coordinate at which to place this card. This controls the size of
/// the shadow below the card.
///
/// Defines the card's [Material.elevation].
///
/// If this property is null then [CardTheme.elevation] of
/// [ThemeData.cardTheme] is used. If that's null, the default value is 1.0.
final double? elevation;
/// The shape of the card's [Material].
///
/// Defines the card's [Material.shape].
///
/// If this property is null then [CardTheme.shape] of [ThemeData.cardTheme]
/// is used. If that's null then the shape will be a [RoundedRectangleBorder]
/// with a circular corner radius of 12.0 and if [ThemeData.useMaterial3] is
/// false, then the circular corner radius will be 4.0.
final ShapeBorder? shape;
/// Whether to paint the [shape] border in front of the [child].
///
/// The default value is true.
/// If false, the border will be painted behind the [child].
final bool borderOnForeground;
/// {@macro flutter.material.Material.clipBehavior}
///
/// If this property is null then [CardTheme.clipBehavior] of
/// [ThemeData.cardTheme] is used. If that's null then the behavior will be [Clip.none].
final Clip? clipBehavior;
/// The empty space that surrounds the card.
///
/// Defines the card's outer [Container.margin].
///
/// If this property is null then [CardTheme.margin] of
/// [ThemeData.cardTheme] is used. If that's null, the default margin is 4.0
/// logical pixels on all sides: `EdgeInsets.all(4.0)`.
final EdgeInsetsGeometry? margin;
/// Whether this widget represents a single semantic container, or if false
/// a collection of individual semantic nodes.
///
/// Defaults to true.
///
/// Setting this flag to true will attempt to merge all child semantics into
/// this node. Setting this flag to false will force all child semantic nodes
/// to be explicit.
///
/// This flag should be false if the card contains multiple different types
/// of content.
final bool semanticContainer;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
final _CardVariant _variant;
@override
Widget build(BuildContext context) {
final CardTheme cardTheme = CardTheme.of(context);
final CardTheme defaults;
if (Theme.of(context).useMaterial3) {
defaults = switch (_variant) {
_CardVariant.elevated => _CardDefaultsM3(context),
_CardVariant.filled => _FilledCardDefaultsM3(context),
_CardVariant.outlined => _OutlinedCardDefaultsM3(context),
};
} else {
defaults = _CardDefaultsM2(context);
}
return Semantics(
container: semanticContainer,
child: Container(
margin: margin ?? cardTheme.margin ?? defaults.margin!,
child: Material(
type: MaterialType.card,
color: color ?? cardTheme.color ?? defaults.color,
shadowColor: shadowColor ?? cardTheme.shadowColor ?? defaults.shadowColor,
surfaceTintColor: surfaceTintColor ?? cardTheme.surfaceTintColor ?? defaults.surfaceTintColor,
elevation: elevation ?? cardTheme.elevation ?? defaults.elevation!,
shape: shape ?? cardTheme.shape ?? defaults.shape,
borderOnForeground: borderOnForeground,
clipBehavior: clipBehavior ?? cardTheme.clipBehavior ?? defaults.clipBehavior!,
child: Semantics(
explicitChildNodes: !semanticContainer,
child: child,
),
),
),
);
}
}
// Hand coded defaults based on Material Design 2.
class _CardDefaultsM2 extends CardTheme {
const _CardDefaultsM2(this.context)
: super(
clipBehavior: Clip.none,
elevation: 1.0,
margin: const EdgeInsets.all(4.0),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
)
);
final BuildContext context;
@override
Color? get color => Theme.of(context).cardColor;
@override
Color? get shadowColor => Theme.of(context).shadowColor;
}
// BEGIN GENERATED TOKEN PROPERTIES - Card
// 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 _CardDefaultsM3 extends CardTheme {
_CardDefaultsM3(this.context)
: super(
clipBehavior: Clip.none,
elevation: 1.0,
margin: const EdgeInsets.all(4.0),
);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
Color? get color => _colors.surfaceContainerLow;
@override
Color? get shadowColor => _colors.shadow;
@override
Color? get surfaceTintColor => Colors.transparent;
@override
ShapeBorder? get shape =>const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0)));
}
// END GENERATED TOKEN PROPERTIES - Card
// BEGIN GENERATED TOKEN PROPERTIES - FilledCard
// 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 _FilledCardDefaultsM3 extends CardTheme {
_FilledCardDefaultsM3(this.context)
: super(
clipBehavior: Clip.none,
elevation: 0.0,
margin: const EdgeInsets.all(4.0),
);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
Color? get color => _colors.surfaceContainerHighest;
@override
Color? get shadowColor => _colors.shadow;
@override
Color? get surfaceTintColor => Colors.transparent;
@override
ShapeBorder? get shape =>const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0)));
}
// END GENERATED TOKEN PROPERTIES - FilledCard
// BEGIN GENERATED TOKEN PROPERTIES - OutlinedCard
// 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 _OutlinedCardDefaultsM3 extends CardTheme {
_OutlinedCardDefaultsM3(this.context)
: super(
clipBehavior: Clip.none,
elevation: 0.0,
margin: const EdgeInsets.all(4.0),
);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
Color? get color => _colors.surface;
@override
Color? get shadowColor => _colors.shadow;
@override
Color? get surfaceTintColor => Colors.transparent;
@override
ShapeBorder? get shape =>
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0))).copyWith(
side: BorderSide(color: _colors.outlineVariant)
);
}
// END GENERATED TOKEN PROPERTIES - OutlinedCard
| flutter/packages/flutter/lib/src/material/card.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/card.dart",
"repo_id": "flutter",
"token_count": 4017
} | 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 'material_localizations.dart';
/// Utility functions for working with dates.
abstract final class DateUtils {
/// Returns a [DateTime] with the date of the original, but time set to
/// midnight.
static DateTime dateOnly(DateTime date) {
return DateTime(date.year, date.month, date.day);
}
/// Returns a [DateTimeRange] with the dates of the original, but with times
/// set to midnight.
///
/// See also:
/// * [dateOnly], which does the same thing for a single date.
static DateTimeRange datesOnly(DateTimeRange range) {
return DateTimeRange(start: dateOnly(range.start), end: dateOnly(range.end));
}
/// Returns true if the two [DateTime] objects have the same day, month, and
/// year, or are both null.
static bool isSameDay(DateTime? dateA, DateTime? dateB) {
return
dateA?.year == dateB?.year &&
dateA?.month == dateB?.month &&
dateA?.day == dateB?.day;
}
/// Returns true if the two [DateTime] objects have the same month and
/// year, or are both null.
static bool isSameMonth(DateTime? dateA, DateTime? dateB) {
return
dateA?.year == dateB?.year &&
dateA?.month == dateB?.month;
}
/// Determines the number of months between two [DateTime] objects.
///
/// For example:
///
/// ```dart
/// DateTime date1 = DateTime(2019, 6, 15);
/// DateTime date2 = DateTime(2020, 1, 15);
/// int delta = DateUtils.monthDelta(date1, date2);
/// ```
///
/// The value for `delta` would be `7`.
static int monthDelta(DateTime startDate, DateTime endDate) {
return (endDate.year - startDate.year) * 12 + endDate.month - startDate.month;
}
/// Returns a [DateTime] that is [monthDate] with the added number
/// of months and the day set to 1 and time set to midnight.
///
/// For example:
///
/// ```dart
/// DateTime date = DateTime(2019, 1, 15);
/// DateTime futureDate = DateUtils.addMonthsToMonthDate(date, 3);
/// ```
///
/// `date` would be January 15, 2019.
/// `futureDate` would be April 1, 2019 since it adds 3 months.
static DateTime addMonthsToMonthDate(DateTime monthDate, int monthsToAdd) {
return DateTime(monthDate.year, monthDate.month + monthsToAdd);
}
/// Returns a [DateTime] with the added number of days and time set to
/// midnight.
static DateTime addDaysToDate(DateTime date, int days) {
return DateTime(date.year, date.month, date.day + days);
}
/// Computes the offset from the first day of the week that the first day of
/// the [month] falls on.
///
/// For example, September 1, 2017 falls on a Friday, which in the calendar
/// localized for United States English appears as:
///
/// S M T W T F S
/// _ _ _ _ _ 1 2
///
/// The offset for the first day of the months is the number of leading blanks
/// in the calendar, i.e. 5.
///
/// The same date localized for the Russian calendar has a different offset,
/// because the first day of week is Monday rather than Sunday:
///
/// M T W T F S S
/// _ _ _ _ 1 2 3
///
/// So the offset is 4, rather than 5.
///
/// This code consolidates the following:
///
/// - [DateTime.weekday] provides a 1-based index into days of week, with 1
/// falling on Monday.
/// - [MaterialLocalizations.firstDayOfWeekIndex] provides a 0-based index
/// into the [MaterialLocalizations.narrowWeekdays] list.
/// - [MaterialLocalizations.narrowWeekdays] list provides localized names of
/// days of week, always starting with Sunday and ending with Saturday.
static int firstDayOffset(int year, int month, MaterialLocalizations localizations) {
// 0-based day of week for the month and year, with 0 representing Monday.
final int weekdayFromMonday = DateTime(year, month).weekday - 1;
// 0-based start of week depending on the locale, with 0 representing Sunday.
int firstDayOfWeekIndex = localizations.firstDayOfWeekIndex;
// firstDayOfWeekIndex recomputed to be Monday-based, in order to compare with
// weekdayFromMonday.
firstDayOfWeekIndex = (firstDayOfWeekIndex - 1) % 7;
// Number of days between the first day of week appearing on the calendar,
// and the day corresponding to the first of the month.
return (weekdayFromMonday - firstDayOfWeekIndex) % 7;
}
/// Returns the number of days in a month, according to the proleptic
/// Gregorian calendar.
///
/// This applies the leap year logic introduced by the Gregorian reforms of
/// 1582. It will not give valid results for dates prior to that time.
static int getDaysInMonth(int year, int month) {
if (month == DateTime.february) {
final bool isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
return isLeapYear ? 29 : 28;
}
const List<int> daysInMonth = <int>[31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return daysInMonth[month - 1];
}
}
/// Mode of date entry method for the date picker dialog.
///
/// In [calendar] mode, a calendar grid is displayed and the user taps the
/// day they wish to select. In [input] mode a TextField] is displayed and
/// the user types in the date they wish to select.
///
/// [calendarOnly] and [inputOnly] are variants of the above that don't
/// allow the user to change to the mode.
///
/// See also:
///
/// * [showDatePicker] and [showDateRangePicker], which use this to control
/// the initial entry mode of their dialogs.
enum DatePickerEntryMode {
/// User picks a date from calendar grid. Can switch to [input] by activating
/// a mode button in the dialog.
calendar,
/// User can input the date by typing it into a text field.
///
/// Can switch to [calendar] by activating a mode button in the dialog.
input,
/// User can only pick a date from calendar grid.
///
/// There is no user interface to switch to another mode.
calendarOnly,
/// User can only input the date by typing it into a text field.
///
/// There is no user interface to switch to another mode.
inputOnly,
}
/// Initial display of a calendar date picker.
///
/// Either a grid of available years or a monthly calendar.
///
/// See also:
///
/// * [showDatePicker], which shows a dialog that contains a Material Design
/// date picker.
/// * [CalendarDatePicker], widget which implements the Material Design date picker.
enum DatePickerMode {
/// Choosing a month and day.
day,
/// Choosing a year.
year,
}
/// Signature for predicating dates for enabled date selections.
///
/// See [showDatePicker], which has a [SelectableDayPredicate] parameter used
/// to specify allowable days in the date picker.
typedef SelectableDayPredicate = bool Function(DateTime day);
/// Encapsulates a start and end [DateTime] that represent the range of dates.
///
/// The range includes the [start] and [end] dates. The [start] and [end] dates
/// may be equal to indicate a date range of a single day. The [start] date must
/// not be after the [end] date.
///
/// See also:
/// * [showDateRangePicker], which displays a dialog that allows the user to
/// select a date range.
@immutable
class DateTimeRange {
/// Creates a date range for the given start and end [DateTime].
DateTimeRange({
required this.start,
required this.end,
}) : assert(!start.isAfter(end));
/// The start of the range of dates.
final DateTime start;
/// The end of the range of dates.
final DateTime end;
/// Returns a [Duration] of the time between [start] and [end].
///
/// See [DateTime.difference] for more details.
Duration get duration => end.difference(start);
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is DateTimeRange
&& other.start == start
&& other.end == end;
}
@override
int get hashCode => Object.hash(start, end);
@override
String toString() => '$start - $end';
}
| flutter/packages/flutter/lib/src/material/date.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/date.dart",
"repo_id": "flutter",
"token_count": 2514
} | 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/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'input_decorator.dart';
import 'menu_style.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// Overrides the default values of visual properties for descendant [DropdownMenu] widgets.
///
/// Descendant widgets obtain the current [DropdownMenuThemeData] object with
/// [DropdownMenuTheme.of]. Instances of [DropdownMenuTheme] can
/// be customized with [DropdownMenuThemeData.copyWith].
///
/// Typically a [DropdownMenuTheme] is specified as part of the overall [Theme] with
/// [ThemeData.dropdownMenuTheme].
///
/// All [DropdownMenuThemeData] properties are null by default. When null, the [DropdownMenu]
/// computes its own default values, typically based on the overall
/// theme's [ThemeData.colorScheme], [ThemeData.textTheme], and [ThemeData.iconTheme].
@immutable
class DropdownMenuThemeData with Diagnosticable {
/// Creates a [DropdownMenuThemeData] that can be used to override default properties
/// in a [DropdownMenuTheme] widget.
const DropdownMenuThemeData({
this.textStyle,
this.inputDecorationTheme,
this.menuStyle,
});
/// Overrides the default value for [DropdownMenu.textStyle].
final TextStyle? textStyle;
/// The input decoration theme for the [TextField]s in a [DropdownMenu].
///
/// If this is null, the [DropdownMenu] provides its own defaults.
final InputDecorationTheme? inputDecorationTheme;
/// Overrides the menu's default style in a [DropdownMenu].
///
/// Any values not set in the [MenuStyle] will use the menu default for that
/// property.
final MenuStyle? menuStyle;
/// Creates a copy of this object with the given fields replaced with the
/// new values.
DropdownMenuThemeData copyWith({
TextStyle? textStyle,
InputDecorationTheme? inputDecorationTheme,
MenuStyle? menuStyle,
}) {
return DropdownMenuThemeData(
textStyle: textStyle ?? this.textStyle,
inputDecorationTheme: inputDecorationTheme ?? this.inputDecorationTheme,
menuStyle: menuStyle ?? this.menuStyle,
);
}
/// Linearly interpolates between two dropdown menu themes.
static DropdownMenuThemeData lerp(DropdownMenuThemeData? a, DropdownMenuThemeData? b, double t) {
if (identical(a, b) && a != null) {
return a;
}
return DropdownMenuThemeData(
textStyle: TextStyle.lerp(a?.textStyle, b?.textStyle, t),
inputDecorationTheme: t < 0.5 ? a?.inputDecorationTheme : b?.inputDecorationTheme,
menuStyle: MenuStyle.lerp(a?.menuStyle, b?.menuStyle, t),
);
}
@override
int get hashCode => Object.hash(
textStyle,
inputDecorationTheme,
menuStyle,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is DropdownMenuThemeData
&& other.textStyle == textStyle
&& other.inputDecorationTheme == inputDecorationTheme
&& other.menuStyle == menuStyle;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<TextStyle>('textStyle', textStyle, defaultValue: null));
properties.add(DiagnosticsProperty<InputDecorationTheme>('inputDecorationTheme', inputDecorationTheme, defaultValue: null));
properties.add(DiagnosticsProperty<MenuStyle>('menuStyle', menuStyle, defaultValue: null));
}
}
/// An inherited widget that defines the visual properties for [DropdownMenu]s in this widget's subtree.
///
/// Values specified here are used for [DropdownMenu] properties that are not
/// given an explicit non-null value.
class DropdownMenuTheme extends InheritedTheme {
/// Creates a [DropdownMenuTheme] that controls visual parameters for
/// descendant [DropdownMenu]s.
const DropdownMenuTheme({
super.key,
required this.data,
required super.child,
});
/// Specifies the visual properties used by descendant [DropdownMenu]
/// widgets.
final DropdownMenuThemeData data;
/// The closest instance of this class that encloses the given context.
///
/// If there is no enclosing [DropdownMenuTheme] widget, then
/// [ThemeData.dropdownMenuTheme] is used.
///
/// Typical usage is as follows:
///
/// ```dart
/// DropdownMenuThemeData theme = DropdownMenuTheme.of(context);
/// ```
///
/// See also:
///
/// * [maybeOf], which returns null if it doesn't find a
/// [DropdownMenuTheme] ancestor.
static DropdownMenuThemeData of(BuildContext context) {
return maybeOf(context) ?? Theme.of(context).dropdownMenuTheme;
}
/// The data from the closest instance of this class that encloses the given
/// context, if any.
///
/// Use this function if you want to allow situations where no
/// [DropdownMenuTheme] is in scope. Prefer using [DropdownMenuTheme.of]
/// in situations where a [DropdownMenuThemeData] is expected to be
/// non-null.
///
/// If there is no [DropdownMenuTheme] in scope, then this function will
/// return null.
///
/// Typical usage is as follows:
///
/// ```dart
/// DropdownMenuThemeData? theme = DropdownMenuTheme.maybeOf(context);
/// if (theme == null) {
/// // Do something else instead.
/// }
/// ```
///
/// See also:
///
/// * [of], which will return [ThemeData.dropdownMenuTheme] if it doesn't
/// find a [DropdownMenuTheme] ancestor, instead of returning null.
static DropdownMenuThemeData? maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DropdownMenuTheme>()?.data;
}
@override
Widget wrap(BuildContext context, Widget child) {
return DropdownMenuTheme(data: data, child: child);
}
@override
bool updateShouldNotify(DropdownMenuTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/dropdown_menu_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/dropdown_menu_theme.dart",
"repo_id": "flutter",
"token_count": 1882
} | 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/widgets.dart';
/// The Flutter logo, in widget form. This widget respects the [IconTheme].
/// For guidelines on using the Flutter logo, visit https://flutter.dev/brand.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=aAmP-WcI6dg}
///
/// See also:
///
/// * [IconTheme], which provides ambient configuration for icons.
/// * [Icon], for showing icons the Material design icon library.
/// * [ImageIcon], for showing icons from [AssetImage]s or other [ImageProvider]s.
class FlutterLogo extends StatelessWidget {
/// Creates a widget that paints the Flutter logo.
///
/// The [size] defaults to the value given by the current [IconTheme].
///
/// The [textColor], [style], [duration], and [curve] arguments must not be
/// null.
const FlutterLogo({
super.key,
this.size,
this.textColor = const Color(0xFF757575),
this.style = FlutterLogoStyle.markOnly,
this.duration = const Duration(milliseconds: 750),
this.curve = Curves.fastOutSlowIn,
});
/// The size of the logo in logical pixels.
///
/// The logo will be fit into a square this size.
///
/// Defaults to the current [IconTheme] size, if any. If there is no
/// [IconTheme], or it does not specify an explicit size, then it defaults to
/// 24.0.
final double? size;
/// The color used to paint the "Flutter" text on the logo, if [style] is
/// [FlutterLogoStyle.horizontal] or [FlutterLogoStyle.stacked].
///
/// If possible, the default (a medium grey) should be used against a white
/// background.
final Color textColor;
/// Whether and where to draw the "Flutter" text. By default, only the logo
/// itself is drawn.
final FlutterLogoStyle style;
/// The length of time for the animation if the [style] or [textColor]
/// properties are changed.
final Duration duration;
/// The curve for the logo animation if the [style] or [textColor] change.
final Curve curve;
@override
Widget build(BuildContext context) {
final IconThemeData iconTheme = IconTheme.of(context);
final double? iconSize = size ?? iconTheme.size;
return AnimatedContainer(
width: iconSize,
height: iconSize,
duration: duration,
curve: curve,
decoration: FlutterLogoDecoration(
style: style,
textColor: textColor,
),
);
}
}
| flutter/packages/flutter/lib/src/material/flutter_logo.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/flutter_logo.dart",
"repo_id": "flutter",
"token_count": 794
} | 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 'dart:math' as math;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'debug.dart';
import 'divider.dart';
import 'icon_button.dart';
import 'icon_button_theme.dart';
import 'ink_decoration.dart';
import 'ink_well.dart';
import 'list_tile_theme.dart';
import 'material_state.dart';
import 'text_theme.dart';
import 'theme.dart';
import 'theme_data.dart';
// Examples can assume:
// int _act = 1;
/// Defines the title font used for [ListTile] descendants of a [ListTileTheme].
///
/// List tiles that appear in a [Drawer] use the theme's [TextTheme.bodyLarge]
/// text style, which is a little smaller than the theme's [TextTheme.titleMedium]
/// text style, which is used by default.
enum ListTileStyle {
/// Use a title font that's appropriate for a [ListTile] in a list.
list,
/// Use a title font that's appropriate for a [ListTile] that appears in a [Drawer].
drawer,
}
/// Where to place the control in widgets that use [ListTile] to position a
/// control next to a label.
///
/// See also:
///
/// * [CheckboxListTile], which combines a [ListTile] with a [Checkbox].
/// * [RadioListTile], which combines a [ListTile] with a [Radio] button.
/// * [SwitchListTile], which combines a [ListTile] with a [Switch].
/// * [ExpansionTile], which combines a [ListTile] with a button that expands
/// or collapses the tile to reveal or hide the children.
enum ListTileControlAffinity {
/// Position the control on the leading edge, and the secondary widget, if
/// any, on the trailing edge.
leading,
/// Position the control on the trailing edge, and the secondary widget, if
/// any, on the leading edge.
trailing,
/// Position the control relative to the text in the fashion that is typical
/// for the current platform, and place the secondary widget on the opposite
/// side.
platform,
}
/// Defines how [ListTile.leading] and [ListTile.trailing] are
/// vertically aligned relative to the [ListTile]'s titles
/// ([ListTile.title] and [ListTile.subtitle]).
///
/// See also:
///
/// * [ListTile.titleAlignment], to configure the title alignment for an
/// individual [ListTile].
/// * [ListTileThemeData.titleAlignment], to configure the title alignment
/// for all of the [ListTile]s under a [ListTileTheme].
/// * [ThemeData.listTileTheme], to configure the [ListTileTheme]
/// for an entire app.
enum ListTileTitleAlignment {
/// The top of the [ListTile.leading] and [ListTile.trailing] widgets are
/// placed [ListTile.minVerticalPadding] below the top of the [ListTile.title]
/// if [ListTile.isThreeLine] is true, otherwise they're centered relative
/// to the [ListTile.title] and [ListTile.subtitle] widgets.
///
/// This is the default when [ThemeData.useMaterial3] is true.
threeLine,
/// The tops of the [ListTile.leading] and [ListTile.trailing] widgets are
/// placed 16 units below the top of the [ListTile.title]
/// if the titles' overall height is greater than 72, otherwise they're
/// centered relative to the [ListTile.title] and [ListTile.subtitle] widgets.
///
/// This is the default when [ThemeData.useMaterial3] is false.
titleHeight,
/// The tops of the [ListTile.leading] and [ListTile.trailing] widgets are
/// placed [ListTile.minVerticalPadding] below the top of the [ListTile.title].
top,
/// The [ListTile.leading] and [ListTile.trailing] widgets are
/// centered relative to the [ListTile]'s titles.
center,
/// The bottoms of the [ListTile.leading] and [ListTile.trailing] widgets are
/// placed [ListTile.minVerticalPadding] above the bottom of the [ListTile]'s
/// titles.
bottom,
}
/// A single fixed-height row that typically contains some text as well as
/// a leading or trailing icon.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=l8dj0yPBvgQ}
///
/// A list tile contains one to three lines of text optionally flanked by icons or
/// other widgets, such as check boxes. The icons (or other widgets) for the
/// tile are defined with the [leading] and [trailing] parameters. The first
/// line of text is not optional and is specified with [title]. The value of
/// [subtitle], which _is_ optional, will occupy the space allocated for an
/// additional line of text, or two lines if [isThreeLine] is true. If [dense]
/// is true then the overall height of this tile and the size of the
/// [DefaultTextStyle]s that wrap the [title] and [subtitle] widget are reduced.
///
/// It is the responsibility of the caller to ensure that [title] does not wrap,
/// and to ensure that [subtitle] doesn't wrap (if [isThreeLine] is false) or
/// wraps to two lines (if it is true).
///
/// The heights of the [leading] and [trailing] widgets are constrained
/// according to the
/// [Material spec](https://material.io/design/components/lists.html).
/// An exception is made for one-line ListTiles for accessibility. Please
/// see the example below to see how to adhere to both Material spec and
/// accessibility requirements.
///
/// The [leading] and [trailing] widgets can expand as far as they wish
/// horizontally, so ensure that they are properly constrained.
///
/// List tiles are typically used in [ListView]s, or arranged in [Column]s in
/// [Drawer]s and [Card]s.
///
/// This widget requires a [Material] widget ancestor in the tree to paint
/// itself on, which is typically provided by the app's [Scaffold].
/// The [tileColor], [selectedTileColor], [focusColor], and [hoverColor]
/// are not painted by the [ListTile] itself but by the [Material] widget
/// ancestor. In this case, one can wrap a [Material] widget around the
/// [ListTile], e.g.:
///
/// {@tool snippet}
/// ```dart
/// const ColoredBox(
/// color: Colors.green,
/// child: Material(
/// child: ListTile(
/// title: Text('ListTile with red background'),
/// tileColor: Colors.red,
/// ),
/// ),
/// )
/// ```
/// {@end-tool}
///
/// ## Performance considerations when wrapping [ListTile] with [Material]
///
/// Wrapping a large number of [ListTile]s individually with [Material]s
/// is expensive. Consider only wrapping the [ListTile]s that require it
/// or include a common [Material] ancestor where possible.
///
/// [ListTile] must be wrapped in a [Material] widget to animate [tileColor],
/// [selectedTileColor], [focusColor], and [hoverColor] as these colors
/// are not drawn by the list tile itself but by the material widget ancestor.
///
/// {@tool dartpad}
/// This example showcases how [ListTile] needs to be wrapped in a [Material]
/// widget to animate colors.
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example uses a [ListView] to demonstrate different configurations of
/// [ListTile]s in [Card]s.
///
/// 
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.1.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample shows the creation of a [ListTile] using [ThemeData.useMaterial3] flag,
/// as described in: https://m3.material.io/components/lists/overview.
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.2.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample shows [ListTile]'s [textColor] and [iconColor] can use
/// [MaterialStateColor] color to change the color of the text and icon
/// when the [ListTile] is enabled, selected, or disabled.
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.3.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample shows [ListTile.titleAlignment] can be used to configure the
/// [leading] and [trailing] widgets alignment relative to the [title] and
/// [subtitle] widgets.
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.4.dart **
/// {@end-tool}
///
/// {@tool snippet}
/// To use a [ListTile] within a [Row], it needs to be wrapped in an
/// [Expanded] widget. [ListTile] requires fixed width constraints,
/// whereas a [Row] does not constrain its children.
///
/// ```dart
/// const Row(
/// children: <Widget>[
/// Expanded(
/// child: ListTile(
/// leading: FlutterLogo(),
/// title: Text('These ListTiles are expanded '),
/// ),
/// ),
/// Expanded(
/// child: ListTile(
/// trailing: FlutterLogo(),
/// title: Text('to fill the available space.'),
/// ),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
/// {@tool snippet}
///
/// Tiles can be much more elaborate. Here is a tile which can be tapped, but
/// which is disabled when the `_act` variable is not 2. When the tile is
/// tapped, the whole row has an ink splash effect (see [InkWell]).
///
/// ```dart
/// ListTile(
/// leading: const Icon(Icons.flight_land),
/// title: const Text("Trix's airplane"),
/// subtitle: _act != 2 ? const Text('The airplane is only in Act II.') : null,
/// enabled: _act == 2,
/// onTap: () { /* react to the tile being tapped */ }
/// )
/// ```
/// {@end-tool}
///
/// To be accessible, tappable [leading] and [trailing] widgets have to
/// be at least 48x48 in size. However, to adhere to the Material spec,
/// [trailing] and [leading] widgets in one-line ListTiles should visually be
/// at most 32 ([dense]: true) or 40 ([dense]: false) in height, which may
/// conflict with the accessibility requirement.
///
/// For this reason, a one-line ListTile allows the height of [leading]
/// and [trailing] widgets to be constrained by the height of the ListTile.
/// This allows for the creation of tappable [leading] and [trailing] widgets
/// that are large enough, but it is up to the developer to ensure that
/// their widgets follow the Material spec.
///
/// {@tool snippet}
///
/// Here is an example of a one-line, non-[dense] ListTile with a
/// tappable leading widget that adheres to accessibility requirements and
/// the Material spec. To adjust the use case below for a one-line, [dense]
/// ListTile, adjust the vertical padding to 8.0.
///
/// ```dart
/// ListTile(
/// leading: GestureDetector(
/// behavior: HitTestBehavior.translucent,
/// onTap: () {},
/// child: Container(
/// width: 48,
/// height: 48,
/// padding: const EdgeInsets.symmetric(vertical: 4.0),
/// alignment: Alignment.center,
/// child: const CircleAvatar(),
/// ),
/// ),
/// title: const Text('title'),
/// dense: false,
/// )
/// ```
/// {@end-tool}
///
/// ## The ListTile layout isn't exactly what I want
///
/// If the way ListTile pads and positions its elements isn't quite what
/// you're looking for, it's easy to create custom list items with a
/// combination of other widgets, such as [Row]s and [Column]s.
///
/// {@tool dartpad}
/// Here is an example of a custom list item that resembles a YouTube-related
/// video list item created with [Expanded] and [Container] widgets.
///
/// ** See code in examples/api/lib/material/list_tile/custom_list_item.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// Here is an example of an article list item with multiline titles and
/// subtitles. It utilizes [Row]s and [Column]s, as well as [Expanded] and
/// [AspectRatio] widgets to organize its layout.
///
/// ** See code in examples/api/lib/material/list_tile/custom_list_item.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ListTileTheme], which defines visual properties for [ListTile]s.
/// * [ListView], which can display an arbitrary number of [ListTile]s
/// in a scrolling list.
/// * [CircleAvatar], which shows an icon representing a person and is often
/// used as the [leading] element of a ListTile.
/// * [Card], which can be used with [Column] to show a few [ListTile]s.
/// * [Divider], which can be used to separate [ListTile]s.
/// * [ListTile.divideTiles], a utility for inserting [Divider]s in between [ListTile]s.
/// * [CheckboxListTile], [RadioListTile], and [SwitchListTile], widgets
/// that combine [ListTile] with other controls.
/// * Material 3 [ListTile] specifications are referenced from <https://m3.material.io/components/lists/specs>
/// and Material 2 [ListTile] specifications are referenced from <https://material.io/design/components/lists.html>
/// * Cookbook: [Use lists](https://flutter.dev/docs/cookbook/lists/basic-list)
/// * Cookbook: [Implement swipe to dismiss](https://flutter.dev/docs/cookbook/gestures/dismissible)
class ListTile extends StatelessWidget {
/// Creates a list tile.
///
/// If [isThreeLine] is true, then [subtitle] must not be null.
///
/// Requires one of its ancestors to be a [Material] widget.
const ListTile({
super.key,
this.leading,
this.title,
this.subtitle,
this.trailing,
this.isThreeLine = false,
this.dense,
this.visualDensity,
this.shape,
this.style,
this.selectedColor,
this.iconColor,
this.textColor,
this.titleTextStyle,
this.subtitleTextStyle,
this.leadingAndTrailingTextStyle,
this.contentPadding,
this.enabled = true,
this.onTap,
this.onLongPress,
this.onFocusChange,
this.mouseCursor,
this.selected = false,
this.focusColor,
this.hoverColor,
this.splashColor,
this.focusNode,
this.autofocus = false,
this.tileColor,
this.selectedTileColor,
this.enableFeedback,
this.horizontalTitleGap,
this.minVerticalPadding,
this.minLeadingWidth,
this.minTileHeight,
this.titleAlignment,
}) : assert(!isThreeLine || subtitle != null);
/// A widget to display before the title.
///
/// Typically an [Icon] or a [CircleAvatar] widget.
final Widget? leading;
/// The primary content of the list tile.
///
/// Typically a [Text] widget.
///
/// This should not wrap. To enforce the single line limit, use
/// [Text.maxLines].
final Widget? title;
/// Additional content displayed below the title.
///
/// Typically a [Text] widget.
///
/// If [isThreeLine] is false, this should not wrap.
///
/// If [isThreeLine] is true, this should be configured to take a maximum of
/// two lines. For example, you can use [Text.maxLines] to enforce the number
/// of lines.
///
/// The subtitle's default [TextStyle] depends on [TextTheme.bodyMedium] except
/// [TextStyle.color]. The [TextStyle.color] depends on the value of [enabled]
/// and [selected].
///
/// When [enabled] is false, the text color is set to [ThemeData.disabledColor].
///
/// When [selected] is false, the text color is set to [ListTileTheme.textColor]
/// if it's not null and to [TextTheme.bodySmall]'s color if [ListTileTheme.textColor]
/// is null.
final Widget? subtitle;
/// A widget to display after the title.
///
/// Typically an [Icon] widget.
///
/// To show right-aligned metadata (assuming left-to-right reading order;
/// left-aligned for right-to-left reading order), consider using a [Row] with
/// [CrossAxisAlignment.baseline] alignment whose first item is [Expanded] and
/// whose second child is the metadata text, instead of using the [trailing]
/// property.
final Widget? trailing;
/// Whether this list tile is intended to display three lines of text.
///
/// If true, then [subtitle] must be non-null (since it is expected to give
/// the second and third lines of text).
///
/// If false, the list tile is treated as having one line if the subtitle is
/// null and treated as having two lines if the subtitle is non-null.
///
/// When using a [Text] widget for [title] and [subtitle], you can enforce
/// line limits using [Text.maxLines].
final bool isThreeLine;
/// {@template flutter.material.ListTile.dense}
/// Whether this list tile is part of a vertically dense list.
///
/// If this property is null then its value is based on [ListTileTheme.dense].
///
/// Dense list tiles default to a smaller height.
///
/// It is not recommended to set [dense] to true when [ThemeData.useMaterial3] is true.
/// {@endtemplate}
final bool? dense;
/// Defines how compact the list tile's layout will be.
///
/// {@macro flutter.material.themedata.visualDensity}
///
/// See also:
///
/// * [ThemeData.visualDensity], which specifies the [visualDensity] for all
/// widgets within a [Theme].
final VisualDensity? visualDensity;
/// {@template flutter.material.ListTile.shape}
/// Defines the tile's [InkWell.customBorder] and [Ink.decoration] shape.
/// {@endtemplate}
///
/// If this property is null then [ListTileThemeData.shape] is used. If that
/// is also null then a rectangular [Border] will be used.
///
/// See also:
///
/// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
/// [ListTileThemeData].
final ShapeBorder? shape;
/// Defines the color used for icons and text when the list tile is selected.
///
/// If this property is null then [ListTileThemeData.selectedColor]
/// is used. If that is also null then [ColorScheme.primary] is used.
///
/// See also:
///
/// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
/// [ListTileThemeData].
final Color? selectedColor;
/// Defines the default color for [leading] and [trailing] icons.
///
/// If this property is null and [selected] is false then [ListTileThemeData.iconColor]
/// is used. If that is also null and [ThemeData.useMaterial3] is true, [ColorScheme.onSurfaceVariant]
/// is used, otherwise if [ThemeData.brightness] is [Brightness.light], [Colors.black54] is used,
/// and if [ThemeData.brightness] is [Brightness.dark], the value is null.
///
/// If this property is null and [selected] is true then [ListTileThemeData.selectedColor]
/// is used. If that is also null then [ColorScheme.primary] is used.
///
/// If this color is a [MaterialStateColor] it will be resolved against
/// [MaterialState.selected] and [MaterialState.disabled] states.
///
/// See also:
///
/// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
/// [ListTileThemeData].
final Color? iconColor;
/// Defines the text color for the [title], [subtitle], [leading], and [trailing].
///
/// If this property is null and [selected] is false then [ListTileThemeData.textColor]
/// is used. If that is also null then default text color is used for the [title], [subtitle]
/// [leading], and [trailing]. Except for [subtitle], if [ThemeData.useMaterial3] is false,
/// [TextTheme.bodySmall] is used.
///
/// If this property is null and [selected] is true then [ListTileThemeData.selectedColor]
/// is used. If that is also null then [ColorScheme.primary] is used.
///
/// If this color is a [MaterialStateColor] it will be resolved against
/// [MaterialState.selected] and [MaterialState.disabled] states.
///
/// See also:
///
/// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
/// [ListTileThemeData].
final Color? textColor;
/// The text style for ListTile's [title].
///
/// If this property is null, then [ListTileThemeData.titleTextStyle] is used.
/// If that is also null and [ThemeData.useMaterial3] is true, [TextTheme.bodyLarge]
/// with [ColorScheme.onSurface] will be used. Otherwise, If ListTile style is
/// [ListTileStyle.list], [TextTheme.titleMedium] will be used and if ListTile style
/// is [ListTileStyle.drawer], [TextTheme.bodyLarge] will be used.
final TextStyle? titleTextStyle;
/// The text style for ListTile's [subtitle].
///
/// If this property is null, then [ListTileThemeData.subtitleTextStyle] is used.
/// If that is also null and [ThemeData.useMaterial3] is true, [TextTheme.bodyMedium]
/// with [ColorScheme.onSurfaceVariant] will be used, otherwise [TextTheme.bodyMedium]
/// with [TextTheme.bodySmall] color will be used.
final TextStyle? subtitleTextStyle;
/// The text style for ListTile's [leading] and [trailing].
///
/// If this property is null, then [ListTileThemeData.leadingAndTrailingTextStyle] is used.
/// If that is also null and [ThemeData.useMaterial3] is true, [TextTheme.labelSmall]
/// with [ColorScheme.onSurfaceVariant] will be used, otherwise [TextTheme.bodyMedium]
/// will be used.
final TextStyle? leadingAndTrailingTextStyle;
/// Defines the font used for the [title].
///
/// If this property is null then [ListTileThemeData.style] is used. If that
/// is also null then [ListTileStyle.list] is used.
///
/// See also:
///
/// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
/// [ListTileThemeData].
final ListTileStyle? style;
/// The tile's internal padding.
///
/// Insets a [ListTile]'s contents: its [leading], [title], [subtitle],
/// and [trailing] widgets.
///
/// If null, `EdgeInsets.symmetric(horizontal: 16.0)` is used.
final EdgeInsetsGeometry? contentPadding;
/// Whether this list tile is interactive.
///
/// If false, this list tile is styled with the disabled color from the
/// current [Theme] and the [onTap] and [onLongPress] callbacks are
/// inoperative.
final bool enabled;
/// Called when the user taps this list tile.
///
/// Inoperative if [enabled] is false.
final GestureTapCallback? onTap;
/// Called when the user long-presses on this list tile.
///
/// Inoperative if [enabled] is false.
final GestureLongPressCallback? onLongPress;
/// {@macro flutter.material.inkwell.onFocusChange}
final ValueChanged<bool>? onFocusChange;
/// {@template flutter.material.ListTile.mouseCursor}
/// The cursor for a mouse pointer when it enters or is hovering over the
/// widget.
///
/// If [mouseCursor] is a [MaterialStateProperty<MouseCursor>],
/// [MaterialStateProperty.resolve] is used for the following [MaterialState]s:
///
/// * [MaterialState.selected].
/// * [MaterialState.disabled].
/// {@endtemplate}
///
/// If null, then the value of [ListTileThemeData.mouseCursor] is used. If
/// that is also null, then [MaterialStateMouseCursor.clickable] is used.
///
/// See also:
///
/// * [MaterialStateMouseCursor], which can be used to create a [MouseCursor]
/// that is also a [MaterialStateProperty<MouseCursor>].
final MouseCursor? mouseCursor;
/// If this tile is also [enabled] then icons and text are rendered with the same color.
///
/// By default the selected color is the theme's primary color. The selected color
/// can be overridden with a [ListTileTheme].
///
/// {@tool dartpad}
/// Here is an example of using a [StatefulWidget] to keep track of the
/// selected index, and using that to set the [selected] property on the
/// corresponding [ListTile].
///
/// ** See code in examples/api/lib/material/list_tile/list_tile.selected.0.dart **
/// {@end-tool}
final bool selected;
/// The color for the tile's [Material] when it has the input focus.
final Color? focusColor;
/// The color for the tile's [Material] when a pointer is hovering over it.
final Color? hoverColor;
/// The color of splash for the tile's [Material].
final Color? splashColor;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// {@macro flutter.widgets.Focus.autofocus}
final bool autofocus;
/// {@template flutter.material.ListTile.tileColor}
/// Defines the background color of `ListTile` when [selected] is false.
///
/// If this property is null and [selected] is false then [ListTileThemeData.tileColor]
/// is used. If that is also null and [selected] is true, [selectedTileColor] is used.
/// When that is also null, the [ListTileTheme.selectedTileColor] is used, otherwise
/// [Colors.transparent] is used.
///
/// {@endtemplate}
final Color? tileColor;
/// Defines the background color of `ListTile` when [selected] is true.
///
/// When the value if null, the [selectedTileColor] is set to [ListTileTheme.selectedTileColor]
/// if it's not null and to [Colors.transparent] if it's null.
final Color? selectedTileColor;
/// {@template flutter.material.ListTile.enableFeedback}
/// Whether detected gestures should provide acoustic and/or haptic feedback.
///
/// For example, on Android a tap will produce a clicking sound and a
/// long-press will produce a short vibration, when feedback is enabled.
///
/// When null, the default value is true.
/// {@endtemplate}
///
/// See also:
///
/// * [Feedback] for providing platform-specific feedback to certain actions.
final bool? enableFeedback;
/// The horizontal gap between the titles and the leading/trailing widgets.
///
/// If null, then the value of [ListTileTheme.horizontalTitleGap] is used. If
/// that is also null, then a default value of 16 is used.
final double? horizontalTitleGap;
/// The minimum padding on the top and bottom of the title and subtitle widgets.
///
/// If null, then the value of [ListTileTheme.minVerticalPadding] is used. If
/// that is also null, then a default value of 4 is used.
final double? minVerticalPadding;
/// The minimum width allocated for the [ListTile.leading] widget.
///
/// If null, then the value of [ListTileTheme.minLeadingWidth] is used. If
/// that is also null, then a default value of 40 is used.
final double? minLeadingWidth;
/// {@template flutter.material.ListTile.minTileHeight}
/// The minimum height allocated for the [ListTile] widget.
///
/// If this is null, default tile heights are 56.0, 72.0, and 88.0 for one,
/// two, and three lines of text respectively. If `isDense` is true, these
/// defaults are changed to 48.0, 64.0, and 76.0. A visual density value or
/// a large title will also adjust the default tile heights.
/// {@endtemplate}
final double? minTileHeight;
/// Defines how [ListTile.leading] and [ListTile.trailing] are
/// vertically aligned relative to the [ListTile]'s titles
/// ([ListTile.title] and [ListTile.subtitle]).
///
/// If this property is null then [ListTileThemeData.titleAlignment]
/// is used. If that is also null then [ListTileTitleAlignment.threeLine]
/// is used.
///
/// See also:
///
/// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s
/// [ListTileThemeData].
final ListTileTitleAlignment? titleAlignment;
/// Add a one pixel border in between each tile. If color isn't specified the
/// [ThemeData.dividerColor] of the context's [Theme] is used.
///
/// See also:
///
/// * [Divider], which you can use to obtain this effect manually.
static Iterable<Widget> divideTiles({ BuildContext? context, required Iterable<Widget> tiles, Color? color }) {
assert(color != null || context != null);
tiles = tiles.toList();
if (tiles.isEmpty || tiles.length == 1) {
return tiles;
}
Widget wrapTile(Widget tile) {
return DecoratedBox(
position: DecorationPosition.foreground,
decoration: BoxDecoration(
border: Border(
bottom: Divider.createBorderSide(context, color: color),
),
),
child: tile,
);
}
return <Widget>[
...tiles.take(tiles.length - 1).map(wrapTile),
tiles.last,
];
}
bool _isDenseLayout(ThemeData theme, ListTileThemeData tileTheme) {
return dense ?? tileTheme.dense ?? theme.listTileTheme.dense ?? false;
}
Color _tileBackgroundColor(ThemeData theme, ListTileThemeData tileTheme, ListTileThemeData defaults) {
final Color? color = selected
? selectedTileColor ?? tileTheme.selectedTileColor ?? theme.listTileTheme.selectedTileColor
: tileColor ?? tileTheme.tileColor ?? theme.listTileTheme.tileColor;
return color ?? defaults.tileColor!;
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context));
final ThemeData theme = Theme.of(context);
final ListTileThemeData tileTheme = ListTileTheme.of(context);
final ListTileStyle listTileStyle = style
?? tileTheme.style
?? theme.listTileTheme.style
?? ListTileStyle.list;
final ListTileThemeData defaults = theme.useMaterial3
? _LisTileDefaultsM3(context)
: _LisTileDefaultsM2(context, listTileStyle);
final Set<MaterialState> states = <MaterialState>{
if (!enabled) MaterialState.disabled,
if (selected) MaterialState.selected,
};
Color? resolveColor(Color? explicitColor, Color? selectedColor, Color? enabledColor, [Color? disabledColor]) {
return _IndividualOverrides(
explicitColor: explicitColor,
selectedColor: selectedColor,
enabledColor: enabledColor,
disabledColor: disabledColor,
).resolve(states);
}
final Color? effectiveIconColor = resolveColor(iconColor, selectedColor, iconColor)
?? resolveColor(tileTheme.iconColor, tileTheme.selectedColor, tileTheme.iconColor)
?? resolveColor(theme.listTileTheme.iconColor, theme.listTileTheme.selectedColor, theme.listTileTheme.iconColor)
?? resolveColor(defaults.iconColor, defaults.selectedColor, defaults.iconColor, theme.disabledColor);
final Color? effectiveColor = resolveColor(textColor, selectedColor, textColor)
?? resolveColor(tileTheme.textColor, tileTheme.selectedColor, tileTheme.textColor)
?? resolveColor(theme.listTileTheme.textColor, theme.listTileTheme.selectedColor, theme.listTileTheme.textColor)
?? resolveColor(defaults.textColor, defaults.selectedColor, defaults.textColor, theme.disabledColor);
final IconThemeData iconThemeData = IconThemeData(color: effectiveIconColor);
final IconButtonThemeData iconButtonThemeData = IconButtonThemeData(
style: IconButton.styleFrom(foregroundColor: effectiveIconColor),
);
TextStyle? leadingAndTrailingStyle;
if (leading != null || trailing != null) {
leadingAndTrailingStyle = leadingAndTrailingTextStyle
?? tileTheme.leadingAndTrailingTextStyle
?? defaults.leadingAndTrailingTextStyle!;
final Color? leadingAndTrailingTextColor = effectiveColor;
leadingAndTrailingStyle = leadingAndTrailingStyle.copyWith(color: leadingAndTrailingTextColor);
}
Widget? leadingIcon;
if (leading != null) {
leadingIcon = AnimatedDefaultTextStyle(
style: leadingAndTrailingStyle!,
duration: kThemeChangeDuration,
child: leading!,
);
}
TextStyle titleStyle = titleTextStyle
?? tileTheme.titleTextStyle
?? defaults.titleTextStyle!;
final Color? titleColor = effectiveColor;
titleStyle = titleStyle.copyWith(
color: titleColor,
fontSize: _isDenseLayout(theme, tileTheme) ? 13.0 : null,
);
final Widget titleText = AnimatedDefaultTextStyle(
style: titleStyle,
duration: kThemeChangeDuration,
child: title ?? const SizedBox(),
);
Widget? subtitleText;
TextStyle? subtitleStyle;
if (subtitle != null) {
subtitleStyle = subtitleTextStyle
?? tileTheme.subtitleTextStyle
?? defaults.subtitleTextStyle!;
final Color? subtitleColor = effectiveColor;
subtitleStyle = subtitleStyle.copyWith(
color: subtitleColor,
fontSize: _isDenseLayout(theme, tileTheme) ? 12.0 : null,
);
subtitleText = AnimatedDefaultTextStyle(
style: subtitleStyle,
duration: kThemeChangeDuration,
child: subtitle!,
);
}
Widget? trailingIcon;
if (trailing != null) {
trailingIcon = AnimatedDefaultTextStyle(
style: leadingAndTrailingStyle!,
duration: kThemeChangeDuration,
child: trailing!,
);
}
final TextDirection textDirection = Directionality.of(context);
final EdgeInsets resolvedContentPadding = contentPadding?.resolve(textDirection)
?? tileTheme.contentPadding?.resolve(textDirection)
?? defaults.contentPadding!.resolve(textDirection);
// Show basic cursor when ListTile isn't enabled or gesture callbacks are null.
final Set<MaterialState> mouseStates = <MaterialState>{
if (!enabled || (onTap == null && onLongPress == null)) MaterialState.disabled,
};
final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs<MouseCursor?>(mouseCursor, mouseStates)
?? tileTheme.mouseCursor?.resolve(mouseStates)
?? MaterialStateMouseCursor.clickable.resolve(mouseStates);
final ListTileTitleAlignment effectiveTitleAlignment = titleAlignment
?? tileTheme.titleAlignment
?? (theme.useMaterial3 ? ListTileTitleAlignment.threeLine : ListTileTitleAlignment.titleHeight);
return InkWell(
customBorder: shape ?? tileTheme.shape,
onTap: enabled ? onTap : null,
onLongPress: enabled ? onLongPress : null,
onFocusChange: onFocusChange,
mouseCursor: effectiveMouseCursor,
canRequestFocus: enabled,
focusNode: focusNode,
focusColor: focusColor,
hoverColor: hoverColor,
splashColor: splashColor,
autofocus: autofocus,
enableFeedback: enableFeedback ?? tileTheme.enableFeedback ?? true,
child: Semantics(
selected: selected,
enabled: enabled,
child: Ink(
decoration: ShapeDecoration(
shape: shape ?? tileTheme.shape ?? const Border(),
color: _tileBackgroundColor(theme, tileTheme, defaults),
),
child: SafeArea(
top: false,
bottom: false,
minimum: resolvedContentPadding,
child: IconTheme.merge(
data: iconThemeData,
child: IconButtonTheme(
data: iconButtonThemeData,
child: _ListTile(
leading: leadingIcon,
title: titleText,
subtitle: subtitleText,
trailing: trailingIcon,
isDense: _isDenseLayout(theme, tileTheme),
visualDensity: visualDensity ?? tileTheme.visualDensity ?? theme.visualDensity,
isThreeLine: isThreeLine,
textDirection: textDirection,
titleBaselineType: titleStyle.textBaseline ?? defaults.titleTextStyle!.textBaseline!,
subtitleBaselineType: subtitleStyle?.textBaseline ?? defaults.subtitleTextStyle!.textBaseline!,
horizontalTitleGap: horizontalTitleGap ?? tileTheme.horizontalTitleGap ?? 16,
minVerticalPadding: minVerticalPadding ?? tileTheme.minVerticalPadding ?? defaults.minVerticalPadding!,
minLeadingWidth: minLeadingWidth ?? tileTheme.minLeadingWidth ?? defaults.minLeadingWidth!,
minTileHeight: minTileHeight ?? tileTheme.minTileHeight,
titleAlignment: effectiveTitleAlignment,
),
),
),
),
),
),
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('isThreeLine', value: isThreeLine, ifTrue:'THREE_LINE', ifFalse: 'TWO_LINE', showName: true, defaultValue: false));
properties.add(FlagProperty('dense', value: dense, ifTrue: 'true', ifFalse: 'false', showName: true));
properties.add(DiagnosticsProperty<VisualDensity>('visualDensity', visualDensity, defaultValue: null));
properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null));
properties.add(DiagnosticsProperty<ListTileStyle>('style', style, defaultValue: null));
properties.add(ColorProperty('selectedColor', selectedColor, defaultValue: null));
properties.add(ColorProperty('iconColor', iconColor, defaultValue: null));
properties.add(ColorProperty('textColor', textColor, defaultValue: null));
properties.add(DiagnosticsProperty<TextStyle>('titleTextStyle', titleTextStyle, defaultValue: null));
properties.add(DiagnosticsProperty<TextStyle>('subtitleTextStyle', subtitleTextStyle, defaultValue: null));
properties.add(DiagnosticsProperty<TextStyle>('leadingAndTrailingTextStyle', leadingAndTrailingTextStyle, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('contentPadding', contentPadding, defaultValue: null));
properties.add(FlagProperty('enabled', value: enabled, ifTrue: 'true', ifFalse: 'false', showName: true, defaultValue: true));
properties.add(DiagnosticsProperty<Function>('onTap', onTap, defaultValue: null));
properties.add(DiagnosticsProperty<Function>('onLongPress', onLongPress, defaultValue: null));
properties.add(DiagnosticsProperty<MouseCursor>('mouseCursor', mouseCursor, defaultValue: null));
properties.add(FlagProperty('selected', value: selected, ifTrue: 'true', ifFalse: 'false', showName: true, defaultValue: false));
properties.add(ColorProperty('focusColor', focusColor, defaultValue: null));
properties.add(ColorProperty('hoverColor', hoverColor, defaultValue: null));
properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null));
properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'true', ifFalse: 'false', showName: true, defaultValue: false));
properties.add(ColorProperty('tileColor', tileColor, defaultValue: null));
properties.add(ColorProperty('selectedTileColor', selectedTileColor, defaultValue: null));
properties.add(FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', ifFalse: 'false', showName: true));
properties.add(DoubleProperty('horizontalTitleGap', horizontalTitleGap, defaultValue: null));
properties.add(DoubleProperty('minVerticalPadding', minVerticalPadding, defaultValue: null));
properties.add(DoubleProperty('minLeadingWidth', minLeadingWidth, defaultValue: null));
properties.add(DiagnosticsProperty<ListTileTitleAlignment>('titleAlignment', titleAlignment, defaultValue: null));
}
}
class _IndividualOverrides extends MaterialStateProperty<Color?> {
_IndividualOverrides({
this.explicitColor,
this.enabledColor,
this.selectedColor,
this.disabledColor,
});
final Color? explicitColor;
final Color? enabledColor;
final Color? selectedColor;
final Color? disabledColor;
@override
Color? resolve(Set<MaterialState> states) {
if (explicitColor is MaterialStateColor) {
return MaterialStateProperty.resolveAs<Color?>(explicitColor, states);
}
if (states.contains(MaterialState.disabled)) {
return disabledColor;
}
if (states.contains(MaterialState.selected)) {
return selectedColor;
}
return enabledColor;
}
}
// Identifies the children of a _ListTileElement.
enum _ListTileSlot {
leading,
title,
subtitle,
trailing,
}
class _ListTile extends SlottedMultiChildRenderObjectWidget<_ListTileSlot, RenderBox> {
const _ListTile({
this.leading,
required this.title,
this.subtitle,
this.trailing,
required this.isThreeLine,
required this.isDense,
required this.visualDensity,
required this.textDirection,
required this.titleBaselineType,
required this.horizontalTitleGap,
required this.minVerticalPadding,
required this.minLeadingWidth,
this.minTileHeight,
this.subtitleBaselineType,
required this.titleAlignment,
});
final Widget? leading;
final Widget title;
final Widget? subtitle;
final Widget? trailing;
final bool isThreeLine;
final bool isDense;
final VisualDensity visualDensity;
final TextDirection textDirection;
final TextBaseline titleBaselineType;
final TextBaseline? subtitleBaselineType;
final double horizontalTitleGap;
final double minVerticalPadding;
final double minLeadingWidth;
final double? minTileHeight;
final ListTileTitleAlignment titleAlignment;
@override
Iterable<_ListTileSlot> get slots => _ListTileSlot.values;
@override
Widget? childForSlot(_ListTileSlot slot) {
return switch (slot) {
_ListTileSlot.leading => leading,
_ListTileSlot.title => title,
_ListTileSlot.subtitle => subtitle,
_ListTileSlot.trailing => trailing,
};
}
@override
_RenderListTile createRenderObject(BuildContext context) {
return _RenderListTile(
isThreeLine: isThreeLine,
isDense: isDense,
visualDensity: visualDensity,
textDirection: textDirection,
titleBaselineType: titleBaselineType,
subtitleBaselineType: subtitleBaselineType,
horizontalTitleGap: horizontalTitleGap,
minVerticalPadding: minVerticalPadding,
minLeadingWidth: minLeadingWidth,
minTileHeight: minTileHeight,
titleAlignment: titleAlignment,
);
}
@override
void updateRenderObject(BuildContext context, _RenderListTile renderObject) {
renderObject
..isThreeLine = isThreeLine
..isDense = isDense
..visualDensity = visualDensity
..textDirection = textDirection
..titleBaselineType = titleBaselineType
..subtitleBaselineType = subtitleBaselineType
..horizontalTitleGap = horizontalTitleGap
..minLeadingWidth = minLeadingWidth
..minTileHeight = minTileHeight
..minVerticalPadding = minVerticalPadding
..titleAlignment = titleAlignment;
}
}
class _RenderListTile extends RenderBox with SlottedContainerRenderObjectMixin<_ListTileSlot, RenderBox> {
_RenderListTile({
required bool isDense,
required VisualDensity visualDensity,
required bool isThreeLine,
required TextDirection textDirection,
required TextBaseline titleBaselineType,
TextBaseline? subtitleBaselineType,
required double horizontalTitleGap,
required double minVerticalPadding,
required double minLeadingWidth,
double? minTileHeight,
required ListTileTitleAlignment titleAlignment
}) : _isDense = isDense,
_visualDensity = visualDensity,
_isThreeLine = isThreeLine,
_textDirection = textDirection,
_titleBaselineType = titleBaselineType,
_subtitleBaselineType = subtitleBaselineType,
_horizontalTitleGap = horizontalTitleGap,
_minVerticalPadding = minVerticalPadding,
_minLeadingWidth = minLeadingWidth,
_minTileHeight = minTileHeight,
_titleAlignment = titleAlignment;
RenderBox? get leading => childForSlot(_ListTileSlot.leading);
RenderBox? get title => childForSlot(_ListTileSlot.title);
RenderBox? get subtitle => childForSlot(_ListTileSlot.subtitle);
RenderBox? get trailing => childForSlot(_ListTileSlot.trailing);
// The returned list is ordered for hit testing.
@override
Iterable<RenderBox> get children {
return <RenderBox>[
if (leading != null)
leading!,
if (title != null)
title!,
if (subtitle != null)
subtitle!,
if (trailing != null)
trailing!,
];
}
bool get isDense => _isDense;
bool _isDense;
set isDense(bool value) {
if (_isDense == value) {
return;
}
_isDense = value;
markNeedsLayout();
}
VisualDensity get visualDensity => _visualDensity;
VisualDensity _visualDensity;
set visualDensity(VisualDensity value) {
if (_visualDensity == value) {
return;
}
_visualDensity = value;
markNeedsLayout();
}
bool get isThreeLine => _isThreeLine;
bool _isThreeLine;
set isThreeLine(bool value) {
if (_isThreeLine == value) {
return;
}
_isThreeLine = value;
markNeedsLayout();
}
TextDirection get textDirection => _textDirection;
TextDirection _textDirection;
set textDirection(TextDirection value) {
if (_textDirection == value) {
return;
}
_textDirection = value;
markNeedsLayout();
}
TextBaseline get titleBaselineType => _titleBaselineType;
TextBaseline _titleBaselineType;
set titleBaselineType(TextBaseline value) {
if (_titleBaselineType == value) {
return;
}
_titleBaselineType = value;
markNeedsLayout();
}
TextBaseline? get subtitleBaselineType => _subtitleBaselineType;
TextBaseline? _subtitleBaselineType;
set subtitleBaselineType(TextBaseline? value) {
if (_subtitleBaselineType == value) {
return;
}
_subtitleBaselineType = value;
markNeedsLayout();
}
double get horizontalTitleGap => _horizontalTitleGap;
double _horizontalTitleGap;
double get _effectiveHorizontalTitleGap => _horizontalTitleGap + visualDensity.horizontal * 2.0;
set horizontalTitleGap(double value) {
if (_horizontalTitleGap == value) {
return;
}
_horizontalTitleGap = value;
markNeedsLayout();
}
double get minVerticalPadding => _minVerticalPadding;
double _minVerticalPadding;
set minVerticalPadding(double value) {
if (_minVerticalPadding == value) {
return;
}
_minVerticalPadding = value;
markNeedsLayout();
}
double get minLeadingWidth => _minLeadingWidth;
double _minLeadingWidth;
set minLeadingWidth(double value) {
if (_minLeadingWidth == value) {
return;
}
_minLeadingWidth = value;
markNeedsLayout();
}
double? _minTileHeight;
double? get minTileHeight => _minTileHeight;
set minTileHeight(double? value) {
if (_minTileHeight == value) {
return;
}
_minTileHeight = value;
markNeedsLayout();
}
ListTileTitleAlignment get titleAlignment => _titleAlignment;
ListTileTitleAlignment _titleAlignment;
set titleAlignment(ListTileTitleAlignment value) {
if (_titleAlignment == value) {
return;
}
_titleAlignment = value;
markNeedsLayout();
}
@override
bool get sizedByParent => false;
static double _minWidth(RenderBox? box, double height) {
return box == null ? 0.0 : box.getMinIntrinsicWidth(height);
}
static double _maxWidth(RenderBox? box, double height) {
return box == null ? 0.0 : box.getMaxIntrinsicWidth(height);
}
@override
double computeMinIntrinsicWidth(double height) {
final double leadingWidth = leading != null
? math.max(leading!.getMinIntrinsicWidth(height), _minLeadingWidth) + _effectiveHorizontalTitleGap
: 0.0;
return leadingWidth
+ math.max(_minWidth(title, height), _minWidth(subtitle, height))
+ _maxWidth(trailing, height);
}
@override
double computeMaxIntrinsicWidth(double height) {
final double leadingWidth = leading != null
? math.max(leading!.getMaxIntrinsicWidth(height), _minLeadingWidth) + _effectiveHorizontalTitleGap
: 0.0;
return leadingWidth
+ math.max(_maxWidth(title, height), _maxWidth(subtitle, height))
+ _maxWidth(trailing, height);
}
double get _defaultTileHeight {
final bool hasSubtitle = subtitle != null;
final bool isTwoLine = !isThreeLine && hasSubtitle;
final bool isOneLine = !isThreeLine && !hasSubtitle;
final Offset baseDensity = visualDensity.baseSizeAdjustment;
if (isOneLine) {
return (isDense ? 48.0 : 56.0) + baseDensity.dy;
}
if (isTwoLine) {
return (isDense ? 64.0 : 72.0) + baseDensity.dy;
}
return (isDense ? 76.0 : 88.0) + baseDensity.dy;
}
@override
double computeMinIntrinsicHeight(double width) {
return math.max(
minTileHeight ?? _defaultTileHeight,
title!.getMinIntrinsicHeight(width) + (subtitle?.getMinIntrinsicHeight(width) ?? 0.0),
);
}
@override
double computeMaxIntrinsicHeight(double width) {
return computeMinIntrinsicHeight(width);
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
assert(title != null);
final BoxParentData parentData = title!.parentData! as BoxParentData;
final BaselineOffset offset = BaselineOffset(title!.getDistanceToActualBaseline(baseline))
+ parentData.offset.dy;
return offset.offset;
}
static double? _boxBaseline(RenderBox box, TextBaseline baseline) {
return box.getDistanceToBaseline(baseline);
}
static Size _layoutBox(RenderBox? box, BoxConstraints constraints) {
if (box == null) {
return Size.zero;
}
box.layout(constraints, parentUsesSize: true);
return box.size;
}
static void _positionBox(RenderBox box, Offset offset) {
final BoxParentData parentData = box.parentData! as BoxParentData;
parentData.offset = offset;
}
@override
Size computeDryLayout(BoxConstraints constraints) {
assert(debugCannotComputeDryLayout(
reason: 'Layout requires baseline metrics, which are only available after a full layout.',
));
return Size.zero;
}
// All of the dimensions below were taken from the Material Design spec:
// https://material.io/design/components/lists.html#specs
@override
void performLayout() {
final BoxConstraints constraints = this.constraints;
final bool hasLeading = leading != null;
final bool hasSubtitle = subtitle != null;
final bool hasTrailing = trailing != null;
final bool isTwoLine = !isThreeLine && hasSubtitle;
final bool isOneLine = !isThreeLine && !hasSubtitle;
final Offset densityAdjustment = visualDensity.baseSizeAdjustment;
final BoxConstraints maxIconHeightConstraint = BoxConstraints(
// One-line trailing and leading widget heights do not follow
// Material specifications, but this sizing is required to adhere
// to accessibility requirements for smallest tappable widget.
// Two- and three-line trailing widget heights are constrained
// properly according to the Material spec.
maxHeight: (isDense ? 48.0 : 56.0) + densityAdjustment.dy,
);
final BoxConstraints looseConstraints = constraints.loosen();
final BoxConstraints iconConstraints = looseConstraints.enforce(maxIconHeightConstraint);
final double tileWidth = looseConstraints.maxWidth;
final Size leadingSize = _layoutBox(leading, iconConstraints);
final Size trailingSize = _layoutBox(trailing, iconConstraints);
assert(
tileWidth != leadingSize.width || tileWidth == 0.0,
'Leading widget consumes entire tile width. Please use a sized widget, '
'or consider replacing ListTile with a custom widget '
'(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)',
);
assert(
tileWidth != trailingSize.width || tileWidth == 0.0,
'Trailing widget consumes entire tile width. Please use a sized widget, '
'or consider replacing ListTile with a custom widget '
'(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)',
);
final double titleStart = hasLeading
? math.max(_minLeadingWidth, leadingSize.width) + _effectiveHorizontalTitleGap
: 0.0;
final double adjustedTrailingWidth = hasTrailing
? math.max(trailingSize.width + _effectiveHorizontalTitleGap, 32.0)
: 0.0;
final BoxConstraints textConstraints = looseConstraints.tighten(
width: tileWidth - titleStart - adjustedTrailingWidth,
);
final Size titleSize = _layoutBox(title, textConstraints);
final Size subtitleSize = _layoutBox(subtitle, textConstraints);
double? titleBaseline;
double? subtitleBaseline;
if (isTwoLine) {
titleBaseline = isDense ? 28.0 : 32.0;
subtitleBaseline = isDense ? 48.0 : 52.0;
} else if (isThreeLine) {
titleBaseline = isDense ? 22.0 : 28.0;
subtitleBaseline = isDense ? 42.0 : 48.0;
} else {
assert(isOneLine);
}
double tileHeight;
double titleY;
double? subtitleY;
if (!hasSubtitle) {
tileHeight = math.max(minTileHeight ?? _defaultTileHeight, titleSize.height + 2.0 * _minVerticalPadding);
titleY = (tileHeight - titleSize.height) / 2.0;
} else {
assert(subtitleBaselineType != null);
titleY = titleBaseline! - _boxBaseline(title!, titleBaselineType)!;
subtitleY = subtitleBaseline! - _boxBaseline(subtitle!, subtitleBaselineType!)! + visualDensity.vertical * 2.0;
tileHeight = minTileHeight ?? _defaultTileHeight;
// If the title and subtitle overlap, move the title upwards by half
// the overlap and the subtitle down by the same amount, and adjust
// tileHeight so that both titles fit.
final double titleOverlap = titleY + titleSize.height - subtitleY;
if (titleOverlap > 0.0) {
titleY -= titleOverlap / 2.0;
subtitleY += titleOverlap / 2.0;
}
// If the title or subtitle overflow tileHeight then punt: title
// and subtitle are arranged in a column, tileHeight = column height plus
// _minVerticalPadding on top and bottom.
if (titleY < _minVerticalPadding ||
(subtitleY + subtitleSize.height + _minVerticalPadding) > tileHeight) {
tileHeight = titleSize.height + subtitleSize.height + 2.0 * _minVerticalPadding;
titleY = _minVerticalPadding;
subtitleY = titleSize.height + _minVerticalPadding;
}
}
final double leadingDiff = tileHeight - leadingSize.height;
final double trailingDiff = tileHeight - trailingSize.height;
final (double leadingY, double trailingY) = switch (titleAlignment) {
ListTileTitleAlignment.threeLine when isThreeLine => (_minVerticalPadding, _minVerticalPadding),
ListTileTitleAlignment.threeLine => (leadingDiff / 2.0, trailingDiff / 2.0),
// This attempts to implement the redlines for the vertical position of the
// leading and trailing icons on the spec page:
// https://m2.material.io/components/lists#specs
//
// For large tiles (> 72dp), both leading and trailing controls should be
// a fixed distance from top. As per guidelines this is set to 16dp.
ListTileTitleAlignment.titleHeight when tileHeight > 72.0 => (16.0, 16.0),
// For smaller tiles, trailing should always be centered. Leading can be
// centered or closer to the top. It should never be further than 16dp
// to the top.
ListTileTitleAlignment.titleHeight => (math.min(leadingDiff / 2.0, 16.0), trailingDiff / 2.0),
ListTileTitleAlignment.top => (_minVerticalPadding, _minVerticalPadding),
ListTileTitleAlignment.center => (leadingDiff / 2.0, trailingDiff / 2.0),
ListTileTitleAlignment.bottom => (leadingDiff - _minVerticalPadding, trailingDiff - _minVerticalPadding),
};
switch (textDirection) {
case TextDirection.rtl: {
if (hasLeading) {
_positionBox(leading!, Offset(tileWidth - leadingSize.width, leadingY));
}
_positionBox(title!, Offset(adjustedTrailingWidth, titleY));
if (hasSubtitle) {
_positionBox(subtitle!, Offset(adjustedTrailingWidth, subtitleY!));
}
if (hasTrailing) {
_positionBox(trailing!, Offset(0.0, trailingY));
}
break;
}
case TextDirection.ltr: {
if (hasLeading) {
_positionBox(leading!, Offset(0.0, leadingY));
}
_positionBox(title!, Offset(titleStart, titleY));
if (hasSubtitle) {
_positionBox(subtitle!, Offset(titleStart, subtitleY!));
}
if (hasTrailing) {
_positionBox(trailing!, Offset(tileWidth - trailingSize.width, trailingY));
}
break;
}
}
size = constraints.constrain(Size(tileWidth, tileHeight));
assert(size.width == constraints.constrainWidth(tileWidth));
assert(size.height == constraints.constrainHeight(tileHeight));
}
@override
void paint(PaintingContext context, Offset offset) {
void doPaint(RenderBox? child) {
if (child != null) {
final BoxParentData parentData = child.parentData! as BoxParentData;
context.paintChild(child, parentData.offset + offset);
}
}
doPaint(leading);
doPaint(title);
doPaint(subtitle);
doPaint(trailing);
}
@override
bool hitTestSelf(Offset position) => true;
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
for (final RenderBox child in children) {
final BoxParentData parentData = child.parentData! as BoxParentData;
final bool isHit = result.addWithPaintOffset(
offset: parentData.offset,
position: position,
hitTest: (BoxHitTestResult result, Offset transformed) {
assert(transformed == position - parentData.offset);
return child.hitTest(result, position: transformed);
},
);
if (isHit) {
return true;
}
}
return false;
}
}
class _LisTileDefaultsM2 extends ListTileThemeData {
_LisTileDefaultsM2(this.context, ListTileStyle style)
: super(
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
minLeadingWidth: 40,
minVerticalPadding: 4,
shape: const Border(),
style: style,
);
final BuildContext context;
late final ThemeData _theme = Theme.of(context);
late final TextTheme _textTheme = _theme.textTheme;
@override
Color? get tileColor => Colors.transparent;
@override
TextStyle? get titleTextStyle {
return switch (style!) {
ListTileStyle.drawer => _textTheme.bodyLarge,
ListTileStyle.list => _textTheme.titleMedium,
};
}
@override
TextStyle? get subtitleTextStyle => _textTheme.bodyMedium!
.copyWith(color: _textTheme.bodySmall!.color);
@override
TextStyle? get leadingAndTrailingTextStyle => _textTheme.bodyMedium;
@override
Color? get selectedColor => _theme.colorScheme.primary;
@override
Color? get iconColor {
return switch (_theme.brightness) {
// For the sake of backwards compatibility, the default for unselected
// tiles is Colors.black45 rather than colorScheme.onSurface.withAlpha(0x73).
Brightness.light => Colors.black45,
// null -> use current icon theme color
Brightness.dark => null,
};
}
}
// BEGIN GENERATED TOKEN PROPERTIES - LisTile
// 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 _LisTileDefaultsM3 extends ListTileThemeData {
_LisTileDefaultsM3(this.context)
: super(
contentPadding: const EdgeInsetsDirectional.only(start: 16.0, end: 24.0),
minLeadingWidth: 24,
minVerticalPadding: 8,
shape: const RoundedRectangleBorder(),
);
final BuildContext context;
late final ThemeData _theme = Theme.of(context);
late final ColorScheme _colors = _theme.colorScheme;
late final TextTheme _textTheme = _theme.textTheme;
@override
Color? get tileColor => Colors.transparent;
@override
TextStyle? get titleTextStyle => _textTheme.bodyLarge!.copyWith(color: _colors.onSurface);
@override
TextStyle? get subtitleTextStyle => _textTheme.bodyMedium!.copyWith(color: _colors.onSurfaceVariant);
@override
TextStyle? get leadingAndTrailingTextStyle => _textTheme.labelSmall!.copyWith(color: _colors.onSurfaceVariant);
@override
Color? get selectedColor => _colors.primary;
@override
Color? get iconColor => _colors.onSurfaceVariant;
}
// END GENERATED TOKEN PROPERTIES - LisTile
| flutter/packages/flutter/lib/src/material/list_tile.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/list_tile.dart",
"repo_id": "flutter",
"token_count": 19795
} | 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/rendering.dart';
import 'package:flutter/widgets.dart';
import 'material_state.dart';
import 'navigation_bar.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// Defines default property values for descendant [NavigationBar]
/// widgets.
///
/// Descendant widgets obtain the current [NavigationBarThemeData] object
/// using `NavigationBarTheme.of(context)`. Instances of
/// [NavigationBarThemeData] can be customized with
/// [NavigationBarThemeData.copyWith].
///
/// Typically a [NavigationBarThemeData] is specified as part of the
/// overall [Theme] with [ThemeData.navigationBarTheme]. Alternatively, a
/// [NavigationBarTheme] inherited widget can be used to theme [NavigationBar]s
/// in a subtree of widgets.
///
/// All [NavigationBarThemeData] properties are `null` by default.
/// When null, the [NavigationBar] will provide its own defaults based on the
/// overall [Theme]'s textTheme and colorScheme. See the individual
/// [NavigationBar] properties for details.
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
@immutable
class NavigationBarThemeData with Diagnosticable {
/// Creates a theme that can be used for [ThemeData.navigationBarTheme] and
/// [NavigationBarTheme].
const NavigationBarThemeData({
this.height,
this.backgroundColor,
this.elevation,
this.shadowColor,
this.surfaceTintColor,
this.indicatorColor,
this.indicatorShape,
this.labelTextStyle,
this.iconTheme,
this.labelBehavior,
this.overlayColor,
});
/// Overrides the default value of [NavigationBar.height].
final double? height;
/// Overrides the default value of [NavigationBar.backgroundColor].
final Color? backgroundColor;
/// Overrides the default value of [NavigationBar.elevation].
final double? elevation;
/// Overrides the default value of [NavigationBar.shadowColor].
final Color? shadowColor;
/// Overrides the default value of [NavigationBar.surfaceTintColor].
final Color? surfaceTintColor;
/// Overrides the default value of [NavigationBar]'s selection indicator.
final Color? indicatorColor;
/// Overrides the default shape of the [NavigationBar]'s selection indicator.
final ShapeBorder? indicatorShape;
/// The style to merge with the default text style for
/// [NavigationDestination] labels.
///
/// You can use this to specify a different style when the label is selected.
final MaterialStateProperty<TextStyle?>? labelTextStyle;
/// The theme to merge with the default icon theme for
/// [NavigationDestination] icons.
///
/// You can use this to specify a different icon theme when the icon is
/// selected.
final MaterialStateProperty<IconThemeData?>? iconTheme;
/// Overrides the default value of [NavigationBar.labelBehavior].
final NavigationDestinationLabelBehavior? labelBehavior;
/// Overrides the default value of [NavigationBar.overlayColor].
final MaterialStateProperty<Color?>? overlayColor;
/// Creates a copy of this object with the given fields replaced with the
/// new values.
NavigationBarThemeData copyWith({
double? height,
Color? backgroundColor,
double? elevation,
Color? shadowColor,
Color? surfaceTintColor,
Color? indicatorColor,
ShapeBorder? indicatorShape,
MaterialStateProperty<TextStyle?>? labelTextStyle,
MaterialStateProperty<IconThemeData?>? iconTheme,
NavigationDestinationLabelBehavior? labelBehavior,
MaterialStateProperty<Color?>? overlayColor,
}) {
return NavigationBarThemeData(
height: height ?? this.height,
backgroundColor: backgroundColor ?? this.backgroundColor,
elevation: elevation ?? this.elevation,
shadowColor: shadowColor ?? this.shadowColor,
surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor,
indicatorColor: indicatorColor ?? this.indicatorColor,
indicatorShape: indicatorShape ?? this.indicatorShape,
labelTextStyle: labelTextStyle ?? this.labelTextStyle,
iconTheme: iconTheme ?? this.iconTheme,
labelBehavior: labelBehavior ?? this.labelBehavior,
overlayColor: overlayColor ?? this.overlayColor,
);
}
/// Linearly interpolate between two navigation rail themes.
///
/// If both arguments are null then null is returned.
///
/// {@macro dart.ui.shadow.lerp}
static NavigationBarThemeData? lerp(NavigationBarThemeData? a, NavigationBarThemeData? b, double t) {
if (identical(a, b)) {
return a;
}
return NavigationBarThemeData(
height: lerpDouble(a?.height, b?.height, t),
backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t),
elevation: lerpDouble(a?.elevation, b?.elevation, t),
shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t),
surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t),
indicatorColor: Color.lerp(a?.indicatorColor, b?.indicatorColor, t),
indicatorShape: ShapeBorder.lerp(a?.indicatorShape, b?.indicatorShape, t),
labelTextStyle: MaterialStateProperty.lerp<TextStyle?>(a?.labelTextStyle, b?.labelTextStyle, t, TextStyle.lerp),
iconTheme: MaterialStateProperty.lerp<IconThemeData?>(a?.iconTheme, b?.iconTheme, t, IconThemeData.lerp),
labelBehavior: t < 0.5 ? a?.labelBehavior : b?.labelBehavior,
overlayColor: MaterialStateProperty.lerp<Color?>(a?.overlayColor, b?.overlayColor, t, Color.lerp),
);
}
@override
int get hashCode => Object.hash(
height,
backgroundColor,
elevation,
shadowColor,
surfaceTintColor,
indicatorColor,
indicatorShape,
labelTextStyle,
iconTheme,
labelBehavior,
overlayColor,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is NavigationBarThemeData
&& other.height == height
&& other.backgroundColor == backgroundColor
&& other.elevation == elevation
&& other.shadowColor == shadowColor
&& other.surfaceTintColor == surfaceTintColor
&& other.indicatorColor == indicatorColor
&& other.indicatorShape == indicatorShape
&& other.labelTextStyle == labelTextStyle
&& other.iconTheme == iconTheme
&& other.labelBehavior == labelBehavior
&& other.overlayColor == overlayColor;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty('height', height, defaultValue: null));
properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null));
properties.add(DoubleProperty('elevation', elevation, defaultValue: null));
properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null));
properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null));
properties.add(ColorProperty('indicatorColor', indicatorColor, defaultValue: null));
properties.add(DiagnosticsProperty<ShapeBorder>('indicatorShape', indicatorShape, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<TextStyle?>>('labelTextStyle', labelTextStyle, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<IconThemeData?>>('iconTheme', iconTheme, defaultValue: null));
properties.add(DiagnosticsProperty<NavigationDestinationLabelBehavior>('labelBehavior', labelBehavior, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('overlayColor', overlayColor, defaultValue: null));
}
}
/// An inherited widget that defines visual properties for [NavigationBar]s and
/// [NavigationDestination]s in this widget's subtree.
///
/// Values specified here are used for [NavigationBar] properties that are not
/// given an explicit non-null value.
///
/// See also:
///
/// * [ThemeData.navigationBarTheme], which describes the
/// [NavigationBarThemeData] in the overall theme for the application.
class NavigationBarTheme extends InheritedTheme {
/// Creates a navigation rail theme that controls the
/// [NavigationBarThemeData] properties for a [NavigationBar].
const NavigationBarTheme({
super.key,
required this.data,
required super.child,
});
/// Specifies the background color, label text style, icon theme, and label
/// type values for descendant [NavigationBar] widgets.
final NavigationBarThemeData data;
/// The closest instance of this class that encloses the given context.
///
/// If there is no enclosing [NavigationBarTheme] widget, then
/// [ThemeData.navigationBarTheme] is used.
///
/// Typical usage is as follows:
///
/// ```dart
/// NavigationBarThemeData theme = NavigationBarTheme.of(context);
/// ```
static NavigationBarThemeData of(BuildContext context) {
final NavigationBarTheme? navigationBarTheme = context.dependOnInheritedWidgetOfExactType<NavigationBarTheme>();
return navigationBarTheme?.data ?? Theme.of(context).navigationBarTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return NavigationBarTheme(data: data, child: child);
}
@override
bool updateShouldNotify(NavigationBarTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/navigation_bar_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/navigation_bar_theme.dart",
"repo_id": "flutter",
"token_count": 2949
} | 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/widgets.dart';
import 'list_tile.dart';
import 'list_tile_theme.dart';
import 'material_state.dart';
import 'radio.dart';
import 'radio_theme.dart';
import 'theme.dart';
import 'theme_data.dart';
// Examples can assume:
// void setState(VoidCallback fn) { }
// enum Meridiem { am, pm }
// enum SingingCharacter { lafayette }
// late SingingCharacter? _character;
enum _RadioType { material, adaptive }
/// A [ListTile] with a [Radio]. In other words, a radio button with a label.
///
/// The entire list tile is interactive: tapping anywhere in the tile selects
/// the radio button.
///
/// The [value], [groupValue], [onChanged], and [activeColor] properties of this
/// widget are identical to the similarly-named properties on the [Radio]
/// widget. The type parameter `T` serves the same purpose as that of the
/// [Radio] class' type parameter.
///
/// The [title], [subtitle], [isThreeLine], and [dense] properties are like
/// those of the same name on [ListTile].
///
/// The [selected] property on this widget is similar to the [ListTile.selected]
/// property. The [fillColor] in the selected state is used for the selected item's
/// text color. If it is null, the [activeColor] is used.
///
/// This widget does not coordinate the [selected] state and the
/// [checked] state; to have the list tile appear selected when the
/// radio button is the selected radio button, set [selected] to true
/// when [value] matches [groupValue].
///
/// The radio button is shown on the left by default in left-to-right languages
/// (i.e. the leading edge). This can be changed using [controlAffinity]. The
/// [secondary] widget is placed on the opposite side. This maps to the
/// [ListTile.leading] and [ListTile.trailing] properties of [ListTile].
///
/// This widget requires a [Material] widget ancestor in the tree to paint
/// itself on, which is typically provided by the app's [Scaffold].
/// The [tileColor], and [selectedTileColor] are not painted by the
/// [RadioListTile] itself but by the [Material] widget ancestor. In this
/// case, one can wrap a [Material] widget around the [RadioListTile], e.g.:
///
/// {@tool snippet}
/// ```dart
/// ColoredBox(
/// color: Colors.green,
/// child: Material(
/// child: RadioListTile<Meridiem>(
/// tileColor: Colors.red,
/// title: const Text('AM'),
/// groupValue: Meridiem.am,
/// value: Meridiem.am,
/// onChanged:(Meridiem? value) { },
/// ),
/// ),
/// )
/// ```
/// {@end-tool}
///
/// ## Performance considerations when wrapping [RadioListTile] with [Material]
///
/// Wrapping a large number of [RadioListTile]s individually with [Material]s
/// is expensive. Consider only wrapping the [RadioListTile]s that require it
/// or include a common [Material] ancestor where possible.
///
/// To show the [RadioListTile] as disabled, pass null as the [onChanged]
/// callback.
///
/// {@tool dartpad}
/// 
///
/// This widget shows a pair of radio buttons that control the `_character`
/// field. The field is of the type `SingingCharacter`, an enum.
///
/// ** See code in examples/api/lib/material/radio_list_tile/radio_list_tile.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample demonstrates how [RadioListTile] positions the radio widget
/// relative to the text in different configurations.
///
/// ** See code in examples/api/lib/material/radio_list_tile/radio_list_tile.1.dart **
/// {@end-tool}
///
/// ## Semantics in RadioListTile
///
/// Since the entirety of the RadioListTile is interactive, it should represent
/// itself as a single interactive entity.
///
/// To do so, a RadioListTile widget wraps its children with a [MergeSemantics]
/// widget. [MergeSemantics] will attempt to merge its descendant [Semantics]
/// nodes into one node in the semantics tree. Therefore, RadioListTile will
/// throw an error if any of its children requires its own [Semantics] node.
///
/// For example, you cannot nest a [RichText] widget as a descendant of
/// RadioListTile. [RichText] has an embedded gesture recognizer that
/// requires its own [Semantics] node, which directly conflicts with
/// RadioListTile's desire to merge all its descendants' semantic nodes
/// into one. Therefore, it may be necessary to create a custom radio tile
/// widget to accommodate similar use cases.
///
/// {@tool dartpad}
/// 
///
/// Here is an example of a custom labeled radio widget, called
/// LinkedLabelRadio, that includes an interactive [RichText] widget that
/// handles tap gestures.
///
/// ** See code in examples/api/lib/material/radio_list_tile/custom_labeled_radio.0.dart **
/// {@end-tool}
///
/// ## RadioListTile isn't exactly what I want
///
/// If the way RadioListTile pads and positions its elements isn't quite what
/// you're looking for, you can create custom labeled radio widgets by
/// combining [Radio] with other widgets, such as [Text], [Padding] and
/// [InkWell].
///
/// {@tool dartpad}
/// 
///
/// Here is an example of a custom LabeledRadio widget, but you can easily
/// make your own configurable widget.
///
/// ** See code in examples/api/lib/material/radio_list_tile/custom_labeled_radio.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ListTileTheme], which can be used to affect the style of list tiles,
/// including radio list tiles.
/// * [CheckboxListTile], a similar widget for checkboxes.
/// * [SwitchListTile], a similar widget for switches.
/// * [ListTile] and [Radio], the widgets from which this widget is made.
class RadioListTile<T> extends StatelessWidget {
/// Creates a combination of a list tile and a radio button.
///
/// The radio tile itself does not maintain any state. Instead, when the radio
/// button is selected, the widget calls the [onChanged] callback. Most
/// widgets that use a radio button will listen for the [onChanged] callback
/// and rebuild the radio tile with a new [groupValue] to update the visual
/// appearance of the radio button.
///
/// The following arguments are required:
///
/// * [value] and [groupValue] together determine whether the radio button is
/// selected.
/// * [onChanged] is called when the user selects this radio button.
const RadioListTile({
super.key,
required this.value,
required this.groupValue,
required this.onChanged,
this.mouseCursor,
this.toggleable = false,
this.activeColor,
this.fillColor,
this.hoverColor,
this.overlayColor,
this.splashRadius,
this.materialTapTargetSize,
this.title,
this.subtitle,
this.isThreeLine = false,
this.dense,
this.secondary,
this.selected = false,
this.controlAffinity = ListTileControlAffinity.platform,
this.autofocus = false,
this.contentPadding,
this.shape,
this.tileColor,
this.selectedTileColor,
this.visualDensity,
this.focusNode,
this.onFocusChange,
this.enableFeedback,
}) : _radioType = _RadioType.material,
useCupertinoCheckmarkStyle = false,
assert(!isThreeLine || subtitle != null);
/// Creates a combination of a list tile and a platform adaptive radio.
///
/// The checkbox uses [Radio.adaptive] to show a [CupertinoRadio] for
/// iOS platforms, or [Radio] for all others.
///
/// All other properties are the same as [RadioListTile].
const RadioListTile.adaptive({
super.key,
required this.value,
required this.groupValue,
required this.onChanged,
this.mouseCursor,
this.toggleable = false,
this.activeColor,
this.fillColor,
this.hoverColor,
this.overlayColor,
this.splashRadius,
this.materialTapTargetSize,
this.title,
this.subtitle,
this.isThreeLine = false,
this.dense,
this.secondary,
this.selected = false,
this.controlAffinity = ListTileControlAffinity.platform,
this.autofocus = false,
this.contentPadding,
this.shape,
this.tileColor,
this.selectedTileColor,
this.visualDensity,
this.focusNode,
this.onFocusChange,
this.enableFeedback,
this.useCupertinoCheckmarkStyle = false,
}) : _radioType = _RadioType.adaptive,
assert(!isThreeLine || subtitle != null);
/// The value represented by this radio button.
final T value;
/// The currently selected value for this group of radio buttons.
///
/// This radio button is considered selected if its [value] matches the
/// [groupValue].
final T? groupValue;
/// Called when the user selects this radio button.
///
/// The radio button passes [value] as a parameter to this callback. The radio
/// button does not actually change state until the parent widget rebuilds the
/// radio tile with the new [groupValue].
///
/// If null, the radio button will be displayed as disabled.
///
/// The provided callback will not be invoked if this radio button is already
/// selected.
///
/// The callback provided to [onChanged] should update the state of the parent
/// [StatefulWidget] using the [State.setState] method, so that the parent
/// gets rebuilt; for example:
///
/// ```dart
/// RadioListTile<SingingCharacter>(
/// title: const Text('Lafayette'),
/// value: SingingCharacter.lafayette,
/// groupValue: _character,
/// onChanged: (SingingCharacter? newValue) {
/// setState(() {
/// _character = newValue;
/// });
/// },
/// )
/// ```
final ValueChanged<T?>? onChanged;
/// The cursor for a mouse pointer when it enters or is hovering over the
/// widget.
///
/// If [mouseCursor] is a [MaterialStateProperty<MouseCursor>],
/// [MaterialStateProperty.resolve] is used for the following [MaterialState]s:
///
/// * [MaterialState.selected].
/// * [MaterialState.hovered].
/// * [MaterialState.disabled].
///
/// If null, then the value of [RadioThemeData.mouseCursor] is used.
/// If that is also null, then [MaterialStateMouseCursor.clickable] is used.
final MouseCursor? mouseCursor;
/// Set to true if this radio list tile is allowed to be returned to an
/// indeterminate state by selecting it again when selected.
///
/// To indicate returning to an indeterminate state, [onChanged] will be
/// called with null.
///
/// If true, [onChanged] can be called with [value] when selected while
/// [groupValue] != [value], or with null when selected again while
/// [groupValue] == [value].
///
/// If false, [onChanged] will be called with [value] when it is selected
/// while [groupValue] != [value], and only by selecting another radio button
/// in the group (i.e. changing the value of [groupValue]) can this radio
/// list tile be unselected.
///
/// The default is false.
///
/// {@tool dartpad}
/// This example shows how to enable deselecting a radio button by setting the
/// [toggleable] attribute.
///
/// ** See code in examples/api/lib/material/radio_list_tile/radio_list_tile.toggleable.0.dart **
/// {@end-tool}
final bool toggleable;
/// The color to use when this radio button is selected.
///
/// Defaults to [ColorScheme.secondary] of the current [Theme].
final Color? activeColor;
/// The color that fills the radio button.
///
/// Resolves in the following states:
/// * [MaterialState.selected].
/// * [MaterialState.hovered].
/// * [MaterialState.disabled].
///
/// If null, then the value of [activeColor] is used in the selected state. If
/// that is also null, then the value of [RadioThemeData.fillColor] is used.
/// If that is also null, then the default value is used.
final MaterialStateProperty<Color?>? fillColor;
/// {@macro flutter.material.radio.materialTapTargetSize}
///
/// Defaults to [MaterialTapTargetSize.shrinkWrap].
final MaterialTapTargetSize? materialTapTargetSize;
/// {@macro flutter.material.radio.hoverColor}
final Color? hoverColor;
/// The color for the radio's [Material].
///
/// Resolves in the following states:
/// * [MaterialState.pressed].
/// * [MaterialState.selected].
/// * [MaterialState.hovered].
///
/// If null, then the value of [activeColor] with alpha [kRadialReactionAlpha]
/// and [hoverColor] is used in the pressed and hovered state. If that is also
/// null, the value of [SwitchThemeData.overlayColor] is used. If that is
/// also null, then the default value is used in the pressed and hovered state.
final MaterialStateProperty<Color?>? overlayColor;
/// {@macro flutter.material.radio.splashRadius}
///
/// If null, then the value of [RadioThemeData.splashRadius] is used. If that
/// is also null, then [kRadialReactionRadius] is used.
final double? splashRadius;
/// The primary content of the list tile.
///
/// Typically a [Text] widget.
final Widget? title;
/// Additional content displayed below the title.
///
/// Typically a [Text] widget.
final Widget? subtitle;
/// A widget to display on the opposite side of the tile from the radio button.
///
/// Typically an [Icon] widget.
final Widget? secondary;
/// Whether this list tile is intended to display three lines of text.
///
/// If false, the list tile is treated as having one line if the subtitle is
/// null and treated as having two lines if the subtitle is non-null.
final bool isThreeLine;
/// Whether this list tile is part of a vertically dense list.
///
/// If this property is null then its value is based on [ListTileThemeData.dense].
final bool? dense;
/// Whether to render icons and text in the [activeColor].
///
/// No effort is made to automatically coordinate the [selected] state and the
/// [checked] state. To have the list tile appear selected when the radio
/// button is the selected radio button, set [selected] to true when [value]
/// matches [groupValue].
///
/// Normally, this property is left to its default value, false.
final bool selected;
/// Where to place the control relative to the text.
final ListTileControlAffinity controlAffinity;
/// {@macro flutter.widgets.Focus.autofocus}
final bool autofocus;
/// Defines the insets surrounding the contents of the tile.
///
/// Insets the [Radio], [title], [subtitle], and [secondary] widgets
/// in [RadioListTile].
///
/// When null, `EdgeInsets.symmetric(horizontal: 16.0)` is used.
final EdgeInsetsGeometry? contentPadding;
/// Whether this radio button is checked.
///
/// To control this value, set [value] and [groupValue] appropriately.
bool get checked => value == groupValue;
/// If specified, [shape] defines the shape of the [RadioListTile]'s [InkWell] border.
final ShapeBorder? shape;
/// If specified, defines the background color for `RadioListTile` when
/// [RadioListTile.selected] is false.
final Color? tileColor;
/// If non-null, defines the background color when [RadioListTile.selected] is true.
final Color? selectedTileColor;
/// Defines how compact the list tile's layout will be.
///
/// {@macro flutter.material.themedata.visualDensity}
final VisualDensity? visualDensity;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// {@macro flutter.material.inkwell.onFocusChange}
final ValueChanged<bool>? onFocusChange;
/// {@macro flutter.material.ListTile.enableFeedback}
///
/// See also:
///
/// * [Feedback] for providing platform-specific feedback to certain actions.
final bool? enableFeedback;
final _RadioType _radioType;
/// Whether to use the checkbox style for the [CupertinoRadio] control.
///
/// Only usable under the [RadioListTile.adaptive] constructor. If set to
/// true, on Apple platforms the radio button will appear as an iOS styled
/// checkmark. Controls the [CupertinoRadio] through
/// [CupertinoRadio.useCheckmarkStyle].
///
/// Defaults to false.
final bool useCupertinoCheckmarkStyle;
@override
Widget build(BuildContext context) {
final Widget control;
switch (_radioType) {
case _RadioType.material:
control = ExcludeFocus(
child: Radio<T>(
value: value,
groupValue: groupValue,
onChanged: onChanged,
toggleable: toggleable,
activeColor: activeColor,
materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap,
autofocus: autofocus,
fillColor: fillColor,
mouseCursor: mouseCursor,
hoverColor: hoverColor,
overlayColor: overlayColor,
splashRadius: splashRadius,
),
);
case _RadioType.adaptive:
control = ExcludeFocus(
child: Radio<T>.adaptive(
value: value,
groupValue: groupValue,
onChanged: onChanged,
toggleable: toggleable,
activeColor: activeColor,
materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap,
autofocus: autofocus,
fillColor: fillColor,
mouseCursor: mouseCursor,
hoverColor: hoverColor,
overlayColor: overlayColor,
splashRadius: splashRadius,
useCupertinoCheckmarkStyle: useCupertinoCheckmarkStyle,
),
);
}
Widget? leading, trailing;
(leading, trailing) = switch (controlAffinity) {
ListTileControlAffinity.leading || ListTileControlAffinity.platform => (control, secondary),
ListTileControlAffinity.trailing => (secondary, control),
};
final ThemeData theme = Theme.of(context);
final RadioThemeData radioThemeData = RadioTheme.of(context);
final Set<MaterialState> states = <MaterialState>{
if (selected) MaterialState.selected,
};
final Color effectiveActiveColor = activeColor
?? radioThemeData.fillColor?.resolve(states)
?? theme.colorScheme.secondary;
return MergeSemantics(
child: ListTile(
selectedColor: effectiveActiveColor,
leading: leading,
title: title,
subtitle: subtitle,
trailing: trailing,
isThreeLine: isThreeLine,
dense: dense,
enabled: onChanged != null,
shape: shape,
tileColor: tileColor,
selectedTileColor: selectedTileColor,
onTap: onChanged != null ? () {
if (toggleable && checked) {
onChanged!(null);
return;
}
if (!checked) {
onChanged!(value);
}
} : null,
selected: selected,
autofocus: autofocus,
contentPadding: contentPadding,
visualDensity: visualDensity,
focusNode: focusNode,
onFocusChange: onFocusChange,
enableFeedback: enableFeedback,
),
);
}
}
| flutter/packages/flutter/lib/src/material/radio_list_tile.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/radio_list_tile.dart",
"repo_id": "flutter",
"token_count": 6160
} | 629 |
#version 320 es
// 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.
precision highp float;
#include <flutter/runtime_effect.glsl>
// TODO(antrob): Put these in a more logical order (e.g. separate consts vs varying, etc)
layout(location = 0) uniform vec4 u_color;
// u_alpha, u_sparkle_alpha, u_blur, u_radius_scale
layout(location = 1) uniform vec4 u_composite_1;
layout(location = 2) uniform vec2 u_center;
layout(location = 3) uniform float u_max_radius;
layout(location = 4) uniform vec2 u_resolution_scale;
layout(location = 5) uniform vec2 u_noise_scale;
layout(location = 6) uniform float u_noise_phase;
layout(location = 7) uniform vec2 u_circle1;
layout(location = 8) uniform vec2 u_circle2;
layout(location = 9) uniform vec2 u_circle3;
layout(location = 10) uniform vec2 u_rotation1;
layout(location = 11) uniform vec2 u_rotation2;
layout(location = 12) uniform vec2 u_rotation3;
layout(location = 0) out vec4 fragColor;
const float PI = 3.1415926535897932384626;
const float PI_ROTATE_RIGHT = PI * 0.0078125;
const float PI_ROTATE_LEFT = PI * -0.0078125;
const float ONE_THIRD = 1./3.;
const vec2 TURBULENCE_SCALE = vec2(0.8);
float u_alpha = u_composite_1.x;
float u_sparkle_alpha = u_composite_1.y;
float u_blur = u_composite_1.z;
float u_radius_scale = u_composite_1.w;
float triangle_noise(highp vec2 n) {
n = fract(n * vec2(5.3987, 5.4421));
n += dot(n.yx, n.xy + vec2(21.5351, 14.3137));
float xy = n.x * n.y;
return fract(xy * 95.4307) + fract(xy * 75.04961) - 1.0;
}
float threshold(float v, float l, float h) {
return step(l, v) * (1.0 - step(h, v));
}
mat2 rotate2d(vec2 rad){
return mat2(rad.x, -rad.y, rad.y, rad.x);
}
float soft_circle(vec2 uv, vec2 xy, float radius, float blur) {
float blur_half = blur * 0.5;
float d = distance(uv, xy);
return 1.0 - smoothstep(1.0 - blur_half, 1.0 + blur_half, d / radius);
}
float soft_ring(vec2 uv, vec2 xy, float radius, float thickness, float blur) {
float circle_outer = soft_circle(uv, xy, radius + thickness, blur);
float circle_inner = soft_circle(uv, xy, max(radius - thickness, 0.0), blur);
return clamp(circle_outer - circle_inner, 0.0, 1.0);
}
float circle_grid(vec2 resolution, vec2 p, vec2 xy, vec2 rotation, float cell_diameter) {
p = rotate2d(rotation) * (xy - p) + xy;
p = mod(p, cell_diameter) / resolution;
float cell_uv = cell_diameter / resolution.y * 0.5;
float r = 0.65 * cell_uv;
return soft_circle(p, vec2(cell_uv), r, r * 50.0);
}
float sparkle(vec2 uv, float t) {
float n = triangle_noise(uv);
float s = threshold(n, 0.0, 0.05);
s += threshold(n + sin(PI * (t + 0.35)), 0.1, 0.15);
s += threshold(n + sin(PI * (t + 0.7)), 0.2, 0.25);
s += threshold(n + sin(PI * (t + 1.05)), 0.3, 0.35);
return clamp(s, 0.0, 1.0) * 0.55;
}
float turbulence(vec2 uv) {
vec2 uv_scale = uv * TURBULENCE_SCALE;
float g1 = circle_grid(TURBULENCE_SCALE, uv_scale, u_circle1, u_rotation1, 0.17);
float g2 = circle_grid(TURBULENCE_SCALE, uv_scale, u_circle2, u_rotation2, 0.2);
float g3 = circle_grid(TURBULENCE_SCALE, uv_scale, u_circle3, u_rotation3, 0.275);
float v = (g1 * g1 + g2 - g3) * 0.5;
return clamp(0.45 + 0.8 * v, 0.0, 1.0);
}
void main() {
vec2 p = FlutterFragCoord();
vec2 uv = p * u_resolution_scale;
vec2 density_uv = uv - mod(p, u_noise_scale);
float radius = u_max_radius * u_radius_scale;
float turbulence = turbulence(uv);
float ring = soft_ring(p, u_center, radius, 0.05 * u_max_radius, u_blur);
float sparkle = sparkle(density_uv, u_noise_phase) * ring * turbulence * u_sparkle_alpha;
float wave_alpha = soft_circle(p, u_center, radius, u_blur) * u_alpha * u_color.a;
vec4 wave_color = vec4(u_color.rgb * wave_alpha, wave_alpha);
fragColor = mix(wave_color, vec4(1.0), sparkle);
}
| flutter/packages/flutter/lib/src/material/shaders/ink_sparkle.frag/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/shaders/ink_sparkle.frag",
"repo_id": "flutter",
"token_count": 1568
} | 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:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'button_style_button.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'ink_ripple.dart';
import 'ink_well.dart';
import 'material_state.dart';
import 'text_button_theme.dart';
import 'theme.dart';
import 'theme_data.dart';
/// A Material Design "Text Button".
///
/// Use text buttons on toolbars, in dialogs, or inline with other
/// content but offset from that content with padding so that the
/// button's presence is obvious. Text buttons do not have visible
/// borders and must therefore rely on their position relative to
/// other content for context. In dialogs and cards, they should be
/// grouped together in one of the bottom corners. Avoid using text
/// buttons where they would blend in with other content, for example
/// in the middle of lists.
///
/// A text button is a label [child] displayed on a (zero elevation)
/// [Material] widget. The label's [Text] and [Icon] widgets are
/// displayed in the [style]'s [ButtonStyle.foregroundColor]. The
/// button reacts to touches by filling with the [style]'s
/// [ButtonStyle.backgroundColor].
///
/// The text button's default style is defined by [defaultStyleOf].
/// The style of this text button can be overridden with its [style]
/// parameter. The style of all text buttons in a subtree can be
/// overridden with the [TextButtonTheme] and the style of all of the
/// text buttons in an app can be overridden with the [Theme]'s
/// [ThemeData.textButtonTheme] property.
///
/// The static [styleFrom] method is a convenient way to create a
/// text button [ButtonStyle] from simple values.
///
/// If the [onPressed] and [onLongPress] callbacks are null, then this
/// button will be disabled, it will not react to touch.
///
/// {@tool dartpad}
/// This sample shows various ways to configure TextButtons, from the
/// simplest default appearance to versions that don't resemble
/// Material Design at all.
///
/// ** See code in examples/api/lib/material/text_button/text_button.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample demonstrates using the [statesController] parameter to create a button
/// that adds support for [MaterialState.selected].
///
/// ** See code in examples/api/lib/material/text_button/text_button.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ElevatedButton], a filled button whose material elevates when pressed.
/// * [FilledButton], a filled button that doesn't elevate when pressed.
/// * [FilledButton.tonal], a filled button variant that uses a secondary fill color.
/// * [OutlinedButton], a button with an outlined border and no fill color.
/// * <https://material.io/design/components/buttons.html>
/// * <https://m3.material.io/components/buttons>
class TextButton extends ButtonStyleButton {
/// Create a [TextButton].
const TextButton({
super.key,
required super.onPressed,
super.onLongPress,
super.onHover,
super.onFocusChange,
super.style,
super.focusNode,
super.autofocus = false,
super.clipBehavior,
super.statesController,
super.isSemanticButton,
required Widget super.child,
super.iconAlignment,
});
/// Create a text button from a pair of widgets that serve as the button's
/// [icon] and [label].
///
/// The icon and label are arranged in a row and padded by 8 logical pixels
/// at the ends, with an 8 pixel gap in between.
///
/// If [icon] is null, will create a [TextButton] instead.
///
/// {@macro flutter.material.ButtonStyleButton.iconAlignment}
///
factory TextButton.icon({
Key? key,
required VoidCallback? onPressed,
VoidCallback? onLongPress,
ValueChanged<bool>? onHover,
ValueChanged<bool>? onFocusChange,
ButtonStyle? style,
FocusNode? focusNode,
bool? autofocus,
Clip? clipBehavior,
MaterialStatesController? statesController,
Widget? icon,
required Widget label,
IconAlignment iconAlignment = IconAlignment.start,
}) {
if (icon == null) {
return TextButton(
key: key,
onPressed: onPressed,
onLongPress: onLongPress,
onHover: onHover,
onFocusChange: onFocusChange,
style: style,
focusNode: focusNode,
autofocus: autofocus ?? false,
clipBehavior: clipBehavior ?? Clip.none,
statesController: statesController,
child: label,
);
}
return _TextButtonWithIcon( key: key,
onPressed: onPressed,
onLongPress: onLongPress,
onHover: onHover,
onFocusChange: onFocusChange,
style: style,
focusNode: focusNode,
autofocus: autofocus ?? false,
clipBehavior: clipBehavior ?? Clip.none,
statesController: statesController,
icon: icon,
label: label,
iconAlignment: iconAlignment,
);
}
/// A static convenience method that constructs a text button
/// [ButtonStyle] given simple values.
///
/// The [foregroundColor] and [disabledForegroundColor] colors are used
/// to create a [MaterialStateProperty] [ButtonStyle.foregroundColor], and
/// a derived [ButtonStyle.overlayColor] if [overlayColor] isn't specified.
///
/// The [backgroundColor] and [disabledBackgroundColor] colors are
/// used to create a [MaterialStateProperty] [ButtonStyle.backgroundColor].
///
/// Similarly, the [enabledMouseCursor] and [disabledMouseCursor]
/// parameters are used to construct [ButtonStyle.mouseCursor] and
/// [iconColor], [disabledIconColor] are used to construct
/// [ButtonStyle.iconColor].
///
/// If [overlayColor] is specified and its value is [Colors.transparent]
/// then the pressed/focused/hovered highlights are effectively defeated.
/// Otherwise a [MaterialStateProperty] with the same opacities as the
/// default is created.
///
/// All of the other parameters are either used directly or used to
/// create a [MaterialStateProperty] with a single value for all
/// states.
///
/// All parameters default to null. By default this method returns
/// a [ButtonStyle] that doesn't override anything.
///
/// For example, to override the default text and icon colors for a
/// [TextButton], as well as its overlay color, with all of the
/// standard opacity adjustments for the pressed, focused, and
/// hovered states, one could write:
///
/// ```dart
/// TextButton(
/// style: TextButton.styleFrom(foregroundColor: Colors.green),
/// child: const Text('Give Kate a mix tape'),
/// onPressed: () {
/// // ...
/// },
/// ),
/// ```
static ButtonStyle styleFrom({
Color? foregroundColor,
Color? backgroundColor,
Color? disabledForegroundColor,
Color? disabledBackgroundColor,
Color? shadowColor,
Color? surfaceTintColor,
Color? iconColor,
Color? disabledIconColor,
Color? overlayColor,
double? elevation,
TextStyle? textStyle,
EdgeInsetsGeometry? padding,
Size? minimumSize,
Size? fixedSize,
Size? maximumSize,
BorderSide? side,
OutlinedBorder? shape,
MouseCursor? enabledMouseCursor,
MouseCursor? disabledMouseCursor,
VisualDensity? visualDensity,
MaterialTapTargetSize? tapTargetSize,
Duration? animationDuration,
bool? enableFeedback,
AlignmentGeometry? alignment,
InteractiveInkFeatureFactory? splashFactory,
ButtonLayerBuilder? backgroundBuilder,
ButtonLayerBuilder? foregroundBuilder,
}) {
final MaterialStateProperty<Color?>? foregroundColorProp = switch ((foregroundColor, disabledForegroundColor)) {
(null, null) => null,
(_, _) => _TextButtonDefaultColor(foregroundColor, disabledForegroundColor),
};
final MaterialStateProperty<Color?>? backgroundColorProp = switch ((backgroundColor, disabledBackgroundColor)) {
(null, null) => null,
(_, null) => MaterialStatePropertyAll<Color?>(backgroundColor),
(_, _) => _TextButtonDefaultColor(backgroundColor, disabledBackgroundColor),
};
final MaterialStateProperty<Color?>? iconColorProp = switch ((iconColor, disabledIconColor)) {
(null, null) => null,
(_, null) => MaterialStatePropertyAll<Color?>(iconColor),
(_, _) => _TextButtonDefaultColor(iconColor, disabledIconColor),
};
final MaterialStateProperty<Color?>? overlayColorProp = switch ((foregroundColor, overlayColor)) {
(null, null) => null,
(_, final Color overlayColor) when overlayColor.value == 0 => const MaterialStatePropertyAll<Color?>(Colors.transparent),
(_, _) => _TextButtonDefaultOverlay((overlayColor ?? foregroundColor)!),
};
final MaterialStateProperty<MouseCursor?> mouseCursor = _TextButtonDefaultMouseCursor(enabledMouseCursor, disabledMouseCursor);
return ButtonStyle(
textStyle: ButtonStyleButton.allOrNull<TextStyle>(textStyle),
foregroundColor: foregroundColorProp,
backgroundColor: backgroundColorProp,
overlayColor: overlayColorProp,
shadowColor: ButtonStyleButton.allOrNull<Color>(shadowColor),
surfaceTintColor: ButtonStyleButton.allOrNull<Color>(surfaceTintColor),
iconColor: iconColorProp,
elevation: ButtonStyleButton.allOrNull<double>(elevation),
padding: ButtonStyleButton.allOrNull<EdgeInsetsGeometry>(padding),
minimumSize: ButtonStyleButton.allOrNull<Size>(minimumSize),
fixedSize: ButtonStyleButton.allOrNull<Size>(fixedSize),
maximumSize: ButtonStyleButton.allOrNull<Size>(maximumSize),
side: ButtonStyleButton.allOrNull<BorderSide>(side),
shape: ButtonStyleButton.allOrNull<OutlinedBorder>(shape),
mouseCursor: mouseCursor,
visualDensity: visualDensity,
tapTargetSize: tapTargetSize,
animationDuration: animationDuration,
enableFeedback: enableFeedback,
alignment: alignment,
splashFactory: splashFactory,
backgroundBuilder: backgroundBuilder,
foregroundBuilder: foregroundBuilder,
);
}
/// Defines the button's default appearance.
///
/// {@template flutter.material.text_button.default_style_of}
/// The button [child]'s [Text] and [Icon] widgets are rendered with
/// the [ButtonStyle]'s foreground color. The button's [InkWell] adds
/// the style's overlay color when the button is focused, hovered
/// or pressed. The button's background color becomes its [Material]
/// color and is transparent by default.
///
/// All of the [ButtonStyle]'s defaults appear below.
///
/// In this list "Theme.foo" is shorthand for
/// `Theme.of(context).foo`. Color scheme values like
/// "onSurface(0.38)" are shorthand for
/// `onSurface.withOpacity(0.38)`. [MaterialStateProperty] valued
/// properties that are not followed by a sublist have the same
/// value for all states, otherwise the values are as specified for
/// each state and "others" means all other states.
///
/// The "default font size" below refers to the font size specified in the
/// [defaultStyleOf] method (or 14.0 if unspecified), scaled by the
/// `MediaQuery.textScalerOf(context).scale` method. And the names of the
/// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been abbreviated
/// for readability.
///
/// The color of the [ButtonStyle.textStyle] is not used, the
/// [ButtonStyle.foregroundColor] color is used instead.
/// {@endtemplate}
///
/// ## Material 2 defaults
///
/// * `textStyle` - Theme.textTheme.button
/// * `backgroundColor` - transparent
/// * `foregroundColor`
/// * disabled - Theme.colorScheme.onSurface(0.38)
/// * others - Theme.colorScheme.primary
/// * `overlayColor`
/// * hovered - Theme.colorScheme.primary(0.08)
/// * focused or pressed - Theme.colorScheme.primary(0.12)
/// * `shadowColor` - Theme.shadowColor
/// * `elevation` - 0
/// * `padding`
/// * `default font size <= 14` - (horizontal(12), vertical(8))
/// * `14 < default font size <= 28` - lerp(all(8), horizontal(8))
/// * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4))
/// * `36 < default font size` - horizontal(4)
/// * `minimumSize` - Size(64, 36)
/// * `fixedSize` - null
/// * `maximumSize` - Size.infinite
/// * `side` - null
/// * `shape` - RoundedRectangleBorder(borderRadius: BorderRadius.circular(4))
/// * `mouseCursor`
/// * disabled - SystemMouseCursors.basic
/// * others - SystemMouseCursors.click
/// * `visualDensity` - theme.visualDensity
/// * `tapTargetSize` - theme.materialTapTargetSize
/// * `animationDuration` - kThemeChangeDuration
/// * `enableFeedback` - true
/// * `alignment` - Alignment.center
/// * `splashFactory` - InkRipple.splashFactory
///
/// The default padding values for the [TextButton.icon] factory are slightly different:
///
/// * `padding`
/// * `default font size <= 14` - all(8)
/// * `14 < default font size <= 28 `- lerp(all(8), horizontal(4))
/// * `28 < default font size` - horizontal(4)
///
/// The default value for `side`, which defines the appearance of the button's
/// outline, is null. That means that the outline is defined by the button
/// shape's [OutlinedBorder.side]. Typically the default value of an
/// [OutlinedBorder]'s side is [BorderSide.none], so an outline is not drawn.
///
/// ## Material 3 defaults
///
/// If [ThemeData.useMaterial3] is set to true the following defaults will
/// be used:
///
/// {@template flutter.material.text_button.material3_defaults}
/// * `textStyle` - Theme.textTheme.labelLarge
/// * `backgroundColor` - transparent
/// * `foregroundColor`
/// * disabled - Theme.colorScheme.onSurface(0.38)
/// * others - Theme.colorScheme.primary
/// * `overlayColor`
/// * hovered - Theme.colorScheme.primary(0.08)
/// * focused or pressed - Theme.colorScheme.primary(0.1)
/// * others - null
/// * `shadowColor` - Colors.transparent,
/// * `surfaceTintColor` - null
/// * `elevation` - 0
/// * `padding`
/// * `default font size <= 14` - lerp(horizontal(12), horizontal(4))
/// * `14 < default font size <= 28` - lerp(all(8), horizontal(8))
/// * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4))
/// * `36 < default font size` - horizontal(4)
/// * `minimumSize` - Size(64, 40)
/// * `fixedSize` - null
/// * `maximumSize` - Size.infinite
/// * `side` - null
/// * `shape` - StadiumBorder()
/// * `mouseCursor`
/// * disabled - SystemMouseCursors.basic
/// * others - SystemMouseCursors.click
/// * `visualDensity` - theme.visualDensity
/// * `tapTargetSize` - theme.materialTapTargetSize
/// * `animationDuration` - kThemeChangeDuration
/// * `enableFeedback` - true
/// * `alignment` - Alignment.center
/// * `splashFactory` - Theme.splashFactory
///
/// For the [TextButton.icon] factory, the end (generally the right) value of
/// [padding] is increased from 12 to 16.
/// {@endtemplate}
@override
ButtonStyle defaultStyleOf(BuildContext context) {
final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme;
return Theme.of(context).useMaterial3
? _TextButtonDefaultsM3(context)
: styleFrom(
foregroundColor: colorScheme.primary,
disabledForegroundColor: colorScheme.onSurface.withOpacity(0.38),
backgroundColor: Colors.transparent,
disabledBackgroundColor: Colors.transparent,
shadowColor: theme.shadowColor,
elevation: 0,
textStyle: theme.textTheme.labelLarge,
padding: _scaledPadding(context),
minimumSize: const Size(64, 36),
maximumSize: Size.infinite,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4))),
enabledMouseCursor: SystemMouseCursors.click,
disabledMouseCursor: SystemMouseCursors.basic,
visualDensity: theme.visualDensity,
tapTargetSize: theme.materialTapTargetSize,
animationDuration: kThemeChangeDuration,
enableFeedback: true,
alignment: Alignment.center,
splashFactory: InkRipple.splashFactory,
);
}
/// Returns the [TextButtonThemeData.style] of the closest
/// [TextButtonTheme] ancestor.
@override
ButtonStyle? themeStyleOf(BuildContext context) {
return TextButtonTheme.of(context).style;
}
}
EdgeInsetsGeometry _scaledPadding(BuildContext context) {
final ThemeData theme = Theme.of(context);
final double defaultFontSize = theme.textTheme.labelLarge?.fontSize ?? 14.0;
final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0;
return ButtonStyleButton.scaledPadding(
theme.useMaterial3 ? const EdgeInsets.symmetric(horizontal: 12, vertical: 8) : const EdgeInsets.all(8),
const EdgeInsets.symmetric(horizontal: 8),
const EdgeInsets.symmetric(horizontal: 4),
effectiveTextScale,
);
}
@immutable
class _TextButtonDefaultColor extends MaterialStateProperty<Color?> {
_TextButtonDefaultColor(this.color, this.disabled);
final Color? color;
final Color? disabled;
@override
Color? resolve(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return disabled;
}
return color;
}
@override
String toString() {
return '{disabled: $disabled, otherwise: $color}';
}
}
@immutable
class _TextButtonDefaultOverlay extends MaterialStateProperty<Color?> {
_TextButtonDefaultOverlay(this.primary);
final Color primary;
@override
Color? resolve(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return primary.withOpacity(0.1);
}
if (states.contains(MaterialState.hovered)) {
return primary.withOpacity(0.08);
}
if (states.contains(MaterialState.focused)) {
return primary.withOpacity(0.1);
}
return null;
}
@override
String toString() {
return '{hovered: ${primary.withOpacity(0.04)}, focused,pressed: ${primary.withOpacity(0.12)}, otherwise: null}';
}
}
@immutable
class _TextButtonDefaultMouseCursor extends MaterialStateProperty<MouseCursor?> with Diagnosticable {
_TextButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor);
final MouseCursor? enabledCursor;
final MouseCursor? disabledCursor;
@override
MouseCursor? resolve(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return disabledCursor;
}
return enabledCursor;
}
}
class _TextButtonWithIcon extends TextButton {
_TextButtonWithIcon({
super.key,
required super.onPressed,
super.onLongPress,
super.onHover,
super.onFocusChange,
super.style,
super.focusNode,
bool? autofocus,
super.clipBehavior,
super.statesController,
required Widget icon,
required Widget label,
super.iconAlignment,
}) : super(
autofocus: autofocus ?? false,
child: _TextButtonWithIconChild(
icon: icon,
label: label,
buttonStyle: style,
iconAlignment: iconAlignment,
),
);
@override
ButtonStyle defaultStyleOf(BuildContext context) {
final bool useMaterial3 = Theme.of(context).useMaterial3;
final ButtonStyle buttonStyle = super.defaultStyleOf(context);
final double defaultFontSize = buttonStyle.textStyle?.resolve(const <MaterialState>{})?.fontSize ?? 14.0;
final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0;
final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding(
useMaterial3 ? const EdgeInsetsDirectional.fromSTEB(12, 8, 16, 8) : const EdgeInsets.all(8),
const EdgeInsets.symmetric(horizontal: 4),
const EdgeInsets.symmetric(horizontal: 4),
effectiveTextScale,
);
return buttonStyle.copyWith(
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding),
);
}
}
class _TextButtonWithIconChild extends StatelessWidget {
const _TextButtonWithIconChild({
required this.label,
required this.icon,
required this.buttonStyle,
required this.iconAlignment,
});
final Widget label;
final Widget icon;
final ButtonStyle? buttonStyle;
final IconAlignment iconAlignment;
@override
Widget build(BuildContext context) {
final double defaultFontSize = buttonStyle?.textStyle?.resolve(const <MaterialState>{})?.fontSize ?? 14.0;
final double scale = clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0;
final double gap = lerpDouble(8, 4, scale)!;
return Row(
mainAxisSize: MainAxisSize.min,
children: iconAlignment == IconAlignment.start
? <Widget>[icon, SizedBox(width: gap), Flexible(child: label)]
: <Widget>[Flexible(child: label), SizedBox(width: gap), icon],
);
}
}
// BEGIN GENERATED TOKEN PROPERTIES - TextButton
// 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 _TextButtonDefaultsM3 extends ButtonStyle {
_TextButtonDefaultsM3(this.context)
: super(
animationDuration: kThemeChangeDuration,
enableFeedback: true,
alignment: Alignment.center,
);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
MaterialStateProperty<TextStyle?> get textStyle =>
MaterialStatePropertyAll<TextStyle?>(Theme.of(context).textTheme.labelLarge);
@override
MaterialStateProperty<Color?>? get backgroundColor =>
const MaterialStatePropertyAll<Color>(Colors.transparent);
@override
MaterialStateProperty<Color?>? get foregroundColor =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return _colors.onSurface.withOpacity(0.38);
}
return _colors.primary;
});
@override
MaterialStateProperty<Color?>? get overlayColor =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return _colors.primary.withOpacity(0.1);
}
if (states.contains(MaterialState.hovered)) {
return _colors.primary.withOpacity(0.08);
}
if (states.contains(MaterialState.focused)) {
return _colors.primary.withOpacity(0.1);
}
return null;
});
@override
MaterialStateProperty<Color>? get shadowColor =>
const MaterialStatePropertyAll<Color>(Colors.transparent);
@override
MaterialStateProperty<Color>? get surfaceTintColor =>
const MaterialStatePropertyAll<Color>(Colors.transparent);
@override
MaterialStateProperty<double>? get elevation =>
const MaterialStatePropertyAll<double>(0.0);
@override
MaterialStateProperty<EdgeInsetsGeometry>? get padding =>
MaterialStatePropertyAll<EdgeInsetsGeometry>(_scaledPadding(context));
@override
MaterialStateProperty<Size>? get minimumSize =>
const MaterialStatePropertyAll<Size>(Size(64.0, 40.0));
// No default fixedSize
@override
MaterialStateProperty<Size>? get maximumSize =>
const MaterialStatePropertyAll<Size>(Size.infinite);
// No default side
@override
MaterialStateProperty<OutlinedBorder>? get shape =>
const MaterialStatePropertyAll<OutlinedBorder>(StadiumBorder());
@override
MaterialStateProperty<MouseCursor?>? get mouseCursor =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return SystemMouseCursors.basic;
}
return SystemMouseCursors.click;
});
@override
VisualDensity? get visualDensity => Theme.of(context).visualDensity;
@override
MaterialTapTargetSize? get tapTargetSize => Theme.of(context).materialTapTargetSize;
@override
InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory;
}
// END GENERATED TOKEN PROPERTIES - TextButton
| flutter/packages/flutter/lib/src/material/text_button.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/text_button.dart",
"repo_id": "flutter",
"token_count": 8062
} | 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 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'constants.dart';
import 'material_state.dart';
// Duration of the animation that moves the toggle from one state to another.
const Duration _kToggleDuration = Duration(milliseconds: 200);
// Duration of the fade animation for the reaction when focus and hover occur.
const Duration _kReactionFadeDuration = Duration(milliseconds: 50);
/// A mixin for [StatefulWidget]s that implement material-themed toggleable
/// controls with toggle animations (e.g. [Switch]es, [Checkbox]es, and
/// [Radio]s).
///
/// The mixin implements the logic for toggling the control (e.g. when tapped)
/// and provides a series of animation controllers to transition the control
/// from one state to another. It does not have any opinion about the visual
/// representation of the toggleable widget. The visuals are defined by a
/// [CustomPainter] passed to the [buildToggleable]. [State] objects using this
/// mixin should call that method from their [build] method.
///
/// This mixin is used to implement the material components for [Switch],
/// [Checkbox], and [Radio] controls.
@optionalTypeArgs
mixin ToggleableStateMixin<S extends StatefulWidget> on TickerProviderStateMixin<S> {
/// Used by subclasses to manipulate the visual value of the control.
///
/// Some controls respond to user input by updating their visual value. For
/// example, the thumb of a switch moves from one position to another when
/// dragged. These controls manipulate this animation controller to update
/// their [position] and eventually trigger an [onChanged] callback when the
/// animation reaches either 0.0 or 1.0.
AnimationController get positionController => _positionController;
late AnimationController _positionController;
/// The visual value of the control.
///
/// When the control is inactive, the [value] is false and this animation has
/// the value 0.0. When the control is active, the value is either true or
/// tristate is true and the value is null. When the control is active the
/// animation has a value of 1.0. When the control is changing from inactive
/// to active (or vice versa), [value] is the target value and this animation
/// gradually updates from 0.0 to 1.0 (or vice versa).
CurvedAnimation get position => _position;
late CurvedAnimation _position;
/// Used by subclasses to control the radial reaction animation.
///
/// Some controls have a radial ink reaction to user input. This animation
/// controller can be used to start or stop these ink reactions.
///
/// To paint the actual radial reaction, [ToggleablePainter.paintRadialReaction]
/// may be used.
AnimationController get reactionController => _reactionController;
late AnimationController _reactionController;
/// The visual value of the radial reaction animation.
///
/// Some controls have a radial ink reaction to user input. This animation
/// controls the progress of these ink reactions.
///
/// To paint the actual radial reaction, [ToggleablePainter.paintRadialReaction]
/// may be used.
CurvedAnimation get reaction => _reaction;
late CurvedAnimation _reaction;
/// Controls the radial reaction's opacity animation for hover changes.
///
/// Some controls have a radial ink reaction to pointer hover. This animation
/// controls these ink reaction fade-ins and
/// fade-outs.
///
/// To paint the actual radial reaction, [ToggleablePainter.paintRadialReaction]
/// may be used.
CurvedAnimation get reactionHoverFade => _reactionHoverFade;
late CurvedAnimation _reactionHoverFade;
late AnimationController _reactionHoverFadeController;
/// Controls the radial reaction's opacity animation for focus changes.
///
/// Some controls have a radial ink reaction to focus. This animation
/// controls these ink reaction fade-ins and fade-outs.
///
/// To paint the actual radial reaction, [ToggleablePainter.paintRadialReaction]
/// may be used.
CurvedAnimation get reactionFocusFade => _reactionFocusFade;
late CurvedAnimation _reactionFocusFade;
late AnimationController _reactionFocusFadeController;
/// Whether [value] of this control can be changed by user interaction.
///
/// The control is considered interactive if the [onChanged] callback is
/// non-null. If the callback is null, then the control is disabled, and
/// non-interactive. A disabled checkbox, for example, is displayed using a
/// grey color and its value cannot be changed.
bool get isInteractive => onChanged != null;
late final Map<Type, Action<Intent>> _actionMap = <Type, Action<Intent>>{
ActivateIntent: CallbackAction<ActivateIntent>(onInvoke: _handleTap),
};
/// Called when the control changes value.
///
/// If the control is tapped, [onChanged] is called immediately with the new
/// value.
///
/// The control is considered interactive (see [isInteractive]) if this
/// callback is non-null. If the callback is null, then the control is
/// disabled, and non-interactive. A disabled checkbox, for example, is
/// displayed using a grey color and its value cannot be changed.
ValueChanged<bool?>? get onChanged;
/// False if this control is "inactive" (not checked, off, or unselected).
///
/// If value is true then the control "active" (checked, on, or selected). If
/// tristate is true and value is null, then the control is considered to be
/// in its third or "indeterminate" state.
///
/// When the value changes, this object starts the [positionController] and
/// [position] animations to animate the visual appearance of the control to
/// the new value.
bool? get value;
/// If true, [value] can be true, false, or null, otherwise [value] must
/// be true or false.
///
/// When [tristate] is true and [value] is null, then the control is
/// considered to be in its third or "indeterminate" state.
bool get tristate;
@override
void initState() {
super.initState();
_positionController = AnimationController(
duration: _kToggleDuration,
value: value == false ? 0.0 : 1.0,
vsync: this,
);
_position = CurvedAnimation(
parent: _positionController,
curve: Curves.easeIn,
reverseCurve: Curves.easeOut,
);
_reactionController = AnimationController(
duration: kRadialReactionDuration,
vsync: this,
);
_reaction = CurvedAnimation(
parent: _reactionController,
curve: Curves.fastOutSlowIn,
);
_reactionHoverFadeController = AnimationController(
duration: _kReactionFadeDuration,
value: _hovering || _focused ? 1.0 : 0.0,
vsync: this,
);
_reactionHoverFade = CurvedAnimation(
parent: _reactionHoverFadeController,
curve: Curves.fastOutSlowIn,
);
_reactionFocusFadeController = AnimationController(
duration: _kReactionFadeDuration,
value: _hovering || _focused ? 1.0 : 0.0,
vsync: this,
);
_reactionFocusFade = CurvedAnimation(
parent: _reactionFocusFadeController,
curve: Curves.fastOutSlowIn,
);
}
/// Runs the [position] animation to transition the Toggleable's appearance
/// to match [value].
///
/// This method must be called whenever [value] changes to ensure that the
/// visual representation of the Toggleable matches the current [value].
void animateToValue() {
if (tristate) {
if (value == null) {
_positionController.value = 0.0;
}
if (value ?? true) {
_positionController.forward();
} else {
_positionController.reverse();
}
} else {
if (value ?? false) {
_positionController.forward();
} else {
_positionController.reverse();
}
}
}
@override
void dispose() {
_positionController.dispose();
_position.dispose();
_reactionController.dispose();
_reaction.dispose();
_reactionHoverFadeController.dispose();
_reactionHoverFade.dispose();
_reactionFocusFadeController.dispose();
_reactionFocusFade.dispose();
super.dispose();
}
/// The most recent [Offset] at which a pointer touched the Toggleable.
///
/// This is null if currently no pointer is touching the Toggleable or if
/// [isInteractive] is false.
Offset? get downPosition => _downPosition;
Offset? _downPosition;
void _handleTapDown(TapDownDetails details) {
if (isInteractive) {
setState(() {
_downPosition = details.localPosition;
});
_reactionController.forward();
}
}
void _handleTap([Intent? _]) {
if (!isInteractive) {
return;
}
switch (value) {
case false:
onChanged!(true);
case true:
onChanged!(tristate ? null : false);
case null:
onChanged!(false);
}
context.findRenderObject()!.sendSemanticsEvent(const TapSemanticEvent());
}
void _handleTapEnd([TapUpDetails? _]) {
if (_downPosition != null) {
setState(() { _downPosition = null; });
}
_reactionController.reverse();
}
bool _focused = false;
void _handleFocusHighlightChanged(bool focused) {
if (focused != _focused) {
setState(() { _focused = focused; });
if (focused) {
_reactionFocusFadeController.forward();
} else {
_reactionFocusFadeController.reverse();
}
}
}
bool _hovering = false;
void _handleHoverChanged(bool hovering) {
if (hovering != _hovering) {
setState(() { _hovering = hovering; });
if (hovering) {
_reactionHoverFadeController.forward();
} else {
_reactionHoverFadeController.reverse();
}
}
}
/// Describes the current [MaterialState] of the Toggleable.
///
/// The returned set will include:
///
/// * [MaterialState.disabled], if [isInteractive] is false
/// * [MaterialState.hovered], if a pointer is hovering over the Toggleable
/// * [MaterialState.focused], if the Toggleable has input focus
/// * [MaterialState.selected], if [value] is true or null
Set<MaterialState> get states => <MaterialState>{
if (!isInteractive) MaterialState.disabled,
if (_hovering) MaterialState.hovered,
if (_focused) MaterialState.focused,
if (value ?? true) MaterialState.selected,
};
/// Typically wraps a `painter` that draws the actual visuals of the
/// Toggleable with logic to toggle it.
///
/// Consider providing a subclass of [ToggleablePainter] as a `painter`, which
/// implements logic to draw a radial ink reaction for this control. The
/// painter is usually configured with the [reaction], [position],
/// [reactionHoverFade], and [reactionFocusFade] animation provided by this
/// mixin. It is expected to draw the visuals of the Toggleable based on the
/// current value of these animations. The animations are triggered by
/// this mixin to transition the Toggleable from one state to another.
///
/// This method must be called from the [build] method of the [State] class
/// that uses this mixin. The returned [Widget] must be returned from the
/// build method - potentially after wrapping it in other widgets.
Widget buildToggleable({
FocusNode? focusNode,
ValueChanged<bool>? onFocusChange,
bool autofocus = false,
required MaterialStateProperty<MouseCursor> mouseCursor,
required Size size,
required CustomPainter painter,
}) {
return FocusableActionDetector(
actions: _actionMap,
focusNode: focusNode,
autofocus: autofocus,
onFocusChange: onFocusChange,
enabled: isInteractive,
onShowFocusHighlight: _handleFocusHighlightChanged,
onShowHoverHighlight: _handleHoverChanged,
mouseCursor: mouseCursor.resolve(states),
child: GestureDetector(
excludeFromSemantics: !isInteractive,
onTapDown: isInteractive ? _handleTapDown : null,
onTap: isInteractive ? _handleTap : null,
onTapUp: isInteractive ? _handleTapEnd : null,
onTapCancel: isInteractive ? _handleTapEnd : null,
child: Semantics(
enabled: isInteractive,
child: CustomPaint(
size: size,
painter: painter,
),
),
),
);
}
}
/// A base class for a [CustomPainter] that may be passed to
/// [ToggleableStateMixin.buildToggleable] to draw the visual representation of
/// a Toggleable.
///
/// Subclasses must implement the [paint] method to draw the actual visuals of
/// the Toggleable. In their [paint] method subclasses may call
/// [paintRadialReaction] to draw a radial ink reaction for this control.
abstract class ToggleablePainter extends ChangeNotifier implements CustomPainter {
/// The visual value of the control.
///
/// Usually set to [ToggleableStateMixin.position].
Animation<double> get position => _position!;
Animation<double>? _position;
set position(Animation<double> value) {
if (value == _position) {
return;
}
_position?.removeListener(notifyListeners);
value.addListener(notifyListeners);
_position = value;
notifyListeners();
}
/// The visual value of the radial reaction animation.
///
/// Usually set to [ToggleableStateMixin.reaction].
Animation<double> get reaction => _reaction!;
Animation<double>? _reaction;
set reaction(Animation<double> value) {
if (value == _reaction) {
return;
}
_reaction?.removeListener(notifyListeners);
value.addListener(notifyListeners);
_reaction = value;
notifyListeners();
}
/// Controls the radial reaction's opacity animation for focus changes.
///
/// Usually set to [ToggleableStateMixin.reactionFocusFade].
Animation<double> get reactionFocusFade => _reactionFocusFade!;
Animation<double>? _reactionFocusFade;
set reactionFocusFade(Animation<double> value) {
if (value == _reactionFocusFade) {
return;
}
_reactionFocusFade?.removeListener(notifyListeners);
value.addListener(notifyListeners);
_reactionFocusFade = value;
notifyListeners();
}
/// Controls the radial reaction's opacity animation for hover changes.
///
/// Usually set to [ToggleableStateMixin.reactionHoverFade].
Animation<double> get reactionHoverFade => _reactionHoverFade!;
Animation<double>? _reactionHoverFade;
set reactionHoverFade(Animation<double> value) {
if (value == _reactionHoverFade) {
return;
}
_reactionHoverFade?.removeListener(notifyListeners);
value.addListener(notifyListeners);
_reactionHoverFade = value;
notifyListeners();
}
/// The color that should be used in the active state (i.e., when
/// [ToggleableStateMixin.value] is true).
///
/// For example, a checkbox should use this color when checked.
Color get activeColor => _activeColor!;
Color? _activeColor;
set activeColor(Color value) {
if (_activeColor == value) {
return;
}
_activeColor = value;
notifyListeners();
}
/// The color that should be used in the inactive state (i.e., when
/// [ToggleableStateMixin.value] is false).
///
/// For example, a checkbox should use this color when unchecked.
Color get inactiveColor => _inactiveColor!;
Color? _inactiveColor;
set inactiveColor(Color value) {
if (_inactiveColor == value) {
return;
}
_inactiveColor = value;
notifyListeners();
}
/// The color that should be used for the reaction when the toggleable is
/// inactive.
///
/// Used when the toggleable needs to change the reaction color/transparency
/// that is displayed when the toggleable is inactive and tapped.
Color get inactiveReactionColor => _inactiveReactionColor!;
Color? _inactiveReactionColor;
set inactiveReactionColor(Color value) {
if (value == _inactiveReactionColor) {
return;
}
_inactiveReactionColor = value;
notifyListeners();
}
/// The color that should be used for the reaction when the toggleable is
/// active.
///
/// Used when the toggleable needs to change the reaction color/transparency
/// that is displayed when the toggleable is active and tapped.
Color get reactionColor => _reactionColor!;
Color? _reactionColor;
set reactionColor(Color value) {
if (value == _reactionColor) {
return;
}
_reactionColor = value;
notifyListeners();
}
/// The color that should be used for the reaction when [isHovered] is true.
///
/// Used when the toggleable needs to change the reaction color/transparency,
/// when it is being hovered over.
Color get hoverColor => _hoverColor!;
Color? _hoverColor;
set hoverColor(Color value) {
if (value == _hoverColor) {
return;
}
_hoverColor = value;
notifyListeners();
}
/// The color that should be used for the reaction when [isFocused] is true.
///
/// Used when the toggleable needs to change the reaction color/transparency,
/// when it has focus.
Color get focusColor => _focusColor!;
Color? _focusColor;
set focusColor(Color value) {
if (value == _focusColor) {
return;
}
_focusColor = value;
notifyListeners();
}
/// The splash radius for the radial reaction.
double get splashRadius => _splashRadius!;
double? _splashRadius;
set splashRadius(double value) {
if (value == _splashRadius) {
return;
}
_splashRadius = value;
notifyListeners();
}
/// The [Offset] within the Toggleable at which a pointer touched the Toggleable.
///
/// This is null if currently no pointer is touching the Toggleable.
///
/// Usually set to [ToggleableStateMixin.downPosition].
Offset? get downPosition => _downPosition;
Offset? _downPosition;
set downPosition(Offset? value) {
if (value == _downPosition) {
return;
}
_downPosition = value;
notifyListeners();
}
/// True if this toggleable has the input focus.
bool get isFocused => _isFocused!;
bool? _isFocused;
set isFocused(bool? value) {
if (value == _isFocused) {
return;
}
_isFocused = value;
notifyListeners();
}
/// True if this toggleable is being hovered over by a pointer.
bool get isHovered => _isHovered!;
bool? _isHovered;
set isHovered(bool? value) {
if (value == _isHovered) {
return;
}
_isHovered = value;
notifyListeners();
}
/// Used by subclasses to paint the radial ink reaction for this control.
///
/// The reaction is painted on the given canvas at the given offset. The
/// origin is the center point of the reaction (usually distinct from the
/// [downPosition] at which the user interacted with the control).
void paintRadialReaction({
required Canvas canvas,
Offset offset = Offset.zero,
required Offset origin,
}) {
if (!reaction.isDismissed || !reactionFocusFade.isDismissed || !reactionHoverFade.isDismissed) {
final Paint reactionPaint = Paint()
..color = Color.lerp(
Color.lerp(
Color.lerp(inactiveReactionColor, reactionColor, position.value),
hoverColor,
reactionHoverFade.value,
),
focusColor,
reactionFocusFade.value,
)!;
final Animatable<double> radialReactionRadiusTween = Tween<double>(
begin: 0.0,
end: splashRadius,
);
final double reactionRadius = isFocused || isHovered
? splashRadius
: radialReactionRadiusTween.evaluate(reaction);
if (reactionRadius > 0.0) {
canvas.drawCircle(origin + offset, reactionRadius, reactionPaint);
}
}
}
@override
void dispose() {
_position?.removeListener(notifyListeners);
_reaction?.removeListener(notifyListeners);
_reactionFocusFade?.removeListener(notifyListeners);
_reactionHoverFade?.removeListener(notifyListeners);
super.dispose();
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
@override
bool? hitTest(Offset position) => null;
@override
SemanticsBuilderCallback? get semanticsBuilder => null;
@override
bool shouldRebuildSemantics(covariant CustomPainter oldDelegate) => false;
@override
String toString() => describeIdentity(this);
}
| flutter/packages/flutter/lib/src/material/toggleable.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/toggleable.dart",
"repo_id": "flutter",
"token_count": 6635
} | 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:math' as math;
import 'package:flutter/foundation.dart';
import 'basic_types.dart';
/// How a box should be inscribed into another box.
///
/// See also:
///
/// * [applyBoxFit], which applies the sizing semantics of these values (though
/// not the alignment semantics).
enum BoxFit {
/// Fill the target box by distorting the source's aspect ratio.
///
/// 
fill,
/// As large as possible while still containing the source entirely within the
/// target box.
///
/// 
contain,
/// As small as possible while still covering the entire target box.
///
/// {@template flutter.painting.BoxFit.cover}
/// To actually clip the content, use `clipBehavior: Clip.hardEdge` alongside
/// this in a [FittedBox].
/// {@endtemplate}
///
/// 
cover,
/// Make sure the full width of the source is shown, regardless of
/// whether this means the source overflows the target box vertically.
///
/// {@macro flutter.painting.BoxFit.cover}
///
/// 
fitWidth,
/// Make sure the full height of the source is shown, regardless of
/// whether this means the source overflows the target box horizontally.
///
/// {@macro flutter.painting.BoxFit.cover}
///
/// 
fitHeight,
/// Align the source within the target box (by default, centering) and discard
/// any portions of the source that lie outside the box.
///
/// The source image is not resized.
///
/// {@macro flutter.painting.BoxFit.cover}
///
/// 
none,
/// Align the source within the target box (by default, centering) and, if
/// necessary, scale the source down to ensure that the source fits within the
/// box.
///
/// This is the same as `contain` if that would shrink the image, otherwise it
/// is the same as `none`.
///
/// 
scaleDown,
}
/// The pair of sizes returned by [applyBoxFit].
@immutable
class FittedSizes {
/// Creates an object to store a pair of sizes,
/// as would be returned by [applyBoxFit].
const FittedSizes(this.source, this.destination);
/// The size of the part of the input to show on the output.
final Size source;
/// The size of the part of the output on which to show the input.
final Size destination;
}
/// Apply a [BoxFit] value.
///
/// The arguments to this method, in addition to the [BoxFit] value to apply,
/// are two sizes, ostensibly the sizes of an input box and an output box.
/// Specifically, the `inputSize` argument gives the size of the complete source
/// that is being fitted, and the `outputSize` gives the size of the rectangle
/// into which the source is to be drawn.
///
/// This function then returns two sizes, combined into a single [FittedSizes]
/// object.
///
/// The [FittedSizes.source] size is the subpart of the `inputSize` that is to
/// be shown. If the entire input source is shown, then this will equal the
/// `inputSize`, but if the input source is to be cropped down, this may be
/// smaller.
///
/// The [FittedSizes.destination] size is the subpart of the `outputSize` in
/// which to paint the (possibly cropped) source. If the
/// [FittedSizes.destination] size is smaller than the `outputSize` then the
/// source is being letterboxed (or pillarboxed).
///
/// This method does not express an opinion regarding the alignment of the
/// source and destination sizes within the input and output rectangles.
/// Typically they are centered (this is what [BoxDecoration] does, for
/// instance, and is how [BoxFit] is defined). The [Alignment] class provides a
/// convenience function, [Alignment.inscribe], for resolving the sizes to
/// rects, as shown in the example below.
///
/// {@tool snippet}
///
/// This function paints a [dart:ui.Image] `image` onto the [Rect] `outputRect` on a
/// [Canvas] `canvas`, using a [Paint] `paint`, applying the [BoxFit] algorithm
/// `fit`:
///
/// ```dart
/// void paintImage(ui.Image image, Rect outputRect, Canvas canvas, Paint paint, BoxFit fit) {
/// final Size imageSize = Size(image.width.toDouble(), image.height.toDouble());
/// final FittedSizes sizes = applyBoxFit(fit, imageSize, outputRect.size);
/// final Rect inputSubrect = Alignment.center.inscribe(sizes.source, Offset.zero & imageSize);
/// final Rect outputSubrect = Alignment.center.inscribe(sizes.destination, outputRect);
/// canvas.drawImageRect(image, inputSubrect, outputSubrect, paint);
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [FittedBox], a widget that applies this algorithm to another widget.
/// * [paintImage], a function that applies this algorithm to images for painting.
/// * [DecoratedBox], [BoxDecoration], and [DecorationImage], which together
/// provide access to [paintImage] at the widgets layer.
FittedSizes applyBoxFit(BoxFit fit, Size inputSize, Size outputSize) {
if (inputSize.height <= 0.0 || inputSize.width <= 0.0 || outputSize.height <= 0.0 || outputSize.width <= 0.0) {
return const FittedSizes(Size.zero, Size.zero);
}
Size sourceSize, destinationSize;
switch (fit) {
case BoxFit.fill:
sourceSize = inputSize;
destinationSize = outputSize;
case BoxFit.contain:
sourceSize = inputSize;
if (outputSize.width / outputSize.height > sourceSize.width / sourceSize.height) {
destinationSize = Size(sourceSize.width * outputSize.height / sourceSize.height, outputSize.height);
} else {
destinationSize = Size(outputSize.width, sourceSize.height * outputSize.width / sourceSize.width);
}
case BoxFit.cover:
if (outputSize.width / outputSize.height > inputSize.width / inputSize.height) {
sourceSize = Size(inputSize.width, inputSize.width * outputSize.height / outputSize.width);
} else {
sourceSize = Size(inputSize.height * outputSize.width / outputSize.height, inputSize.height);
}
destinationSize = outputSize;
case BoxFit.fitWidth:
if (outputSize.width / outputSize.height > inputSize.width / inputSize.height) {
// Like "cover"
sourceSize = Size(inputSize.width, inputSize.width * outputSize.height / outputSize.width);
destinationSize = outputSize;
} else {
// Like "contain"
sourceSize = inputSize;
destinationSize = Size(outputSize.width, sourceSize.height * outputSize.width / sourceSize.width);
}
case BoxFit.fitHeight:
if (outputSize.width / outputSize.height > inputSize.width / inputSize.height) {
// Like "contain"
sourceSize = inputSize;
destinationSize = Size(sourceSize.width * outputSize.height / sourceSize.height, outputSize.height);
} else {
// Like "cover"
sourceSize = Size(inputSize.height * outputSize.width / outputSize.height, inputSize.height);
destinationSize = outputSize;
}
case BoxFit.none:
sourceSize = Size(math.min(inputSize.width, outputSize.width), math.min(inputSize.height, outputSize.height));
destinationSize = sourceSize;
case BoxFit.scaleDown:
sourceSize = inputSize;
destinationSize = inputSize;
final double aspectRatio = inputSize.width / inputSize.height;
if (destinationSize.height > outputSize.height) {
destinationSize = Size(outputSize.height * aspectRatio, outputSize.height);
}
if (destinationSize.width > outputSize.width) {
destinationSize = Size(outputSize.width, outputSize.width / aspectRatio);
}
}
return FittedSizes(sourceSize, destinationSize);
}
| flutter/packages/flutter/lib/src/painting/box_fit.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/box_fit.dart",
"repo_id": "flutter",
"token_count": 2636
} | 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 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '_network_image_io.dart'
if (dart.library.js_util) '_network_image_web.dart' as network_image;
import 'binding.dart';
import 'image_cache.dart';
import 'image_stream.dart';
/// Signature for the callback taken by [_createErrorHandlerAndKey].
typedef _KeyAndErrorHandlerCallback<T> = void Function(T key, ImageErrorListener handleError);
/// Signature used for error handling by [_createErrorHandlerAndKey].
typedef _AsyncKeyErrorHandler<T> = Future<void> Function(T key, Object exception, StackTrace? stack);
/// Configuration information passed to the [ImageProvider.resolve] method to
/// select a specific image.
///
/// See also:
///
/// * [createLocalImageConfiguration], which creates an [ImageConfiguration]
/// based on ambient configuration in a [Widget] environment.
/// * [ImageProvider], which uses [ImageConfiguration] objects to determine
/// which image to obtain.
@immutable
class ImageConfiguration {
/// Creates an object holding the configuration information for an [ImageProvider].
///
/// All the arguments are optional. Configuration information is merely
/// advisory and best-effort.
const ImageConfiguration({
this.bundle,
this.devicePixelRatio,
this.locale,
this.textDirection,
this.size,
this.platform,
});
/// Creates an object holding the configuration information for an [ImageProvider].
///
/// All the arguments are optional. Configuration information is merely
/// advisory and best-effort.
ImageConfiguration copyWith({
AssetBundle? bundle,
double? devicePixelRatio,
ui.Locale? locale,
TextDirection? textDirection,
Size? size,
TargetPlatform? platform,
}) {
return ImageConfiguration(
bundle: bundle ?? this.bundle,
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
locale: locale ?? this.locale,
textDirection: textDirection ?? this.textDirection,
size: size ?? this.size,
platform: platform ?? this.platform,
);
}
/// The preferred [AssetBundle] to use if the [ImageProvider] needs one and
/// does not have one already selected.
final AssetBundle? bundle;
/// The device pixel ratio where the image will be shown.
final double? devicePixelRatio;
/// The language and region for which to select the image.
final ui.Locale? locale;
/// The reading direction of the language for which to select the image.
final TextDirection? textDirection;
/// The size at which the image will be rendered.
final Size? size;
/// The [TargetPlatform] for which assets should be used. This allows images
/// to be specified in a platform-neutral fashion yet use different assets on
/// different platforms, to match local conventions e.g. for color matching or
/// shadows.
final TargetPlatform? platform;
/// An image configuration that provides no additional information.
///
/// Useful when resolving an [ImageProvider] without any context.
static const ImageConfiguration empty = ImageConfiguration();
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is ImageConfiguration
&& other.bundle == bundle
&& other.devicePixelRatio == devicePixelRatio
&& other.locale == locale
&& other.textDirection == textDirection
&& other.size == size
&& other.platform == platform;
}
@override
int get hashCode => Object.hash(bundle, devicePixelRatio, locale, size, platform);
@override
String toString() {
final StringBuffer result = StringBuffer();
result.write('ImageConfiguration(');
bool hasArguments = false;
if (bundle != null) {
result.write('bundle: $bundle');
hasArguments = true;
}
if (devicePixelRatio != null) {
if (hasArguments) {
result.write(', ');
}
result.write('devicePixelRatio: ${devicePixelRatio!.toStringAsFixed(1)}');
hasArguments = true;
}
if (locale != null) {
if (hasArguments) {
result.write(', ');
}
result.write('locale: $locale');
hasArguments = true;
}
if (textDirection != null) {
if (hasArguments) {
result.write(', ');
}
result.write('textDirection: $textDirection');
hasArguments = true;
}
if (size != null) {
if (hasArguments) {
result.write(', ');
}
result.write('size: $size');
hasArguments = true;
}
if (platform != null) {
if (hasArguments) {
result.write(', ');
}
result.write('platform: ${platform!.name}');
hasArguments = true;
}
result.write(')');
return result.toString();
}
}
/// Performs the decode process for use in [ImageProvider.loadBuffer].
///
/// This callback allows decoupling of the `cacheWidth`, `cacheHeight`, and
/// `allowUpscaling` parameters from implementations of [ImageProvider] that do
/// not expose them.
///
/// See also:
///
/// * [ResizeImage], which uses this to override the `cacheWidth`,
/// `cacheHeight`, and `allowUpscaling` parameters.
@Deprecated(
'Use ImageDecoderCallback with ImageProvider.loadImage instead. '
'This feature was deprecated after v3.7.0-1.4.pre.',
)
typedef DecoderBufferCallback = Future<ui.Codec> Function(ui.ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool allowUpscaling});
// Method signature for _loadAsync decode callbacks.
typedef _SimpleDecoderCallback = Future<ui.Codec> Function(ui.ImmutableBuffer buffer);
/// Performs the decode process for use in [ImageProvider.loadImage].
///
/// This callback allows decoupling of the `getTargetSize` parameter from
/// implementations of [ImageProvider] that do not expose it.
///
/// See also:
///
/// * [ResizeImage], which uses this to load images at specific sizes.
typedef ImageDecoderCallback = Future<ui.Codec> Function(
ui.ImmutableBuffer buffer, {
ui.TargetImageSizeCallback? getTargetSize,
});
/// Identifies an image without committing to the precise final asset. This
/// allows a set of images to be identified and for the precise image to later
/// be resolved based on the environment, e.g. the device pixel ratio.
///
/// To obtain an [ImageStream] from an [ImageProvider], call [resolve],
/// passing it an [ImageConfiguration] object.
///
/// [ImageProvider] uses the global [imageCache] to cache images.
///
/// The type argument `T` is the type of the object used to represent a resolved
/// configuration. This is also the type used for the key in the image cache. It
/// should be immutable and implement the [==] operator and the [hashCode]
/// getter. Subclasses should subclass a variant of [ImageProvider] with an
/// explicit `T` type argument.
///
/// The type argument does not have to be specified when using the type as an
/// argument (where any image provider is acceptable).
///
/// The following image formats are supported: {@macro dart.ui.imageFormats}
///
/// ## Lifecycle of resolving an image
///
/// The [ImageProvider] goes through the following lifecycle to resolve an
/// image, once the [resolve] method is called:
///
/// 1. Create an [ImageStream] using [createStream] to return to the caller.
/// This stream will be used to communicate back to the caller when the
/// image is decoded and ready to display, or when an error occurs.
/// 2. Obtain the key for the image using [obtainKey].
/// Calling this method can throw exceptions into the zone asynchronously
/// or into the call stack synchronously. To handle that, an error handler
/// is created that catches both synchronous and asynchronous errors, to
/// make sure errors can be routed to the correct consumers.
/// The error handler is passed on to [resolveStreamForKey] and the
/// [ImageCache].
/// 3. If the key is successfully obtained, schedule resolution of the image
/// using that key. This is handled by [resolveStreamForKey]. That method
/// may fizzle if it determines the image is no longer necessary, use the
/// provided [ImageErrorListener] to report an error, set the completer
/// from the cache if possible, or call [loadImage] to fetch the encoded image
/// bytes and schedule decoding.
/// 4. The [loadImage] method is responsible for both fetching the encoded bytes
/// and decoding them using the provided [ImageDecoderCallback]. It is called
/// in a context that uses the [ImageErrorListener] to report errors back.
///
/// Subclasses normally only have to implement the [loadImage] and [obtainKey]
/// methods. A subclass that needs finer grained control over the [ImageStream]
/// type must override [createStream]. A subclass that needs finer grained
/// control over the resolution, such as delaying calling [loadImage], must override
/// [resolveStreamForKey].
///
/// The [resolve] method is marked as [nonVirtual] so that [ImageProvider]s can
/// be properly composed, and so that the base class can properly set up error
/// handling for subsequent methods.
///
/// ## Using an [ImageProvider]
///
/// {@tool snippet}
///
/// The following shows the code required to write a widget that fully conforms
/// to the [ImageProvider] and [Widget] protocols. (It is essentially a
/// bare-bones version of the [widgets.Image] widget.)
///
/// ```dart
/// class MyImage extends StatefulWidget {
/// const MyImage({
/// super.key,
/// required this.imageProvider,
/// });
///
/// final ImageProvider imageProvider;
///
/// @override
/// State<MyImage> createState() => _MyImageState();
/// }
///
/// class _MyImageState extends State<MyImage> {
/// ImageStream? _imageStream;
/// ImageInfo? _imageInfo;
///
/// @override
/// void didChangeDependencies() {
/// super.didChangeDependencies();
/// // We call _getImage here because createLocalImageConfiguration() needs to
/// // be called again if the dependencies changed, in case the changes relate
/// // to the DefaultAssetBundle, MediaQuery, etc, which that method uses.
/// _getImage();
/// }
///
/// @override
/// void didUpdateWidget(MyImage oldWidget) {
/// super.didUpdateWidget(oldWidget);
/// if (widget.imageProvider != oldWidget.imageProvider) {
/// _getImage();
/// }
/// }
///
/// void _getImage() {
/// final ImageStream? oldImageStream = _imageStream;
/// _imageStream = widget.imageProvider.resolve(createLocalImageConfiguration(context));
/// if (_imageStream!.key != oldImageStream?.key) {
/// // If the keys are the same, then we got the same image back, and so we don't
/// // need to update the listeners. If the key changed, though, we must make sure
/// // to switch our listeners to the new image stream.
/// final ImageStreamListener listener = ImageStreamListener(_updateImage);
/// oldImageStream?.removeListener(listener);
/// _imageStream!.addListener(listener);
/// }
/// }
///
/// void _updateImage(ImageInfo imageInfo, bool synchronousCall) {
/// setState(() {
/// // Trigger a build whenever the image changes.
/// _imageInfo?.dispose();
/// _imageInfo = imageInfo;
/// });
/// }
///
/// @override
/// void dispose() {
/// _imageStream?.removeListener(ImageStreamListener(_updateImage));
/// _imageInfo?.dispose();
/// _imageInfo = null;
/// super.dispose();
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// return RawImage(
/// image: _imageInfo?.image, // this is a dart:ui Image object
/// scale: _imageInfo?.scale ?? 1.0,
/// );
/// }
/// }
/// ```
/// {@end-tool}
///
/// ## Creating an [ImageProvider]
///
/// {@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}
@optionalTypeArgs
abstract class ImageProvider<T extends Object> {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const ImageProvider();
/// Resolves this image provider using the given `configuration`, returning
/// an [ImageStream].
///
/// This is the public entry-point of the [ImageProvider] class hierarchy.
///
/// Subclasses should implement [obtainKey] and [loadImage], which are used by
/// this method. If they need to change the implementation of [ImageStream]
/// used, they should override [createStream]. If they need to manage the
/// actual resolution of the image, they should override [resolveStreamForKey].
///
/// See the Lifecycle documentation on [ImageProvider] for more information.
@nonVirtual
ImageStream resolve(ImageConfiguration configuration) {
final ImageStream stream = createStream(configuration);
// Load the key (potentially asynchronously), set up an error handling zone,
// and call resolveStreamForKey.
_createErrorHandlerAndKey(
configuration,
(T key, ImageErrorListener errorHandler) {
resolveStreamForKey(configuration, stream, key, errorHandler);
},
(T? key, Object exception, StackTrace? stack) async {
await null; // wait an event turn in case a listener has been added to the image stream.
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<ImageProvider>('Image provider', this),
DiagnosticsProperty<ImageConfiguration>('Image configuration', configuration),
DiagnosticsProperty<T>('Image key', key, defaultValue: null),
];
return true;
}());
if (stream.completer == null) {
stream.setCompleter(_ErrorImageCompleter());
}
stream.completer!.reportError(
exception: exception,
stack: stack,
context: ErrorDescription('while resolving an image'),
silent: true, // could be a network error or whatnot
informationCollector: collector,
);
},
);
return stream;
}
/// Called by [resolve] to create the [ImageStream] it returns.
///
/// Subclasses should override this instead of [resolve] if they need to
/// return some subclass of [ImageStream]. The stream created here will be
/// passed to [resolveStreamForKey].
@protected
ImageStream createStream(ImageConfiguration configuration) {
return ImageStream();
}
/// Returns the cache location for the key that this [ImageProvider] creates.
///
/// The location may be [ImageCacheStatus.untracked], indicating that this
/// image provider's key is not available in the [ImageCache].
///
/// If the `handleError` parameter is null, errors will be reported to
/// [FlutterError.onError], and the method will return null.
///
/// A completed return value of null indicates that an error has occurred.
Future<ImageCacheStatus?> obtainCacheStatus({
required ImageConfiguration configuration,
ImageErrorListener? handleError,
}) {
final Completer<ImageCacheStatus?> completer = Completer<ImageCacheStatus?>();
_createErrorHandlerAndKey(
configuration,
(T key, ImageErrorListener innerHandleError) {
completer.complete(PaintingBinding.instance.imageCache.statusForKey(key));
},
(T? key, Object exception, StackTrace? stack) async {
if (handleError != null) {
handleError(exception, stack);
} else {
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<ImageProvider>('Image provider', this),
DiagnosticsProperty<ImageConfiguration>('Image configuration', configuration),
DiagnosticsProperty<T>('Image key', key, defaultValue: null),
];
return true;
}());
FlutterError.reportError(FlutterErrorDetails(
context: ErrorDescription('while checking the cache location of an image'),
informationCollector: collector,
exception: exception,
stack: stack,
));
completer.complete();
}
},
);
return completer.future;
}
/// This method is used by both [resolve] and [obtainCacheStatus] to ensure
/// that errors thrown during key creation are handled whether synchronous or
/// asynchronous.
void _createErrorHandlerAndKey(
ImageConfiguration configuration,
_KeyAndErrorHandlerCallback<T> successCallback,
_AsyncKeyErrorHandler<T?> errorCallback,
) {
T? obtainedKey;
bool didError = false;
Future<void> handleError(Object exception, StackTrace? stack) async {
if (didError) {
return;
}
if (!didError) {
didError = true;
errorCallback(obtainedKey, exception, stack);
}
}
Future<T> key;
try {
key = obtainKey(configuration);
} catch (error, stackTrace) {
handleError(error, stackTrace);
return;
}
key.then<void>((T key) {
obtainedKey = key;
try {
successCallback(key, handleError);
} catch (error, stackTrace) {
handleError(error, stackTrace);
}
}).catchError(handleError);
}
/// Called by [resolve] with the key returned by [obtainKey].
///
/// Subclasses should override this method rather than calling [obtainKey] if
/// they need to use a key directly. The [resolve] method installs appropriate
/// error handling guards so that errors will bubble up to the right places in
/// the framework, and passes those guards along to this method via the
/// [handleError] parameter.
///
/// It is safe for the implementation of this method to call [handleError]
/// multiple times if multiple errors occur, or if an error is thrown both
/// synchronously into the current part of the stack and thrown into the
/// enclosing [Zone].
///
/// The default implementation uses the key to interact with the [ImageCache],
/// calling [ImageCache.putIfAbsent] and notifying listeners of the [stream].
/// Implementers that do not call super are expected to correctly use the
/// [ImageCache].
@protected
void resolveStreamForKey(ImageConfiguration configuration, ImageStream stream, T key, ImageErrorListener handleError) {
// This is an unusual edge case where someone has told us that they found
// the image we want before getting to this method. We should avoid calling
// load again, but still update the image cache with LRU information.
if (stream.completer != null) {
final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent(
key,
() => stream.completer!,
onError: handleError,
);
assert(identical(completer, stream.completer));
return;
}
final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent(
key,
() {
ImageStreamCompleter result = loadImage(key, PaintingBinding.instance.instantiateImageCodecWithSize);
// This check exists as a fallback for backwards compatibility until the
// deprecated `loadBuffer()` method is removed. Until then, ImageProvider
// subclasses may have only overridden `loadBuffer()`, in which case the
// base implementation of `loadWithSize()` will return a sentinel value
// of type `_AbstractImageStreamCompleter`.
if (result is _AbstractImageStreamCompleter) {
result = loadBuffer(key, PaintingBinding.instance.instantiateImageCodecFromBuffer);
}
return result;
},
onError: handleError,
);
if (completer != null) {
stream.setCompleter(completer);
}
}
/// Evicts an entry from the image cache.
///
/// Returns a [Future] which indicates whether the value was successfully
/// removed.
///
/// The [ImageProvider] used does not need to be the same instance that was
/// passed to an [Image] widget, but it does need to create a key which is
/// equal to one.
///
/// The [cache] is optional and defaults to the global image cache.
///
/// The [configuration] is optional and defaults to
/// [ImageConfiguration.empty].
///
/// {@tool snippet}
///
/// The following sample code shows how an image loaded using the [Image]
/// widget can be evicted using a [NetworkImage] with a matching URL.
///
/// ```dart
/// class MyWidget extends StatelessWidget {
/// const MyWidget({
/// super.key,
/// this.url = ' ... ',
/// });
///
/// final String url;
///
/// @override
/// Widget build(BuildContext context) {
/// return Image.network(url);
/// }
///
/// void evictImage() {
/// final NetworkImage provider = NetworkImage(url);
/// provider.evict().then<void>((bool success) {
/// if (success) {
/// debugPrint('removed image!');
/// }
/// });
/// }
/// }
/// ```
/// {@end-tool}
Future<bool> evict({ ImageCache? cache, ImageConfiguration configuration = ImageConfiguration.empty }) async {
cache ??= imageCache;
final T key = await obtainKey(configuration);
return cache.evict(key);
}
/// Converts an [ImageProvider]'s settings plus an [ImageConfiguration] to a key
/// that describes the precise image to load.
///
/// The type of the key is determined by the subclass. It is a value that
/// unambiguously identifies the image (_including its scale_) that the
/// [loadImage] method will fetch. Different [ImageProvider]s given the same
/// constructor arguments and [ImageConfiguration] objects should return keys
/// that are '==' to each other (possibly by using a class for the key that
/// itself implements [==]).
///
/// If the result can be determined synchronously, this function should return
/// a [SynchronousFuture]. This allows image resolution to progress
/// synchronously during a frame rather than delaying image loading.
Future<T> obtainKey(ImageConfiguration configuration);
/// Converts a key into an [ImageStreamCompleter], and begins fetching the
/// image.
///
/// This method is deprecated. Implement [loadImage] instead.
///
/// The [decode] callback provides the logic to obtain the codec for the
/// image.
///
/// See also:
///
/// * [ResizeImage], for modifying the key to account for cache dimensions.
@protected
@Deprecated(
'Implement loadImage for image loading. '
'This feature was deprecated after v3.7.0-1.4.pre.',
)
ImageStreamCompleter loadBuffer(T key, DecoderBufferCallback decode) {
return _AbstractImageStreamCompleter();
}
/// Converts a key into an [ImageStreamCompleter], and begins fetching the
/// image.
///
/// For backwards-compatibility the default implementation of this method returns
/// an object that will cause [resolveStreamForKey] to consult [loadBuffer].
/// However, implementors of this interface should only override this method
/// and not [loadBuffer], which is deprecated.
///
/// The [decode] callback provides the logic to obtain the codec for the
/// image.
///
/// See also:
///
/// * [ResizeImage], for modifying the key to account for cache dimensions.
// TODO(tvolkert): make abstract (https://github.com/flutter/flutter/issues/119209)
@protected
ImageStreamCompleter loadImage(T key, ImageDecoderCallback decode) {
return _AbstractImageStreamCompleter();
}
@override
String toString() => '${objectRuntimeType(this, 'ImageConfiguration')}()';
}
/// A class that exists to facilitate backwards compatibility in the transition
/// from [ImageProvider.load] to [ImageProvider.loadBuffer] to [ImageProvider.loadImage]
class _AbstractImageStreamCompleter extends ImageStreamCompleter {}
/// Key for the image obtained by an [AssetImage] or [ExactAssetImage].
///
/// This is used to identify the precise resource in the [imageCache].
@immutable
class AssetBundleImageKey {
/// Creates the key for an [AssetImage] or [AssetBundleImageProvider].
const AssetBundleImageKey({
required this.bundle,
required this.name,
required this.scale,
});
/// The bundle from which the image will be obtained.
///
/// The image is obtained by calling [AssetBundle.load] on the given [bundle]
/// using the key given by [name].
final AssetBundle bundle;
/// The key to use to obtain the resource from the [bundle]. This is the
/// argument passed to [AssetBundle.load].
final String name;
/// The scale to place in the [ImageInfo] object of the image.
final double scale;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is AssetBundleImageKey
&& other.bundle == bundle
&& other.name == name
&& other.scale == scale;
}
@override
int get hashCode => Object.hash(bundle, name, scale);
@override
String toString() => '${objectRuntimeType(this, 'AssetBundleImageKey')}(bundle: $bundle, name: "$name", scale: $scale)';
}
/// A subclass of [ImageProvider] that knows about [AssetBundle]s.
///
/// This factors out the common logic of [AssetBundle]-based [ImageProvider]
/// classes, simplifying what subclasses must implement to just [obtainKey].
abstract class AssetBundleImageProvider extends ImageProvider<AssetBundleImageKey> {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const AssetBundleImageProvider();
@override
ImageStreamCompleter loadImage(AssetBundleImageKey key, ImageDecoderCallback decode) {
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<ImageProvider>('Image provider', this),
DiagnosticsProperty<AssetBundleImageKey>('Image key', key),
];
return true;
}());
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key, decode: decode),
scale: key.scale,
debugLabel: key.name,
informationCollector: collector,
);
}
/// Converts a key into an [ImageStreamCompleter], and begins fetching the
/// image.
@override
ImageStreamCompleter loadBuffer(AssetBundleImageKey key, DecoderBufferCallback decode) {
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<ImageProvider>('Image provider', this),
DiagnosticsProperty<AssetBundleImageKey>('Image key', key),
];
return true;
}());
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key, decode: decode),
scale: key.scale,
debugLabel: key.name,
informationCollector: collector,
);
}
/// Fetches the image from the asset bundle, decodes it, and returns a
/// corresponding [ImageInfo] object.
///
/// This function is used by [loadImage].
@protected
Future<ui.Codec> _loadAsync(
AssetBundleImageKey key, {
required _SimpleDecoderCallback decode,
}) async {
final ui.ImmutableBuffer buffer;
// Hot reload/restart could change whether an asset bundle or key in a
// bundle are available, or if it is a network backed bundle.
try {
buffer = await key.bundle.loadBuffer(key.name);
} on FlutterError {
PaintingBinding.instance.imageCache.evict(key);
rethrow;
}
return decode(buffer);
}
}
/// Key used internally by [ResizeImage].
///
/// This is used to identify the precise resource in the [imageCache].
@immutable
class ResizeImageKey {
// Private constructor so nobody from the outside can poison the image cache
// with this key. It's only accessible to [ResizeImage] internally.
const ResizeImageKey._(this._providerCacheKey, this._policy, this._width, this._height, this._allowUpscaling);
final Object _providerCacheKey;
final ResizeImagePolicy _policy;
final int? _width;
final int? _height;
final bool _allowUpscaling;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is ResizeImageKey
&& other._providerCacheKey == _providerCacheKey
&& other._policy == _policy
&& other._width == _width
&& other._height == _height
&& other._allowUpscaling == _allowUpscaling;
}
@override
int get hashCode => Object.hash(_providerCacheKey, _policy, _width, _height, _allowUpscaling);
}
/// Configures the behavior for [ResizeImage].
///
/// This is used in [ResizeImage.policy] to affect how the [ResizeImage.width]
/// and [ResizeImage.height] properties are interpreted.
enum ResizeImagePolicy {
/// Sizes the image to the exact width and height specified by
/// [ResizeImage.width] and [ResizeImage.height].
///
/// If [ResizeImage.width] and [ResizeImage.height] are both non-null, the
/// output image will have the specified width and height (with the
/// corresponding aspect ratio) regardless of whether it matches the source
/// image's intrinsic aspect ratio. This case is similar to [BoxFit.fill].
///
/// If only one of `width` and `height` is non-null, then the output image
/// will be scaled to the associated width or height, and the other dimension
/// will take whatever value is needed to maintain the image's original aspect
/// ratio. These cases are similar to [BoxFit.fitWidth] and
/// [BoxFit.fitHeight], respectively.
///
/// If [ResizeImage.allowUpscaling] is false (the default), the width and the
/// height of the output image will each be clamped to the intrinsic width and
/// height of the image. This may result in a different aspect ratio than the
/// aspect ratio specified by the target width and height (e.g. if the height
/// gets clamped downwards but the width does not).
///
/// ## Examples
///
/// The examples below show how [ResizeImagePolicy.exact] works in various
/// scenarios. In each example, the source image has a size of 300x200
/// (landscape orientation), the red box is a 150x150 square, and the green
/// box is a 400x400 square.
///
/// <table>
/// <tr>
/// <td>Scenario</td>
/// <td>Output</td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 150,
/// height: 150,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 150,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// height: 150,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 400,
/// height: 400,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 400,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// height: 400,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 400,
/// height: 400,
/// allowUpscaling: true,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// width: 400,
/// allowUpscaling: true,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// height: 400,
/// allowUpscaling: true,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// </table>
exact,
/// Scales the image as necessary to ensure that it fits within the bounding
/// box specified by [ResizeImage.width] and [ResizeImage.height] while
/// maintaining its aspect ratio.
///
/// If [ResizeImage.allowUpscaling] is true, the image will be scaled up or
/// down to best fit the bounding box; otherwise it will only ever be scaled
/// down.
///
/// This is conceptually similar to [BoxFit.contain].
///
/// ## Examples
///
/// The examples below show how [ResizeImagePolicy.fit] works in various
/// scenarios. In each example, the source image has a size of 300x200
/// (landscape orientation), the red box is a 150x150 square, and the green
/// box is a 400x400 square.
///
/// <table>
/// <tr>
/// <td>Scenario</td>
/// <td>Output</td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// policy: ResizeImagePolicy.fit,
/// width: 150,
/// height: 150,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// policy: ResizeImagePolicy.fit,
/// width: 150,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// policy: ResizeImagePolicy.fit,
/// height: 150,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// policy: ResizeImagePolicy.fit,
/// width: 400,
/// height: 400,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// policy: ResizeImagePolicy.fit,
/// width: 400,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// policy: ResizeImagePolicy.fit,
/// height: 400,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// policy: ResizeImagePolicy.fit,
/// width: 400,
/// height: 400,
/// allowUpscaling: true,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// policy: ResizeImagePolicy.fit,
/// width: 400,
/// allowUpscaling: true,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// <tr>
/// <td>
///
/// ```dart
/// const ResizeImage(
/// AssetImage('dragon_cake.jpg'),
/// policy: ResizeImagePolicy.fit,
/// height: 400,
/// allowUpscaling: true,
/// )
/// ```
///
/// </td>
/// <td>
///
/// 
///
/// </td>
/// </tr>
/// </table>
fit,
}
/// Instructs Flutter to decode the image at the specified dimensions
/// instead of at its native size.
///
/// This allows finer control of the size of the image in [ImageCache] and is
/// generally used to reduce the memory footprint of [ImageCache].
///
/// The decoded image may still be displayed at sizes other than the
/// cached size provided here.
class ResizeImage extends ImageProvider<ResizeImageKey> {
/// Creates an ImageProvider that decodes the image to the specified size.
///
/// The cached image will be directly decoded and stored at the resolution
/// defined by `width` and `height`. The image will lose detail and
/// use less memory if resized to a size smaller than the native size.
///
/// At least one of `width` and `height` must be non-null.
const ResizeImage(
this.imageProvider, {
this.width,
this.height,
this.policy = ResizeImagePolicy.exact,
this.allowUpscaling = false,
}) : assert(width != null || height != null);
/// The [ImageProvider] that this class wraps.
final ImageProvider imageProvider;
/// The width the image should decode to and cache.
///
/// At least one of this and [height] must be non-null.
final int? width;
/// The height the image should decode to and cache.
///
/// At least one of this and [width] must be non-null.
final int? height;
/// The policy that determines how [width] and [height] are interpreted.
///
/// Defaults to [ResizeImagePolicy.exact].
final ResizeImagePolicy policy;
/// Whether the [width] and [height] parameters should be clamped to the
/// intrinsic width and height of the image.
///
/// In general, it is better for memory usage to avoid scaling the image
/// beyond its intrinsic dimensions when decoding it. If there is a need to
/// scale an image larger, it is better to apply a scale to the canvas, or
/// to use an appropriate [Image.fit].
final bool allowUpscaling;
/// Composes the `provider` in a [ResizeImage] only when `cacheWidth` and
/// `cacheHeight` are not both null.
///
/// When `cacheWidth` and `cacheHeight` are both null, this will return the
/// `provider` directly.
static ImageProvider<Object> resizeIfNeeded(int? cacheWidth, int? cacheHeight, ImageProvider<Object> provider) {
if (cacheWidth != null || cacheHeight != null) {
return ResizeImage(provider, width: cacheWidth, height: cacheHeight);
}
return provider;
}
@override
@Deprecated(
'Implement loadImage for image loading. '
'This feature was deprecated after v3.7.0-1.4.pre.',
)
ImageStreamCompleter loadBuffer(ResizeImageKey key, DecoderBufferCallback decode) {
Future<ui.Codec> decodeResize(ui.ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
assert(
cacheWidth == null && cacheHeight == null && allowUpscaling == null,
'ResizeImage cannot be composed with another ImageProvider that applies '
'cacheWidth, cacheHeight, or allowUpscaling.',
);
return decode(buffer, cacheWidth: width, cacheHeight: height, allowUpscaling: this.allowUpscaling);
}
final ImageStreamCompleter completer = imageProvider.loadBuffer(key._providerCacheKey, decodeResize);
if (!kReleaseMode) {
completer.debugLabel = '${completer.debugLabel} - Resized(${key._width}×${key._height})';
}
_configureErrorListener(completer, key);
return completer;
}
@override
ImageStreamCompleter loadImage(ResizeImageKey key, ImageDecoderCallback decode) {
Future<ui.Codec> decodeResize(ui.ImmutableBuffer buffer, {ui.TargetImageSizeCallback? getTargetSize}) {
assert(
getTargetSize == null,
'ResizeImage cannot be composed with another ImageProvider that applies '
'getTargetSize.',
);
return decode(buffer, getTargetSize: (int intrinsicWidth, int intrinsicHeight) {
switch (policy) {
case ResizeImagePolicy.exact:
int? targetWidth = width;
int? targetHeight = height;
if (!allowUpscaling) {
if (targetWidth != null && targetWidth > intrinsicWidth) {
targetWidth = intrinsicWidth;
}
if (targetHeight != null && targetHeight > intrinsicHeight) {
targetHeight = intrinsicHeight;
}
}
return ui.TargetImageSize(width: targetWidth, height: targetHeight);
case ResizeImagePolicy.fit:
final double aspectRatio = intrinsicWidth / intrinsicHeight;
final int maxWidth = width ?? intrinsicWidth;
final int maxHeight = height ?? intrinsicHeight;
int targetWidth = intrinsicWidth;
int targetHeight = intrinsicHeight;
if (targetWidth > maxWidth) {
targetWidth = maxWidth;
targetHeight = targetWidth ~/ aspectRatio;
}
if (targetHeight > maxHeight) {
targetHeight = maxHeight;
targetWidth = (targetHeight * aspectRatio).floor();
}
if (allowUpscaling) {
if (width == null) {
assert(height != null);
targetHeight = height!;
targetWidth = (targetHeight * aspectRatio).floor();
} else if (height == null) {
targetWidth = width!;
targetHeight = targetWidth ~/ aspectRatio;
} else {
final int derivedMaxWidth = (maxHeight * aspectRatio).floor();
final int derivedMaxHeight = maxWidth ~/ aspectRatio;
targetWidth = math.min(maxWidth, derivedMaxWidth);
targetHeight = math.min(maxHeight, derivedMaxHeight);
}
}
return ui.TargetImageSize(width: targetWidth, height: targetHeight);
}
});
}
final ImageStreamCompleter completer = imageProvider.loadImage(key._providerCacheKey, decodeResize);
if (!kReleaseMode) {
completer.debugLabel = '${completer.debugLabel} - Resized(${key._width}×${key._height})';
}
_configureErrorListener(completer, key);
return completer;
}
void _configureErrorListener(ImageStreamCompleter completer, ResizeImageKey key) {
completer.addEphemeralErrorListener((Object exception, StackTrace? stackTrace) {
// The microtask is scheduled because of the same reason as NetworkImage:
// Depending on where the exception was thrown, the image cache may not
// have had a chance to track the key in the cache at all.
// Schedule a microtask to give the cache a chance to add the key.
scheduleMicrotask(() {
PaintingBinding.instance.imageCache.evict(key);
});
});
}
@override
Future<ResizeImageKey> obtainKey(ImageConfiguration configuration) {
Completer<ResizeImageKey>? completer;
// If the imageProvider.obtainKey future is synchronous, then we will be able to fill in result with
// a value before completer is initialized below.
SynchronousFuture<ResizeImageKey>? result;
imageProvider.obtainKey(configuration).then((Object key) {
if (completer == null) {
// This future has completed synchronously (completer was never assigned),
// so we can directly create the synchronous result to return.
result = SynchronousFuture<ResizeImageKey>(ResizeImageKey._(key, policy, width, height, allowUpscaling));
} else {
// This future did not synchronously complete.
completer.complete(ResizeImageKey._(key, policy, width, height, allowUpscaling));
}
});
if (result != null) {
return result!;
}
// If the code reaches here, it means the imageProvider.obtainKey was not
// completed sync, so we initialize the completer for completion later.
completer = Completer<ResizeImageKey>();
return completer.future;
}
}
/// Fetches the given URL from the network, associating it with the given scale.
///
/// The image will be cached regardless of cache headers from the server.
///
/// When a network image is used on the Web platform, the `getTargetSize`
/// parameter of the [ImageDecoderCallback] is 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.
///
/// See also:
///
/// * [Image.network] for a shorthand of an [Image] widget backed by [NetworkImage].
/// * The example at [ImageProvider], which shows a custom variant of this class
/// that applies different logic for fetching the image.
// TODO(ianh): Find some way to honor cache headers to the extent that when the
// last reference to an image is released, we proactively evict the image from
// our cache if the headers describe the image as having expired at that point.
abstract class NetworkImage extends ImageProvider<NetworkImage> {
/// Creates an object that fetches the image at the given URL.
///
/// The [scale] argument is the linear scale factor for drawing this image at
/// its intended size. See [ImageInfo.scale] for more information.
const factory NetworkImage(String url, { double scale, Map<String, String>? headers }) = network_image.NetworkImage;
/// The URL from which the image will be fetched.
String get url;
/// The scale to place in the [ImageInfo] object of the image.
double get scale;
/// The HTTP headers that will be used with [HttpClient.get] to fetch image from network.
///
/// When running Flutter on the web, headers are not used.
Map<String, String>? get headers;
@override
ImageStreamCompleter loadBuffer(NetworkImage key, DecoderBufferCallback decode);
@override
ImageStreamCompleter loadImage(NetworkImage key, ImageDecoderCallback decode);
}
/// Decodes the given [File] object as an image, associating it with the given
/// scale.
///
/// The provider does not monitor the file for changes. If you expect the
/// underlying data to change, you should call the [evict] method.
///
/// See also:
///
/// * [Image.file] for a shorthand of an [Image] widget backed by [FileImage].
@immutable
class FileImage extends ImageProvider<FileImage> {
/// Creates an object that decodes a [File] as an image.
const FileImage(this.file, { this.scale = 1.0 });
/// The file to decode into an image.
final File file;
/// The scale to place in the [ImageInfo] object of the image.
final double scale;
@override
Future<FileImage> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<FileImage>(this);
}
@override
ImageStreamCompleter loadBuffer(FileImage key, DecoderBufferCallback decode) {
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key, decode: decode),
scale: key.scale,
debugLabel: key.file.path,
informationCollector: () => <DiagnosticsNode>[
ErrorDescription('Path: ${file.path}'),
],
);
}
@override
@protected
ImageStreamCompleter loadImage(FileImage key, ImageDecoderCallback decode) {
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key, decode: decode),
scale: key.scale,
debugLabel: key.file.path,
informationCollector: () => <DiagnosticsNode>[
ErrorDescription('Path: ${file.path}'),
],
);
}
Future<ui.Codec> _loadAsync(
FileImage key, {
required _SimpleDecoderCallback decode,
}) async {
assert(key == this);
// TODO(jonahwilliams): making this sync caused test failures that seem to
// indicate that we can fail to call evict unless at least one await has
// occurred in the test.
// https://github.com/flutter/flutter/issues/113044
final int lengthInBytes = await file.length();
if (lengthInBytes == 0) {
// The file may become available later.
PaintingBinding.instance.imageCache.evict(key);
throw StateError('$file is empty and cannot be loaded as an image.');
}
return (file.runtimeType == File)
? decode(await ui.ImmutableBuffer.fromFilePath(file.path))
: decode(await ui.ImmutableBuffer.fromUint8List(await file.readAsBytes()));
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is FileImage
&& other.file.path == file.path
&& other.scale == scale;
}
@override
int get hashCode => Object.hash(file.path, scale);
@override
String toString() => '${objectRuntimeType(this, 'FileImage')}("${file.path}", scale: ${scale.toStringAsFixed(1)})';
}
/// Decodes the given [Uint8List] buffer as an image, associating it with the
/// given scale.
///
/// The provided [bytes] buffer should not be changed after it is provided
/// to a [MemoryImage]. To provide an [ImageStream] that represents an image
/// that changes over time, consider creating a new subclass of [ImageProvider]
/// whose [loadImage] method returns a subclass of [ImageStreamCompleter] that
/// can handle providing multiple images.
///
/// See also:
///
/// * [Image.memory] for a shorthand of an [Image] widget backed by [MemoryImage].
@immutable
class MemoryImage extends ImageProvider<MemoryImage> {
/// Creates an object that decodes a [Uint8List] buffer as an image.
const MemoryImage(this.bytes, { this.scale = 1.0 });
/// The bytes to decode into an image.
///
/// The bytes represent encoded image bytes and can be encoded in any of the
/// following supported image formats: {@macro dart.ui.imageFormats}
///
/// See also:
///
/// * [PaintingBinding.instantiateImageCodecWithSize]
final Uint8List bytes;
/// The scale to place in the [ImageInfo] object of the image.
///
/// See also:
///
/// * [ImageInfo.scale], which gives more information on how this scale is
/// applied.
final double scale;
@override
Future<MemoryImage> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<MemoryImage>(this);
}
@override
ImageStreamCompleter loadBuffer(MemoryImage key, DecoderBufferCallback decode) {
assert(key == this);
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key, decode: decode),
scale: key.scale,
debugLabel: 'MemoryImage(${describeIdentity(key.bytes)})',
);
}
@override
ImageStreamCompleter loadImage(MemoryImage key, ImageDecoderCallback decode) {
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key, decode: decode),
scale: key.scale,
debugLabel: 'MemoryImage(${describeIdentity(key.bytes)})',
);
}
Future<ui.Codec> _loadAsync(
MemoryImage key, {
required _SimpleDecoderCallback decode,
}) async {
assert(key == this);
return decode(await ui.ImmutableBuffer.fromUint8List(bytes));
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is MemoryImage
&& other.bytes == bytes
&& other.scale == scale;
}
@override
int get hashCode => Object.hash(bytes.hashCode, scale);
@override
String toString() => '${objectRuntimeType(this, 'MemoryImage')}(${describeIdentity(bytes)}, scale: ${scale.toStringAsFixed(1)})';
}
/// Fetches an image from an [AssetBundle], associating it with the given scale.
///
/// This implementation requires an explicit final [assetName] and [scale] on
/// construction, and ignores the device pixel ratio and size in the
/// configuration passed into [resolve]. For a resolution-aware variant that
/// uses the configuration to pick an appropriate image based on the device
/// pixel ratio and size, see [AssetImage].
///
/// ## Fetching assets
///
/// When fetching an image provided by the app itself, use the [assetName]
/// argument to name the asset to choose. For instance, consider a directory
/// `icons` with an image `heart.png`. First, the `pubspec.yaml` of the project
/// should specify its assets in the `flutter` section:
///
/// ```yaml
/// flutter:
/// assets:
/// - icons/heart.png
/// ```
///
/// Then, to fetch the image and associate it with scale `1.5`, use:
///
/// {@tool snippet}
/// ```dart
/// const ExactAssetImage('icons/heart.png', scale: 1.5)
/// ```
/// {@end-tool}
///
/// ## Assets in packages
///
/// To fetch an asset from a package, the [package] argument must be provided.
/// For instance, suppose the structure above is inside a package called
/// `my_icons`. Then to fetch the image, use:
///
/// {@tool snippet}
/// ```dart
/// const ExactAssetImage('icons/heart.png', scale: 1.5, package: 'my_icons')
/// ```
/// {@end-tool}
///
/// Assets used by the package itself should also be fetched 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:
///
/// * [Image.asset] for a shorthand of an [Image] widget backed by
/// [ExactAssetImage] when using a scale.
@immutable
class ExactAssetImage extends AssetBundleImageProvider {
/// Creates an object that fetches the given image from an asset bundle.
///
/// The [scale] argument defaults to 1. The [bundle] argument may be null, in
/// which case the bundle provided in the [ImageConfiguration] passed to the
/// [resolve] call will be used instead.
///
/// The [package] argument must be non-null when fetching an asset that is
/// included in a package. See the documentation for the [ExactAssetImage] class
/// itself for details.
const ExactAssetImage(
this.assetName, {
this.scale = 1.0,
this.bundle,
this.package,
});
/// The name of the asset.
final String assetName;
/// The key to use to obtain the resource from the [bundle]. This is the
/// argument passed to [AssetBundle.load].
String get keyName => package == null ? assetName : 'packages/$package/$assetName';
/// The scale to place in the [ImageInfo] object of the image.
final double scale;
/// The bundle from which the image will be obtained.
///
/// If the provided [bundle] is null, the bundle provided in the
/// [ImageConfiguration] passed to the [resolve] call will be used instead. If
/// that is also null, the [rootBundle] is used.
///
/// The image is obtained by calling [AssetBundle.load] on the given [bundle]
/// using the key given by [keyName].
final AssetBundle? bundle;
/// The name of the package from which the image is included. See the
/// documentation for the [ExactAssetImage] class itself for details.
final String? package;
@override
Future<AssetBundleImageKey> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<AssetBundleImageKey>(AssetBundleImageKey(
bundle: bundle ?? configuration.bundle ?? rootBundle,
name: keyName,
scale: scale,
));
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is ExactAssetImage
&& other.keyName == keyName
&& other.scale == scale
&& other.bundle == bundle;
}
@override
int get hashCode => Object.hash(keyName, scale, bundle);
@override
String toString() => '${objectRuntimeType(this, 'ExactAssetImage')}(name: "$keyName", scale: ${scale.toStringAsFixed(1)}, bundle: $bundle)';
}
// A completer used when resolving an image fails sync.
class _ErrorImageCompleter extends ImageStreamCompleter { }
/// The exception thrown when the HTTP request to load a network image fails.
class NetworkImageLoadException implements Exception {
/// Creates a [NetworkImageLoadException] with the specified http [statusCode]
/// and [uri].
NetworkImageLoadException({required this.statusCode, required this.uri})
: _message = 'HTTP request failed, statusCode: $statusCode, $uri';
/// The HTTP status code from the server.
final int statusCode;
/// A human-readable error message.
final String _message;
/// Resolved URL of the requested image.
final Uri uri;
@override
String toString() => _message;
}
| flutter/packages/flutter/lib/src/painting/image_provider.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/image_provider.dart",
"repo_id": "flutter",
"token_count": 19488
} | 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:math' show max;
import 'dart:ui' as ui show
BoxHeightStyle,
BoxWidthStyle,
GlyphInfo,
LineMetrics,
Paragraph,
ParagraphBuilder,
ParagraphConstraints,
ParagraphStyle,
PlaceholderAlignment,
TextStyle;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'basic_types.dart';
import 'inline_span.dart';
import 'placeholder_span.dart';
import 'strut_style.dart';
import 'text_scaler.dart';
import 'text_span.dart';
import 'text_style.dart';
export 'dart:ui' show LineMetrics;
export 'package:flutter/services.dart' show TextRange, TextSelection;
/// The default font size if none is specified.
///
/// This should be kept in sync with the defaults set in the engine (e.g.,
/// LibTxt's text_style.h, paragraph_style.h).
const double kDefaultFontSize = 14.0;
/// How overflowing text should be handled.
///
/// A [TextOverflow] can be passed to [Text] and [RichText] via their
/// [Text.overflow] and [RichText.overflow] properties respectively.
enum TextOverflow {
/// Clip the overflowing text to fix its container.
clip,
/// Fade the overflowing text to transparent.
fade,
/// Use an ellipsis to indicate that the text has overflowed.
ellipsis,
/// Render overflowing text outside of its container.
visible,
}
/// Holds the [Size] and baseline required to represent the dimensions of
/// a placeholder in text.
///
/// Placeholders specify an empty space in the text layout, which is used
/// to later render arbitrary inline widgets into defined by a [WidgetSpan].
///
/// See also:
///
/// * [WidgetSpan], a subclass of [InlineSpan] and [PlaceholderSpan] that
/// represents an inline widget embedded within text. The space this
/// widget takes is indicated by a placeholder.
/// * [RichText], a text widget that supports text inline widgets.
@immutable
class PlaceholderDimensions {
/// Constructs a [PlaceholderDimensions] with the specified parameters.
///
/// The `size` and `alignment` are required as a placeholder's dimensions
/// require at least `size` and `alignment` to be fully defined.
const PlaceholderDimensions({
required this.size,
required this.alignment,
this.baseline,
this.baselineOffset,
});
/// A constant representing an empty placeholder.
static const PlaceholderDimensions empty = PlaceholderDimensions(size: Size.zero, alignment: ui.PlaceholderAlignment.bottom);
/// Width and height dimensions of the placeholder.
final Size size;
/// How to align the placeholder with the text.
///
/// See also:
///
/// * [baseline], the baseline to align to when using
/// [dart:ui.PlaceholderAlignment.baseline],
/// [dart:ui.PlaceholderAlignment.aboveBaseline],
/// or [dart:ui.PlaceholderAlignment.belowBaseline].
/// * [baselineOffset], the distance of the alphabetic baseline from the upper
/// edge of the placeholder.
final ui.PlaceholderAlignment alignment;
/// Distance of the [baseline] from the upper edge of the placeholder.
///
/// Only used when [alignment] is [ui.PlaceholderAlignment.baseline].
final double? baselineOffset;
/// The [TextBaseline] to align to. Used with:
///
/// * [ui.PlaceholderAlignment.baseline]
/// * [ui.PlaceholderAlignment.aboveBaseline]
/// * [ui.PlaceholderAlignment.belowBaseline]
/// * [ui.PlaceholderAlignment.middle]
final TextBaseline? baseline;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is PlaceholderDimensions
&& other.size == size
&& other.alignment == alignment
&& other.baseline == baseline
&& other.baselineOffset == baselineOffset;
}
@override
int get hashCode => Object.hash(size, alignment, baseline, baselineOffset);
@override
String toString() {
return switch (alignment) {
ui.PlaceholderAlignment.top ||
ui.PlaceholderAlignment.bottom ||
ui.PlaceholderAlignment.middle ||
ui.PlaceholderAlignment.aboveBaseline ||
ui.PlaceholderAlignment.belowBaseline => 'PlaceholderDimensions($size, $alignment)',
ui.PlaceholderAlignment.baseline => 'PlaceholderDimensions($size, $alignment($baselineOffset from top))',
};
}
}
/// The different ways of measuring the width of one or more lines of text.
///
/// See [Text.textWidthBasis], for example.
enum TextWidthBasis {
/// multiline text will take up the full width given by the parent. For single
/// line text, only the minimum amount of width needed to contain the text
/// will be used. A common use case for this is a standard series of
/// paragraphs.
parent,
/// The width will be exactly enough to contain the longest line and no
/// longer. A common use case for this is chat bubbles.
longestLine,
}
/// A [TextBoundary] subclass for locating word breaks.
///
/// The underlying implementation uses [UAX #29](https://unicode.org/reports/tr29/)
/// defined default word boundaries.
///
/// The default word break rules can be tailored to meet the requirements of
/// different use cases. For instance, the default rule set keeps horizontal
/// whitespaces together as a single word, which may not make sense in a
/// word-counting context -- "hello world" counts as 3 words instead of 2.
/// An example is the [moveByWordBoundary] variant, which is a tailored
/// word-break locator that more closely matches the default behavior of most
/// platforms and editors when it comes to handling text editing keyboard
/// shortcuts that move or delete word by word.
class WordBoundary extends TextBoundary {
/// Creates a [WordBoundary] with the text and layout information.
WordBoundary._(this._text, this._paragraph);
final InlineSpan _text;
final ui.Paragraph _paragraph;
@override
TextRange getTextBoundaryAt(int position) => _paragraph.getWordBoundary(TextPosition(offset: max(position, 0)));
// Combines two UTF-16 code units (high surrogate + low surrogate) into a
// single code point that represents a supplementary character.
static int _codePointFromSurrogates(int highSurrogate, int lowSurrogate) {
assert(
TextPainter.isHighSurrogate(highSurrogate),
'U+${highSurrogate.toRadixString(16).toUpperCase().padLeft(4, "0")}) is not a high surrogate.',
);
assert(
TextPainter.isLowSurrogate(lowSurrogate),
'U+${lowSurrogate.toRadixString(16).toUpperCase().padLeft(4, "0")}) is not a low surrogate.',
);
const int base = 0x010000 - (0xD800 << 10) - 0xDC00;
return (highSurrogate << 10) + lowSurrogate + base;
}
// The Runes class does not provide random access with a code unit offset.
int? _codePointAt(int index) {
final int? codeUnitAtIndex = _text.codeUnitAt(index);
if (codeUnitAtIndex == null) {
return null;
}
return switch (codeUnitAtIndex & 0xFC00) {
0xD800 => _codePointFromSurrogates(codeUnitAtIndex, _text.codeUnitAt(index + 1)!),
0xDC00 => _codePointFromSurrogates(_text.codeUnitAt(index - 1)!, codeUnitAtIndex),
_ => codeUnitAtIndex,
};
}
static bool _isNewline(int codePoint) {
// Carriage Return is not treated as a hard line break.
return switch (codePoint) {
0x000A || // Line Feed
0x0085 || // New Line
0x000B || // Form Feed
0x000C || // Vertical Feed
0x2028 || // Line Separator
0x2029 => true, // Paragraph Separator
_ => false,
};
}
bool _skipSpacesAndPunctuations(int offset, bool forward) {
// Use code point since some punctuations are supplementary characters.
// "inner" here refers to the code unit that's before the break in the
// search direction (`forward`).
final int? innerCodePoint = _codePointAt(forward ? offset - 1 : offset);
final int? outerCodeUnit = _text.codeUnitAt(forward ? offset : offset - 1);
// Make sure the hard break rules in UAX#29 take precedence over the ones we
// add below. Luckily there're only 4 hard break rules for word breaks, and
// dictionary based breaking does not introduce new hard breaks:
// https://unicode-org.github.io/icu/userguide/boundaryanalysis/break-rules.html#word-dictionaries
//
// WB1 & WB2: always break at the start or the end of the text.
final bool hardBreakRulesApply = innerCodePoint == null || outerCodeUnit == null
// WB3a & WB3b: always break before and after newlines.
|| _isNewline(innerCodePoint) || _isNewline(outerCodeUnit);
return hardBreakRulesApply || !RegExp(r'[\p{Space_Separator}\p{Punctuation}]', unicode: true).hasMatch(String.fromCharCode(innerCodePoint));
}
/// Returns a [TextBoundary] suitable for handling keyboard navigation
/// commands that change the current selection word by word.
///
/// This [TextBoundary] is used by text widgets in the flutter framework to
/// provide default implementation for text editing shortcuts, for example,
/// "delete to the previous word".
///
/// The implementation applies the same set of rules [WordBoundary] uses,
/// except that word breaks end on a space separator or a punctuation will be
/// skipped, to match the behavior of most platforms. Additional rules may be
/// added in the future to better match platform behaviors.
late final TextBoundary moveByWordBoundary = _UntilTextBoundary(this, _skipSpacesAndPunctuations);
}
class _UntilTextBoundary extends TextBoundary {
const _UntilTextBoundary(this._textBoundary, this._predicate);
final UntilPredicate _predicate;
final TextBoundary _textBoundary;
@override
int? getLeadingTextBoundaryAt(int position) {
if (position < 0) {
return null;
}
final int? offset = _textBoundary.getLeadingTextBoundaryAt(position);
return offset == null || _predicate(offset, false)
? offset
: getLeadingTextBoundaryAt(offset - 1);
}
@override
int? getTrailingTextBoundaryAt(int position) {
final int? offset = _textBoundary.getTrailingTextBoundaryAt(max(position, 0));
return offset == null || _predicate(offset, true)
? offset
: getTrailingTextBoundaryAt(offset);
}
}
class _TextLayout {
_TextLayout._(this._paragraph, this.writingDirection, this.rawString);
final TextDirection writingDirection;
final String rawString;
// This field is not final because the owner TextPainter could create a new
// ui.Paragraph with the exact same text layout (for example, when only the
// color of the text is changed).
//
// The creator of this _TextLayout is also responsible for disposing this
// object when it's no longer needed.
ui.Paragraph _paragraph;
/// Whether this layout has been invalidated and disposed.
///
/// Only for use when asserts are enabled.
bool get debugDisposed => _paragraph.debugDisposed;
/// The horizontal space required to paint this text.
///
/// If a line ends with trailing spaces, the trailing spaces may extend
/// outside of the horizontal paint bounds defined by [width].
double get width => _paragraph.width;
/// The vertical space required to paint this text.
double get height => _paragraph.height;
/// The width at which decreasing the width of the text would prevent it from
/// painting itself completely within its bounds.
double get minIntrinsicLineExtent => _paragraph.minIntrinsicWidth;
/// The width at which increasing the width of the text no longer decreases the height.
///
/// Includes trailing spaces if any.
double get maxIntrinsicLineExtent => _paragraph.maxIntrinsicWidth;
/// The distance from the left edge of the leftmost glyph to the right edge of
/// the rightmost glyph in the paragraph.
double get longestLine => _paragraph.longestLine;
/// Returns the distance from the top of the text to the first baseline of the
/// given type.
double getDistanceToBaseline(TextBaseline baseline) {
return switch (baseline) {
TextBaseline.alphabetic => _paragraph.alphabeticBaseline,
TextBaseline.ideographic => _paragraph.ideographicBaseline,
};
}
/// The line caret metrics representing the end of text location.
///
/// This is usually used when the caret is placed at the end of the text
/// (text.length, downstream), unless maxLines is set to a non-null value, in
/// which case the caret is placed at the visual end of the last visible line.
///
/// This should not be called when the paragraph is empty as the implementation
/// relies on line metrics.
///
/// When the last bidi level run in the paragraph and the paragraph's bidi
/// levels have opposite parities (which implies opposite writing directions),
/// this makes sure the caret is placed at the same "end" of the line as if the
/// line ended with a line feed.
late final _LineCaretMetrics _endOfTextCaretMetrics = _computeEndOfTextCaretAnchorOffset();
_LineCaretMetrics _computeEndOfTextCaretAnchorOffset() {
final int lastLineIndex = _paragraph.numberOfLines - 1;
assert(lastLineIndex >= 0);
final ui.LineMetrics lineMetrics = _paragraph.getLineMetricsAt(lastLineIndex)!;
// SkParagraph currently treats " " and "\t" as white spaces. Trailing white
// spaces don't contribute to the line width and thus require special handling
// when they're present.
// Luckily they have the same bidi embedding level as the paragraph as per
// https://unicode.org/reports/tr9/#L1, so we can anchor the caret to the
// last logical trailing space.
final bool hasTrailingSpaces = switch (rawString.codeUnitAt(rawString.length - 1)) {
0x9 || // horizontal tab
0x20 => true, // space
_ => false,
};
final double baseline = lineMetrics.baseline;
final double dx;
late final ui.GlyphInfo? lastGlyph = _paragraph.getGlyphInfoAt(rawString.length - 1);
// TODO(LongCatIsLooong): handle the case where maxLine is set to non-null
// and the last line ends with trailing whitespaces.
if (hasTrailingSpaces && lastGlyph != null) {
final Rect glyphBounds = lastGlyph.graphemeClusterLayoutBounds;
assert(!glyphBounds.isEmpty);
dx = switch (writingDirection) {
TextDirection.ltr => glyphBounds.right,
TextDirection.rtl => glyphBounds.left,
};
} else {
dx = switch (writingDirection) {
TextDirection.ltr => lineMetrics.left + lineMetrics.width,
TextDirection.rtl => lineMetrics.left,
};
}
return _LineCaretMetrics(offset: Offset(dx, baseline), writingDirection: writingDirection);
}
double _contentWidthFor(double minWidth, double maxWidth, TextWidthBasis widthBasis) {
return switch (widthBasis) {
TextWidthBasis.longestLine => clampDouble(longestLine, minWidth, maxWidth),
TextWidthBasis.parent => clampDouble(maxIntrinsicLineExtent, minWidth, maxWidth),
};
}
}
// This class stores the current text layout and the corresponding
// paintOffset/contentWidth, as well as some cached text metrics values that
// depends on the current text layout, which will be invalidated as soon as the
// text layout is invalidated.
class _TextPainterLayoutCacheWithOffset {
_TextPainterLayoutCacheWithOffset(this.layout, this.textAlignment, this.layoutMaxWidth, this.contentWidth)
: assert(textAlignment >= 0.0 && textAlignment <= 1.0),
assert(!layoutMaxWidth.isNaN),
assert(!contentWidth.isNaN);
final _TextLayout layout;
// The input width used to lay out the paragraph.
final double layoutMaxWidth;
// The content width the text painter should report in TextPainter.width.
// This is also used to compute `paintOffset`.
double contentWidth;
// The effective text alignment in the TextPainter's canvas. The value is
// within the [0, 1] interval: 0 for left aligned and 1 for right aligned.
final double textAlignment;
// The paintOffset of the `paragraph` in the TextPainter's canvas.
//
// It's coordinate values are guaranteed to not be NaN.
Offset get paintOffset {
if (textAlignment == 0) {
return Offset.zero;
}
if (!paragraph.width.isFinite) {
return const Offset(double.infinity, 0.0);
}
final double dx = textAlignment * (contentWidth - paragraph.width);
assert(!dx.isNaN);
return Offset(dx, 0);
}
ui.Paragraph get paragraph => layout._paragraph;
// Try to resize the contentWidth to fit the new input constraints, by just
// adjusting the paint offset (so no line-breaking changes needed).
//
// Returns false if the new constraints require the text layout library to
// re-compute the line breaks.
bool _resizeToFit(double minWidth, double maxWidth, TextWidthBasis widthBasis) {
assert(layout.maxIntrinsicLineExtent.isFinite);
assert(minWidth <= maxWidth);
// The assumption here is that if a Paragraph's width is already >= its
// maxIntrinsicWidth, further increasing the input width does not change its
// layout (but may change the paint offset if it's not left-aligned). This is
// true even for TextAlign.justify: when width >= maxIntrinsicWidth
// TextAlign.justify will behave exactly the same as TextAlign.start.
//
// An exception to this is when the text is not left-aligned, and the input
// width is double.infinity. Since the resulting Paragraph will have a width
// of double.infinity, and to make the text visible the paintOffset.dx is
// bound to be double.negativeInfinity, which invalidates all arithmetic
// operations.
if (maxWidth == contentWidth && minWidth == contentWidth) {
contentWidth = layout._contentWidthFor(minWidth, maxWidth, widthBasis);
return true;
}
// Special case:
// When the paint offset and the paragraph width are both +∞, it's likely
// that the text layout engine skipped layout because there weren't anything
// to paint. Always try to re-compute the text layout.
if (!paintOffset.dx.isFinite && !paragraph.width.isFinite && minWidth.isFinite) {
assert(paintOffset.dx == double.infinity);
assert(paragraph.width == double.infinity);
return false;
}
final double maxIntrinsicWidth = paragraph.maxIntrinsicWidth;
// Skip line breaking if the input width remains the same, of there will be
// no soft breaks.
final bool skipLineBreaking = maxWidth == layoutMaxWidth // Same input max width so relayout is unnecessary.
|| ((paragraph.width - maxIntrinsicWidth) > -precisionErrorTolerance && (maxWidth - maxIntrinsicWidth) > -precisionErrorTolerance);
if (skipLineBreaking) {
// Adjust the content width in case the TextWidthBasis changed.
contentWidth = layout._contentWidthFor(minWidth, maxWidth, widthBasis);
return true;
}
return false;
}
// ---- Cached Values ----
List<TextBox> get inlinePlaceholderBoxes => _cachedInlinePlaceholderBoxes ??= paragraph.getBoxesForPlaceholders();
List<TextBox>? _cachedInlinePlaceholderBoxes;
List<ui.LineMetrics> get lineMetrics => _cachedLineMetrics ??= paragraph.computeLineMetrics();
List<ui.LineMetrics>? _cachedLineMetrics;
// Used to determine whether the caret metrics cache should be invalidated.
int? _previousCaretPositionKey;
}
/// The _CaretMetrics for carets located in a non-empty paragraph. Such carets
/// are anchored to the trailing edge or the leading edge of a glyph, or a
/// ligature component.
final class _LineCaretMetrics {
const _LineCaretMetrics({required this.offset, required this.writingDirection});
/// The offset from the top left corner of the paragraph to the caret's top
/// start location.
final Offset offset;
/// The writing direction of the glyph the _LineCaretMetrics is associated with.
/// The value determines whether the cursor is painted to the left or to the
/// right of [offset].
final TextDirection writingDirection;
_LineCaretMetrics shift(Offset offset) {
return offset == Offset.zero
? this
: _LineCaretMetrics(offset: offset + this.offset, writingDirection: writingDirection);
}
}
const String _flutterPaintingLibrary = 'package:flutter/painting.dart';
/// An object that paints a [TextSpan] tree into a [Canvas].
///
/// To use a [TextPainter], follow these steps:
///
/// 1. Create a [TextSpan] tree and pass it to the [TextPainter]
/// constructor.
///
/// 2. Call [layout] to prepare the paragraph.
///
/// 3. Call [paint] as often as desired to paint the paragraph.
///
/// 4. Call [dispose] when the object will no longer be accessed to release
/// native resources. For [TextPainter] objects that are used repeatedly and
/// stored on a [State] or [RenderObject], call [dispose] from
/// [State.dispose] or [RenderObject.dispose] or similar. For [TextPainter]
/// objects that are only used ephemerally, it is safe to immediately dispose
/// them after the last call to methods or properties on the object.
///
/// If the width of the area into which the text is being painted
/// changes, return to step 2. If the text to be painted changes,
/// return to step 1.
///
/// The default text style is white. To change the color of the text,
/// pass a [TextStyle] object to the [TextSpan] in `text`.
class TextPainter {
/// Creates a text painter that paints the given text.
///
/// The `text` and `textDirection` arguments are optional but [text] and
/// [textDirection] must be non-null before calling [layout].
///
/// The [maxLines] property, if non-null, must be greater than zero.
TextPainter({
InlineSpan? text,
TextAlign textAlign = TextAlign.start,
TextDirection? textDirection,
@Deprecated(
'Use textScaler instead. '
'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
'This feature was deprecated after v3.12.0-2.0.pre.',
)
double textScaleFactor = 1.0,
TextScaler textScaler = TextScaler.noScaling,
int? maxLines,
String? ellipsis,
Locale? locale,
StrutStyle? strutStyle,
TextWidthBasis textWidthBasis = TextWidthBasis.parent,
TextHeightBehavior? textHeightBehavior,
}) : assert(text == null || text.debugAssertIsValid()),
assert(maxLines == null || maxLines > 0),
assert(textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling), 'Use textScaler instead.'),
_text = text,
_textAlign = textAlign,
_textDirection = textDirection,
_textScaler = textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler,
_maxLines = maxLines,
_ellipsis = ellipsis,
_locale = locale,
_strutStyle = strutStyle,
_textWidthBasis = textWidthBasis,
_textHeightBehavior = textHeightBehavior {
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectCreated(
library: _flutterPaintingLibrary,
className: '$TextPainter',
object: this,
);
}
}
/// Computes the width of a configured [TextPainter].
///
/// This is a convenience method that creates a text painter with the supplied
/// parameters, lays it out with the supplied [minWidth] and [maxWidth], and
/// returns its [TextPainter.width] making sure to dispose the underlying
/// resources. Doing this operation is expensive and should be avoided
/// whenever it is possible to preserve the [TextPainter] to paint the
/// text or get other information about it.
static double computeWidth({
required InlineSpan text,
required TextDirection textDirection,
TextAlign textAlign = TextAlign.start,
@Deprecated(
'Use textScaler instead. '
'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
'This feature was deprecated after v3.12.0-2.0.pre.',
)
double textScaleFactor = 1.0,
TextScaler textScaler = TextScaler.noScaling,
int? maxLines,
String? ellipsis,
Locale? locale,
StrutStyle? strutStyle,
TextWidthBasis textWidthBasis = TextWidthBasis.parent,
TextHeightBehavior? textHeightBehavior,
double minWidth = 0.0,
double maxWidth = double.infinity,
}) {
assert(
textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling),
'Use textScaler instead.',
);
final TextPainter painter = TextPainter(
text: text,
textAlign: textAlign,
textDirection: textDirection,
textScaler: textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler,
maxLines: maxLines,
ellipsis: ellipsis,
locale: locale,
strutStyle: strutStyle,
textWidthBasis: textWidthBasis,
textHeightBehavior: textHeightBehavior,
)..layout(minWidth: minWidth, maxWidth: maxWidth);
try {
return painter.width;
} finally {
painter.dispose();
}
}
/// Computes the max intrinsic width of a configured [TextPainter].
///
/// This is a convenience method that creates a text painter with the supplied
/// parameters, lays it out with the supplied [minWidth] and [maxWidth], and
/// returns its [TextPainter.maxIntrinsicWidth] making sure to dispose the
/// underlying resources. Doing this operation is expensive and should be avoided
/// whenever it is possible to preserve the [TextPainter] to paint the
/// text or get other information about it.
static double computeMaxIntrinsicWidth({
required InlineSpan text,
required TextDirection textDirection,
TextAlign textAlign = TextAlign.start,
@Deprecated(
'Use textScaler instead. '
'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
'This feature was deprecated after v3.12.0-2.0.pre.',
)
double textScaleFactor = 1.0,
TextScaler textScaler = TextScaler.noScaling,
int? maxLines,
String? ellipsis,
Locale? locale,
StrutStyle? strutStyle,
TextWidthBasis textWidthBasis = TextWidthBasis.parent,
TextHeightBehavior? textHeightBehavior,
double minWidth = 0.0,
double maxWidth = double.infinity,
}) {
assert(
textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling),
'Use textScaler instead.',
);
final TextPainter painter = TextPainter(
text: text,
textAlign: textAlign,
textDirection: textDirection,
textScaler: textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler,
maxLines: maxLines,
ellipsis: ellipsis,
locale: locale,
strutStyle: strutStyle,
textWidthBasis: textWidthBasis,
textHeightBehavior: textHeightBehavior,
)..layout(minWidth: minWidth, maxWidth: maxWidth);
try {
return painter.maxIntrinsicWidth;
} finally {
painter.dispose();
}
}
// Whether textWidthBasis has changed after the most recent `layout` call.
bool _debugNeedsRelayout = true;
// The result of the most recent `layout` call.
_TextPainterLayoutCacheWithOffset? _layoutCache;
// Whether _layoutCache contains outdated paint information and needs to be
// updated before painting.
//
// ui.Paragraph is entirely immutable, thus text style changes that can affect
// layout and those who can't both require the ui.Paragraph object being
// recreated. The caller may not call `layout` again after text color is
// updated. See: https://github.com/flutter/flutter/issues/85108
bool _rebuildParagraphForPaint = true;
bool get _debugAssertTextLayoutIsValid {
assert(!debugDisposed);
if (_layoutCache == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Text layout not available'),
if (_debugMarkNeedsLayoutCallStack != null) DiagnosticsStackTrace('The calls that first invalidated the text layout were', _debugMarkNeedsLayoutCallStack)
else ErrorDescription('The TextPainter has never been laid out.')
]);
}
return true;
}
StackTrace? _debugMarkNeedsLayoutCallStack;
/// Marks this text painter's layout information as dirty and removes cached
/// information.
///
/// Uses this method to notify text painter to relayout in the case of
/// layout changes in engine. In most cases, updating text painter properties
/// in framework will automatically invoke this method.
void markNeedsLayout() {
assert(() {
if (_layoutCache != null) {
_debugMarkNeedsLayoutCallStack ??= StackTrace.current;
}
return true;
}());
_layoutCache?.paragraph.dispose();
_layoutCache = null;
}
/// The (potentially styled) text to paint.
///
/// After this is set, you must call [layout] before the next call to [paint].
/// This and [textDirection] must be non-null before you call [layout].
///
/// The [InlineSpan] this provides is in the form of a tree that may contain
/// multiple instances of [TextSpan]s and [WidgetSpan]s. To obtain a plain text
/// representation of the contents of this [TextPainter], use [plainText].
InlineSpan? get text => _text;
InlineSpan? _text;
set text(InlineSpan? value) {
assert(value == null || value.debugAssertIsValid());
if (_text == value) {
return;
}
if (_text?.style != value?.style) {
_layoutTemplate?.dispose();
_layoutTemplate = null;
}
final RenderComparison comparison = value == null
? RenderComparison.layout
: _text?.compareTo(value) ?? RenderComparison.layout;
_text = value;
_cachedPlainText = null;
if (comparison.index >= RenderComparison.layout.index) {
markNeedsLayout();
} else if (comparison.index >= RenderComparison.paint.index) {
// Don't invalid the _layoutCache just yet. It still contains valid layout
// information.
_rebuildParagraphForPaint = true;
}
// Neither relayout or repaint is needed.
}
/// Returns a plain text version of the text to paint.
///
/// This uses [InlineSpan.toPlainText] to get the full contents of all nodes in the tree.
String get plainText {
_cachedPlainText ??= _text?.toPlainText(includeSemanticsLabels: false);
return _cachedPlainText ?? '';
}
String? _cachedPlainText;
/// How the text should be aligned horizontally.
///
/// After this is set, you must call [layout] before the next call to [paint].
///
/// The [textAlign] property defaults to [TextAlign.start].
TextAlign get textAlign => _textAlign;
TextAlign _textAlign;
set textAlign(TextAlign value) {
if (_textAlign == value) {
return;
}
_textAlign = value;
markNeedsLayout();
}
/// The default directionality of the text.
///
/// This controls how the [TextAlign.start], [TextAlign.end], and
/// [TextAlign.justify] values of [textAlign] are resolved.
///
/// This is also used to disambiguate how to render bidirectional text. For
/// example, if the [text] is an English phrase followed by a Hebrew phrase,
/// in a [TextDirection.ltr] context the English phrase will be on the left
/// and the Hebrew phrase to its right, while in a [TextDirection.rtl]
/// context, the English phrase will be on the right and the Hebrew phrase on
/// its left.
///
/// After this is set, you must call [layout] before the next call to [paint].
///
/// This and [text] must be non-null before you call [layout].
TextDirection? get textDirection => _textDirection;
TextDirection? _textDirection;
set textDirection(TextDirection? value) {
if (_textDirection == value) {
return;
}
_textDirection = value;
markNeedsLayout();
_layoutTemplate?.dispose();
_layoutTemplate = null; // Shouldn't really matter, but for strict correctness...
}
/// Deprecated. Will be removed in a future version of Flutter. Use
/// [textScaler] instead.
///
/// The number of font pixels for each logical pixel.
///
/// For example, if the text scale factor is 1.5, text will be 50% larger than
/// the specified font size.
///
/// After this is set, you must call [layout] before the next call to [paint].
@Deprecated(
'Use textScaler instead. '
'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
'This feature was deprecated after v3.12.0-2.0.pre.',
)
double get textScaleFactor => textScaler.textScaleFactor;
@Deprecated(
'Use textScaler instead. '
'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
'This feature was deprecated after v3.12.0-2.0.pre.',
)
set textScaleFactor(double value) {
textScaler = TextScaler.linear(value);
}
/// {@template flutter.painting.textPainter.textScaler}
/// The font scaling strategy to use when laying out and rendering the text.
///
/// The value usually comes from [MediaQuery.textScalerOf], which typically
/// reflects the user-specified text scaling value in the platform's
/// accessibility settings. The [TextStyle.fontSize] of the text will be
/// adjusted by the [TextScaler] before the text is laid out and rendered.
/// {@endtemplate}
///
/// The [layout] method must be called after [textScaler] changes as it
/// affects the text layout.
TextScaler get textScaler => _textScaler;
TextScaler _textScaler;
set textScaler(TextScaler value) {
if (value == _textScaler) {
return;
}
_textScaler = value;
markNeedsLayout();
_layoutTemplate?.dispose();
_layoutTemplate = null;
}
/// The string used to ellipsize overflowing text. Setting this to a non-empty
/// string will cause this string to be substituted for the remaining text
/// if the text can not fit within the specified maximum width.
///
/// Specifically, the ellipsis is applied to the last line before the line
/// truncated by [maxLines], if [maxLines] is non-null and that line overflows
/// the width constraint, or to the first line that is wider than the width
/// constraint, if [maxLines] is null. The width constraint is the `maxWidth`
/// passed to [layout].
///
/// After this is set, you must call [layout] before the next call to [paint].
///
/// The higher layers of the system, such as the [Text] widget, represent
/// overflow effects using the [TextOverflow] enum. The
/// [TextOverflow.ellipsis] value corresponds to setting this property to
/// U+2026 HORIZONTAL ELLIPSIS (…).
String? get ellipsis => _ellipsis;
String? _ellipsis;
set ellipsis(String? value) {
assert(value == null || value.isNotEmpty);
if (_ellipsis == value) {
return;
}
_ellipsis = value;
markNeedsLayout();
}
/// The locale used to select region-specific glyphs.
Locale? get locale => _locale;
Locale? _locale;
set locale(Locale? value) {
if (_locale == value) {
return;
}
_locale = value;
markNeedsLayout();
}
/// An optional maximum number of lines for the text to span, wrapping if
/// necessary.
///
/// If the text exceeds the given number of lines, it is truncated such that
/// subsequent lines are dropped.
///
/// After this is set, you must call [layout] before the next call to [paint].
int? get maxLines => _maxLines;
int? _maxLines;
/// The value may be null. If it is not null, then it must be greater than zero.
set maxLines(int? value) {
assert(value == null || value > 0);
if (_maxLines == value) {
return;
}
_maxLines = value;
markNeedsLayout();
}
/// {@template flutter.painting.textPainter.strutStyle}
/// The strut style to use. Strut style defines the strut, which sets minimum
/// vertical layout metrics.
///
/// Omitting or providing null will disable strut.
///
/// Omitting or providing null for any properties of [StrutStyle] will result in
/// default values being used. It is highly recommended to at least specify a
/// [StrutStyle.fontSize].
///
/// See [StrutStyle] for details.
/// {@endtemplate}
StrutStyle? get strutStyle => _strutStyle;
StrutStyle? _strutStyle;
set strutStyle(StrutStyle? value) {
if (_strutStyle == value) {
return;
}
_strutStyle = value;
markNeedsLayout();
}
/// {@template flutter.painting.textPainter.textWidthBasis}
/// Defines how to measure the width of the rendered text.
/// {@endtemplate}
TextWidthBasis get textWidthBasis => _textWidthBasis;
TextWidthBasis _textWidthBasis;
set textWidthBasis(TextWidthBasis value) {
if (_textWidthBasis == value) {
return;
}
assert(() { return _debugNeedsRelayout = true; }());
_textWidthBasis = value;
}
/// {@macro dart.ui.textHeightBehavior}
TextHeightBehavior? get textHeightBehavior => _textHeightBehavior;
TextHeightBehavior? _textHeightBehavior;
set textHeightBehavior(TextHeightBehavior? value) {
if (_textHeightBehavior == value) {
return;
}
_textHeightBehavior = value;
markNeedsLayout();
}
/// An ordered list of [TextBox]es that bound the positions of the placeholders
/// in the paragraph.
///
/// Each box corresponds to a [PlaceholderSpan] in the order they were defined
/// in the [InlineSpan] tree.
List<TextBox>? get inlinePlaceholderBoxes {
final _TextPainterLayoutCacheWithOffset? layout = _layoutCache;
if (layout == null) {
return null;
}
final Offset offset = layout.paintOffset;
if (!offset.dx.isFinite || !offset.dy.isFinite) {
return <TextBox>[];
}
final List<TextBox> rawBoxes = layout.inlinePlaceholderBoxes;
if (offset == Offset.zero) {
return rawBoxes;
}
return rawBoxes.map((TextBox box) => _shiftTextBox(box, offset)).toList(growable: false);
}
/// Sets the dimensions of each placeholder in [text].
///
/// The number of [PlaceholderDimensions] provided should be the same as the
/// number of [PlaceholderSpan]s in text. Passing in an empty or null `value`
/// will do nothing.
///
/// If [layout] is attempted without setting the placeholder dimensions, the
/// placeholders will be ignored in the text layout and no valid
/// [inlinePlaceholderBoxes] will be returned.
void setPlaceholderDimensions(List<PlaceholderDimensions>? value) {
if (value == null || value.isEmpty || listEquals(value, _placeholderDimensions)) {
return;
}
assert(() {
int placeholderCount = 0;
text!.visitChildren((InlineSpan span) {
if (span is PlaceholderSpan) {
placeholderCount += 1;
}
return value.length >= placeholderCount;
});
return placeholderCount == value.length;
}());
_placeholderDimensions = value;
markNeedsLayout();
}
List<PlaceholderDimensions>? _placeholderDimensions;
ui.ParagraphStyle _createParagraphStyle([ TextAlign? textAlignOverride ]) {
assert(textDirection != null, 'TextPainter.textDirection must be set to a non-null value before using the TextPainter.');
final TextStyle baseStyle = _text?.style ?? const TextStyle();
return baseStyle.getParagraphStyle(
textAlign: textAlignOverride ?? textAlign,
textDirection: textDirection,
textScaler: textScaler,
maxLines: _maxLines,
textHeightBehavior: _textHeightBehavior,
ellipsis: _ellipsis,
locale: _locale,
strutStyle: _strutStyle,
);
}
ui.Paragraph? _layoutTemplate;
ui.Paragraph _createLayoutTemplate() {
final ui.ParagraphBuilder builder = ui.ParagraphBuilder(
_createParagraphStyle(TextAlign.left),
); // direction doesn't matter, text is just a space
final ui.TextStyle? textStyle = text?.style?.getTextStyle(textScaler: textScaler);
if (textStyle != null) {
builder.pushStyle(textStyle);
}
builder.addText(' ');
return builder.build()
..layout(const ui.ParagraphConstraints(width: double.infinity));
}
ui.Paragraph _getOrCreateLayoutTemplate() => _layoutTemplate ??= _createLayoutTemplate();
/// The height of a space in [text] in logical pixels.
///
/// Not every line of text in [text] will have this height, but this height
/// is "typical" for text in [text] and useful for sizing other objects
/// relative a typical line of text.
///
/// Obtaining this value does not require calling [layout].
///
/// The style of the [text] property is used to determine the font settings
/// that contribute to the [preferredLineHeight]. If [text] is null or if it
/// specifies no styles, the default [TextStyle] values are used (a 10 pixel
/// sans-serif font).
double get preferredLineHeight => _getOrCreateLayoutTemplate().height;
/// The width at which decreasing the width of the text would prevent it from
/// painting itself completely within its bounds.
///
/// Valid only after [layout] has been called.
double get minIntrinsicWidth {
assert(_debugAssertTextLayoutIsValid);
return _layoutCache!.layout.minIntrinsicLineExtent;
}
/// The width at which increasing the width of the text no longer decreases the height.
///
/// Valid only after [layout] has been called.
double get maxIntrinsicWidth {
assert(_debugAssertTextLayoutIsValid);
return _layoutCache!.layout.maxIntrinsicLineExtent;
}
/// The horizontal space required to paint this text.
///
/// Valid only after [layout] has been called.
double get width {
assert(_debugAssertTextLayoutIsValid);
assert(!_debugNeedsRelayout);
return _layoutCache!.contentWidth;
}
/// The vertical space required to paint this text.
///
/// Valid only after [layout] has been called.
double get height {
assert(_debugAssertTextLayoutIsValid);
return _layoutCache!.layout.height;
}
/// The amount of space required to paint this text.
///
/// Valid only after [layout] has been called.
Size get size {
assert(_debugAssertTextLayoutIsValid);
assert(!_debugNeedsRelayout);
return Size(width, height);
}
/// Returns the distance from the top of the text to the first baseline of the
/// given type.
///
/// Valid only after [layout] has been called.
double computeDistanceToActualBaseline(TextBaseline baseline) {
assert(_debugAssertTextLayoutIsValid);
return _layoutCache!.layout.getDistanceToBaseline(baseline);
}
/// Whether any text was truncated or ellipsized.
///
/// If [maxLines] is not null, this is true if there were more lines to be
/// drawn than the given [maxLines], and thus at least one line was omitted in
/// the output; otherwise it is false.
///
/// If [maxLines] is null, this is true if [ellipsis] is not the empty string
/// and there was a line that overflowed the `maxWidth` argument passed to
/// [layout]; otherwise it is false.
///
/// Valid only after [layout] has been called.
bool get didExceedMaxLines {
assert(_debugAssertTextLayoutIsValid);
return _layoutCache!.paragraph.didExceedMaxLines;
}
// Creates a ui.Paragraph using the current configurations in this class and
// assign it to _paragraph.
ui.Paragraph _createParagraph(InlineSpan text) {
final ui.ParagraphBuilder builder = ui.ParagraphBuilder(_createParagraphStyle());
text.build(builder, textScaler: textScaler, dimensions: _placeholderDimensions);
assert(() {
_debugMarkNeedsLayoutCallStack = null;
return true;
}());
_rebuildParagraphForPaint = false;
return builder.build();
}
/// Computes the visual position of the glyphs for painting the text.
///
/// The text will layout with a width that's as close to its max intrinsic
/// width (or its longest line, if [textWidthBasis] is set to
/// [TextWidthBasis.parent]) as possible while still being greater than or
/// equal to `minWidth` and less than or equal to `maxWidth`.
///
/// The [text] and [textDirection] properties must be non-null before this is
/// called.
void layout({ double minWidth = 0.0, double maxWidth = double.infinity }) {
assert(!maxWidth.isNaN);
assert(!minWidth.isNaN);
assert(() {
_debugNeedsRelayout = false;
return true;
}());
final _TextPainterLayoutCacheWithOffset? cachedLayout = _layoutCache;
if (cachedLayout != null && cachedLayout._resizeToFit(minWidth, maxWidth, textWidthBasis)) {
return;
}
final InlineSpan? text = this.text;
if (text == null) {
throw StateError('TextPainter.text must be set to a non-null value before using the TextPainter.');
}
final TextDirection? textDirection = this.textDirection;
if (textDirection == null) {
throw StateError('TextPainter.textDirection must be set to a non-null value before using the TextPainter.');
}
final double paintOffsetAlignment = _computePaintOffsetFraction(textAlign, textDirection);
// Try to avoid laying out the paragraph with maxWidth=double.infinity
// when the text is not left-aligned, so we don't have to deal with an
// infinite paint offset.
final bool adjustMaxWidth = !maxWidth.isFinite && paintOffsetAlignment != 0;
final double? adjustedMaxWidth = !adjustMaxWidth ? maxWidth : cachedLayout?.layout.maxIntrinsicLineExtent;
final double layoutMaxWidth = adjustedMaxWidth ?? maxWidth;
// Only rebuild the paragraph when there're layout changes, even when
// `_rebuildParagraphForPaint` is true. It's best to not eagerly rebuild
// the paragraph to avoid the extra work, because:
// 1. the text color could change again before `paint` is called (so one of
// the paragraph rebuilds is unnecessary)
// 2. the user could be measuring the text layout so `paint` will never be
// called.
final ui.Paragraph paragraph = (cachedLayout?.paragraph ?? _createParagraph(text))
..layout(ui.ParagraphConstraints(width: layoutMaxWidth));
final _TextLayout layout = _TextLayout._(paragraph, textDirection, plainText);
final double contentWidth = layout._contentWidthFor(minWidth, maxWidth, textWidthBasis);
final _TextPainterLayoutCacheWithOffset newLayoutCache;
// Call layout again if newLayoutCache had an infinite paint offset.
// This is not as expensive as it seems, line breaking is relatively cheap
// as compared to shaping.
if (adjustedMaxWidth == null && minWidth.isFinite) {
assert(maxWidth.isInfinite);
final double newInputWidth = layout.maxIntrinsicLineExtent;
paragraph.layout(ui.ParagraphConstraints(width: newInputWidth));
newLayoutCache = _TextPainterLayoutCacheWithOffset(layout, paintOffsetAlignment, newInputWidth, contentWidth);
} else {
newLayoutCache = _TextPainterLayoutCacheWithOffset(layout, paintOffsetAlignment, layoutMaxWidth, contentWidth);
}
_layoutCache = newLayoutCache;
}
/// Paints the text onto the given canvas at the given offset.
///
/// Valid only after [layout] has been called.
///
/// If you cannot see the text being painted, check that your text color does
/// not conflict with the background on which you are drawing. The default
/// text color is white (to contrast with the default black background color),
/// so if you are writing an application with a white background, the text
/// will not be visible by default.
///
/// To set the text style, specify a [TextStyle] when creating the [TextSpan]
/// that you pass to the [TextPainter] constructor or to the [text] property.
void paint(Canvas canvas, Offset offset) {
final _TextPainterLayoutCacheWithOffset? layoutCache = _layoutCache;
if (layoutCache == null) {
throw StateError(
'TextPainter.paint called when text geometry was not yet calculated.\n'
'Please call layout() before paint() to position the text before painting it.',
);
}
if (!layoutCache.paintOffset.dx.isFinite || !layoutCache.paintOffset.dy.isFinite) {
return;
}
if (_rebuildParagraphForPaint) {
Size? debugSize;
assert(() {
debugSize = size;
return true;
}());
final ui.Paragraph paragraph = layoutCache.paragraph;
// Unfortunately even if we know that there is only paint changes, there's
// no API to only make those updates so the paragraph has to be recreated
// and re-laid out.
assert(!layoutCache.layoutMaxWidth.isNaN);
layoutCache.layout._paragraph = _createParagraph(text!)..layout(ui.ParagraphConstraints(width: layoutCache.layoutMaxWidth));
assert(paragraph.width == layoutCache.layout._paragraph.width);
paragraph.dispose();
assert(debugSize == size);
}
assert(!_rebuildParagraphForPaint);
canvas.drawParagraph(layoutCache.paragraph, offset + layoutCache.paintOffset);
}
// Returns true if value falls in the valid range of the UTF16 encoding.
static bool _isUTF16(int value) {
return value >= 0x0 && value <= 0xFFFFF;
}
/// Returns true iff the given value is a valid UTF-16 high (first) surrogate.
/// The value must be a UTF-16 code unit, meaning it must be in the range
/// 0x0000-0xFFFF.
///
/// See also:
/// * https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF
/// * [isLowSurrogate], which checks the same thing for low (second)
/// surrogates.
static bool isHighSurrogate(int value) {
assert(_isUTF16(value));
return value & 0xFC00 == 0xD800;
}
/// Returns true iff the given value is a valid UTF-16 low (second) surrogate.
/// The value must be a UTF-16 code unit, meaning it must be in the range
/// 0x0000-0xFFFF.
///
/// See also:
/// * https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF
/// * [isHighSurrogate], which checks the same thing for high (first)
/// surrogates.
static bool isLowSurrogate(int value) {
assert(_isUTF16(value));
return value & 0xFC00 == 0xDC00;
}
/// Returns the closest offset after `offset` at which the input cursor can be
/// positioned.
int? getOffsetAfter(int offset) {
final int? nextCodeUnit = _text!.codeUnitAt(offset);
if (nextCodeUnit == null) {
return null;
}
// TODO(goderbauer): doesn't handle extended grapheme clusters with more than one Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
return isHighSurrogate(nextCodeUnit) ? offset + 2 : offset + 1;
}
/// Returns the closest offset before `offset` at which the input cursor can
/// be positioned.
int? getOffsetBefore(int offset) {
final int? prevCodeUnit = _text!.codeUnitAt(offset - 1);
if (prevCodeUnit == null) {
return null;
}
// TODO(goderbauer): doesn't handle extended grapheme clusters with more than one Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
return isLowSurrogate(prevCodeUnit) ? offset - 2 : offset - 1;
}
static double _computePaintOffsetFraction(TextAlign textAlign, TextDirection textDirection) {
return switch ((textAlign, textDirection)) {
(TextAlign.left, _) => 0.0,
(TextAlign.right, _) => 1.0,
(TextAlign.center, _) => 0.5,
(TextAlign.start || TextAlign.justify, TextDirection.ltr) => 0.0,
(TextAlign.start || TextAlign.justify, TextDirection.rtl) => 1.0,
(TextAlign.end, TextDirection.ltr) => 1.0,
(TextAlign.end, TextDirection.rtl) => 0.0,
};
}
/// Returns the offset at which to paint the caret.
///
/// Valid only after [layout] has been called.
Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) {
final _TextPainterLayoutCacheWithOffset layoutCache = _layoutCache!;
final _LineCaretMetrics? caretMetrics = _computeCaretMetrics(position);
if (caretMetrics == null) {
final double paintOffsetAlignment = _computePaintOffsetFraction(textAlign, textDirection!);
// The full width is not (width - caretPrototype.width), because
// RenderEditable reserves cursor width on the right. Ideally this
// should be handled by RenderEditable instead.
final double dx = paintOffsetAlignment == 0 ? 0 : paintOffsetAlignment * layoutCache.contentWidth;
return Offset(dx, 0.0);
}
final Offset rawOffset = switch (caretMetrics) {
_LineCaretMetrics(writingDirection: TextDirection.ltr, :final Offset offset) => offset,
_LineCaretMetrics(writingDirection: TextDirection.rtl, :final Offset offset) => Offset(offset.dx - caretPrototype.width, offset.dy),
};
// If offset.dx is outside of the advertised content area, then the associated
// glyph belongs to a trailing whitespace character. Ideally the behavior
// should be handled by higher-level implementations (for instance,
// RenderEditable reserves width for showing the caret, it's best to handle
// the clamping there).
final double adjustedDx = clampDouble(rawOffset.dx + layoutCache.paintOffset.dx, 0, layoutCache.contentWidth);
return Offset(adjustedDx, rawOffset.dy + layoutCache.paintOffset.dy);
}
/// {@template flutter.painting.textPainter.getFullHeightForCaret}
/// Returns the strut bounded height of the glyph at the given `position`.
/// {@endtemplate}
///
/// Valid only after [layout] has been called.
double? getFullHeightForCaret(TextPosition position, Rect caretPrototype) {
final TextBox textBox = _getOrCreateLayoutTemplate().getBoxesForRange(0, 1, boxHeightStyle: ui.BoxHeightStyle.strut).single;
return textBox.toRect().height;
}
bool _isNewlineAtOffset(int offset) => 0 <= offset && offset < plainText.length
&& WordBoundary._isNewline(plainText.codeUnitAt(offset));
// Cached caret metrics. This allows multiple invokes of [getOffsetForCaret] and
// [getFullHeightForCaret] in a row without performing redundant and expensive
// get rect calls to the paragraph.
//
// The cache implementation assumes there's only one cursor at any given time.
late _LineCaretMetrics _caretMetrics;
// This function returns the caret's offset and height for the given
// `position` in the text, or null if the paragraph is empty.
//
// For a TextPosition, typically when its TextAffinity is downstream, the
// corresponding I-beam caret is anchored to the leading edge of the character
// at `offset` in the text. When the TextAffinity is upstream, the I-beam is
// then anchored to the trailing edge of the preceding character, except for a
// few edge cases:
//
// 1. empty paragraph: this method returns null and the caller handles this
// case.
//
// 2. (textLength, downstream), the end-of-text caret when the text is not
// empty: it's placed next to the trailing edge of the last line of the
// text, in case the text and its last bidi run have different writing
// directions. See the `_computeEndOfTextCaretAnchorOffset` method for more
// details.
//
// 3. (0, upstream), which isn't a valid position, but it's not a conventional
// "invalid" caret location either (the offset isn't negative). For
// historical reasons, this is treated as (0, downstream).
//
// 4. (x, upstream) where x - 1 points to a line break character. The caret
// should be displayed at the beginning of the newline instead of at the
// end of the previous line. Converts the location to (x, downstream). The
// choice we makes in 5. allows us to still check (x - 1) in case x points
// to a multi-code-unit character.
//
// 5. (x, downstream || upstream), where x points to a multi-code-unit
// character. There's no perfect caret placement in this case. Here we chose
// to draw the caret at the location that makes the most sense when the
// user wants to backspace (which also means it's left-arrow-key-biased):
//
// * downstream: show the caret at the leading edge of the character only if
// x points to the start of the grapheme. Otherwise show the caret at the
// leading edge of the next logical character.
// * upstream: show the caret at the trailing edge of the previous character
// only if x points to the start of the grapheme. Otherwise place the
// caret at the trailing edge of the character.
_LineCaretMetrics? _computeCaretMetrics(TextPosition position) {
assert(_debugAssertTextLayoutIsValid);
assert(!_debugNeedsRelayout);
final _TextPainterLayoutCacheWithOffset cachedLayout = _layoutCache!;
// If nothing is laid out, top start is the only reasonable place to place
// the cursor.
// The HTML renderer reports numberOfLines == 1 when the text is empty:
// https://github.com/flutter/flutter/issues/143331
if (cachedLayout.paragraph.numberOfLines < 1 || plainText.isEmpty) {
// TODO(LongCatIsLooong): assert when an invalid position is given.
return null;
}
final (int offset, bool anchorToLeadingEdge) = switch (position) {
TextPosition(offset: 0) => (0, true), // As a special case, always anchor to the leading edge of the first grapheme regardless of the affinity.
TextPosition(:final int offset, affinity: TextAffinity.downstream) => (offset, true),
TextPosition(:final int offset, affinity: TextAffinity.upstream) when _isNewlineAtOffset(offset - 1) => (offset, true),
TextPosition(:final int offset, affinity: TextAffinity.upstream) => (offset - 1, false)
};
final int caretPositionCacheKey = anchorToLeadingEdge ? offset : -offset - 1;
if (caretPositionCacheKey == cachedLayout._previousCaretPositionKey) {
return _caretMetrics;
}
final ui.GlyphInfo? glyphInfo = cachedLayout.paragraph.getGlyphInfoAt(offset);
if (glyphInfo == null) {
// If the glyph isn't laid out, then the position points to a character
// that is not laid out. Use the EOT caret.
// TODO(LongCatIsLooong): assert when an invalid position is given.
final ui.Paragraph template = _getOrCreateLayoutTemplate();
assert(template.numberOfLines == 1);
final double baselineOffset = template.getLineMetricsAt(0)!.baseline;
return cachedLayout.layout._endOfTextCaretMetrics.shift(Offset(0.0, -baselineOffset));
}
final TextRange graphemeRange = glyphInfo.graphemeClusterCodeUnitRange;
// Works around a SkParagraph bug (https://github.com/flutter/flutter/issues/120836#issuecomment-1937343854):
// placeholders with a size of (0, 0) always have a rect of Rect.zero and a
// range of (0, 0).
if (graphemeRange.isCollapsed) {
assert(graphemeRange.start == 0);
return _computeCaretMetrics(TextPosition(offset: offset + 1));
}
if (anchorToLeadingEdge && graphemeRange.start != offset) {
assert(graphemeRange.end > graphemeRange.start + 1);
// Addresses the case where `offset` points to a multi-code-unit grapheme
// that doesn't start at `offset`.
return _computeCaretMetrics(TextPosition(offset: graphemeRange.end));
}
final _LineCaretMetrics metrics;
final List<TextBox> boxes = cachedLayout.paragraph
.getBoxesForRange(graphemeRange.start, graphemeRange.end, boxHeightStyle: ui.BoxHeightStyle.strut);
if (boxes.isNotEmpty) {
final TextBox box = boxes.single;
metrics = _LineCaretMetrics(
offset: Offset(anchorToLeadingEdge ? box.start : box.end, box.top),
writingDirection: box.direction,
);
} else {
// Fall back to glyphInfo. This should only happen when using the HTML renderer.
assert(kIsWeb && !isCanvasKit);
final Rect graphemeBounds = glyphInfo.graphemeClusterLayoutBounds;
final double dx = switch (glyphInfo.writingDirection) {
TextDirection.ltr => anchorToLeadingEdge ? graphemeBounds.left : graphemeBounds.right,
TextDirection.rtl => anchorToLeadingEdge ? graphemeBounds.right : graphemeBounds.left,
};
metrics = _LineCaretMetrics(
offset: Offset(dx, graphemeBounds.top),
writingDirection: glyphInfo.writingDirection,
);
}
cachedLayout._previousCaretPositionKey = caretPositionCacheKey;
return _caretMetrics = metrics;
}
/// Returns a list of rects that bound the given selection.
///
/// The [selection] must be a valid range (with [TextSelection.isValid] true).
///
/// The [boxHeightStyle] and [boxWidthStyle] arguments may be used to select
/// the shape of the [TextBox]s. These properties default to
/// [ui.BoxHeightStyle.tight] and [ui.BoxWidthStyle.tight] respectively.
///
/// A given selection might have more than one rect if this text painter
/// contains bidirectional text because logically contiguous text might not be
/// visually contiguous.
///
/// Leading or trailing newline characters will be represented by zero-width
/// `TextBox`es.
///
/// The method only returns `TextBox`es of glyphs that are entirely enclosed by
/// the given `selection`: a multi-code-unit glyph will be excluded if only
/// part of its code units are in `selection`.
List<TextBox> getBoxesForSelection(
TextSelection selection, {
ui.BoxHeightStyle boxHeightStyle = ui.BoxHeightStyle.tight,
ui.BoxWidthStyle boxWidthStyle = ui.BoxWidthStyle.tight,
}) {
assert(_debugAssertTextLayoutIsValid);
assert(selection.isValid);
assert(!_debugNeedsRelayout);
final _TextPainterLayoutCacheWithOffset cachedLayout = _layoutCache!;
final Offset offset = cachedLayout.paintOffset;
if (!offset.dx.isFinite || !offset.dy.isFinite) {
return <TextBox>[];
}
final List<TextBox> boxes = cachedLayout.paragraph.getBoxesForRange(
selection.start,
selection.end,
boxHeightStyle: boxHeightStyle,
boxWidthStyle: boxWidthStyle,
);
return offset == Offset.zero
? boxes
: boxes.map((TextBox box) => _shiftTextBox(box, offset)).toList(growable: false);
}
/// Returns the [GlyphInfo] of the glyph closest to the given `offset` in the
/// paragraph coordinate system, or null if the text is empty, or is entirely
/// clipped or ellipsized away.
///
/// This method first finds the line closest to `offset.dy`, and then returns
/// the [GlyphInfo] of the closest glyph(s) within that line.
ui.GlyphInfo? getClosestGlyphForOffset(Offset offset) {
assert(_debugAssertTextLayoutIsValid);
assert(!_debugNeedsRelayout);
final _TextPainterLayoutCacheWithOffset cachedLayout = _layoutCache!;
final ui.GlyphInfo? rawGlyphInfo = cachedLayout.paragraph.getClosestGlyphInfoForOffset(offset - cachedLayout.paintOffset);
if (rawGlyphInfo == null || cachedLayout.paintOffset == Offset.zero) {
return rawGlyphInfo;
}
return ui.GlyphInfo(rawGlyphInfo.graphemeClusterLayoutBounds.shift(cachedLayout.paintOffset), rawGlyphInfo.graphemeClusterCodeUnitRange, rawGlyphInfo.writingDirection);
}
/// Returns the closest position within the text for the given pixel offset.
TextPosition getPositionForOffset(Offset offset) {
assert(_debugAssertTextLayoutIsValid);
assert(!_debugNeedsRelayout);
final _TextPainterLayoutCacheWithOffset cachedLayout = _layoutCache!;
return cachedLayout.paragraph.getPositionForOffset(offset - cachedLayout.paintOffset);
}
/// {@template flutter.painting.TextPainter.getWordBoundary}
/// Returns the text range of the word at the given offset. Characters not
/// part of a word, such as spaces, symbols, and punctuation, have word breaks
/// on both sides. In such cases, this method will return a text range that
/// contains the given text position.
///
/// Word boundaries are defined more precisely in Unicode Standard Annex #29
/// <http://www.unicode.org/reports/tr29/#Word_Boundaries>.
/// {@endtemplate}
TextRange getWordBoundary(TextPosition position) {
assert(_debugAssertTextLayoutIsValid);
return _layoutCache!.paragraph.getWordBoundary(position);
}
/// {@template flutter.painting.TextPainter.wordBoundaries}
/// Returns a [TextBoundary] that can be used to perform word boundary analysis
/// on the current [text].
///
/// This [TextBoundary] uses word boundary rules defined in [Unicode Standard
/// Annex #29](http://www.unicode.org/reports/tr29/#Word_Boundaries).
/// {@endtemplate}
///
/// Currently word boundary analysis can only be performed after [layout]
/// has been called.
WordBoundary get wordBoundaries => WordBoundary._(text!, _layoutCache!.paragraph);
/// Returns the text range of the line at the given offset.
///
/// The newline (if any) is not returned as part of the range.
TextRange getLineBoundary(TextPosition position) {
assert(_debugAssertTextLayoutIsValid);
return _layoutCache!.paragraph.getLineBoundary(position);
}
static ui.LineMetrics _shiftLineMetrics(ui.LineMetrics metrics, Offset offset) {
assert(offset.dx.isFinite);
assert(offset.dy.isFinite);
return ui.LineMetrics(
hardBreak: metrics.hardBreak,
ascent: metrics.ascent,
descent: metrics.descent,
unscaledAscent: metrics.unscaledAscent,
height: metrics.height,
width: metrics.width,
left: metrics.left + offset.dx,
baseline: metrics.baseline + offset.dy,
lineNumber: metrics.lineNumber,
);
}
static TextBox _shiftTextBox(TextBox box, Offset offset) {
assert(offset.dx.isFinite);
assert(offset.dy.isFinite);
return TextBox.fromLTRBD(
box.left + offset.dx,
box.top + offset.dy,
box.right + offset.dx,
box.bottom + offset.dy,
box.direction,
);
}
/// Returns the full list of [LineMetrics] that describe in detail the various
/// metrics of each laid out line.
///
/// The [LineMetrics] list is presented in the order of the lines they represent.
/// For example, the first line is in the zeroth index.
///
/// [LineMetrics] contains measurements such as ascent, descent, baseline, and
/// width for the line as a whole, and may be useful for aligning additional
/// widgets to a particular line.
///
/// Valid only after [layout] has been called.
List<ui.LineMetrics> computeLineMetrics() {
assert(_debugAssertTextLayoutIsValid);
assert(!_debugNeedsRelayout);
final _TextPainterLayoutCacheWithOffset layout = _layoutCache!;
final Offset offset = layout.paintOffset;
if (!offset.dx.isFinite || !offset.dy.isFinite) {
return const <ui.LineMetrics>[];
}
final List<ui.LineMetrics> rawMetrics = layout.lineMetrics;
return offset == Offset.zero
? rawMetrics
: rawMetrics.map((ui.LineMetrics metrics) => _shiftLineMetrics(metrics, offset)).toList(growable: false);
}
bool _disposed = false;
/// Whether this object has been disposed or not.
///
/// Only for use when asserts are enabled.
bool get debugDisposed {
bool? disposed;
assert(() {
disposed = _disposed;
return true;
}());
return disposed ?? (throw StateError('debugDisposed only available when asserts are on.'));
}
/// Releases the resources associated with this painter.
///
/// After disposal this painter is unusable.
void dispose() {
assert(!debugDisposed);
assert(() {
_disposed = true;
return true;
}());
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
_layoutTemplate?.dispose();
_layoutTemplate = null;
_layoutCache?.paragraph.dispose();
_layoutCache = null;
_text = null;
}
}
| flutter/packages/flutter/lib/src/painting/text_painter.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/text_painter.dart",
"repo_id": "flutter",
"token_count": 21902
} | 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 'box.dart';
import 'object.dart';
export 'package:flutter/foundation.dart' show debugPrint;
// Any changes to this file should be reflected in the debugAssertAllRenderVarsUnset()
// function below.
const HSVColor _kDebugDefaultRepaintColor = HSVColor.fromAHSV(0.4, 60.0, 1.0, 1.0);
/// Causes each RenderBox to paint a box around its bounds, and some extra
/// boxes, such as [RenderPadding], to draw construction lines.
///
/// The edges of the boxes are painted as a one-pixel-thick `const Color(0xFF00FFFF)` outline.
///
/// Spacing is painted as a solid `const Color(0x90909090)` area.
///
/// Padding is filled in solid `const Color(0x900090FF)`, with the inner edge
/// outlined in `const Color(0xFF0090FF)`, using [debugPaintPadding].
bool debugPaintSizeEnabled = false;
/// Causes each RenderBox to paint a line at each of its baselines.
bool debugPaintBaselinesEnabled = false;
/// Causes each Layer to paint a box around its bounds.
bool debugPaintLayerBordersEnabled = false;
/// Causes objects like [RenderPointerListener] to flash while they are being
/// tapped. This can be useful to see how large the hit box is, e.g. when
/// debugging buttons that are harder to hit than expected.
///
/// For details on how to support this in your [RenderBox] subclass, see
/// [RenderBox.debugHandleEvent].
bool debugPaintPointersEnabled = false;
/// Overlay a rotating set of colors when repainting layers in debug mode.
///
/// See also:
///
/// * [RepaintBoundary], which can be used to contain repaints when unchanged
/// areas are being excessively repainted.
bool debugRepaintRainbowEnabled = false;
/// Overlay a rotating set of colors when repainting text in debug mode.
bool debugRepaintTextRainbowEnabled = false;
/// The current color to overlay when repainting a layer.
///
/// This is used by painting debug code that implements
/// [debugRepaintRainbowEnabled] or [debugRepaintTextRainbowEnabled].
///
/// The value is incremented by [RenderView.compositeFrame] if either of those
/// flags is enabled.
HSVColor debugCurrentRepaintColor = _kDebugDefaultRepaintColor;
/// Log the call stacks that mark render objects as needing layout.
///
/// For sanity, this only logs the stack traces of cases where an object is
/// added to the list of nodes needing layout. This avoids printing multiple
/// redundant stack traces as a single [RenderObject.markNeedsLayout] call walks
/// up the tree.
bool debugPrintMarkNeedsLayoutStacks = false;
/// Log the call stacks that mark render objects as needing paint.
bool debugPrintMarkNeedsPaintStacks = false;
/// Log the dirty render objects that are laid out each frame.
///
/// Combined with [debugPrintBeginFrameBanner], this allows you to distinguish
/// layouts triggered by the initial mounting of a render tree (e.g. in a call
/// to [runApp]) from the regular layouts triggered by the pipeline.
///
/// Combined with [debugPrintMarkNeedsLayoutStacks], this lets you watch a
/// render object's dirty/clean lifecycle.
///
/// See also:
///
/// * [debugProfileLayoutsEnabled], which does something similar for layout
/// but using the timeline view.
/// * [debugProfilePaintsEnabled], which does something similar for painting
/// but using the timeline view.
/// * [debugPrintRebuildDirtyWidgets], which does something similar for widgets
/// being rebuilt.
/// * The discussion at [RendererBinding.drawFrame].
bool debugPrintLayouts = false;
/// Check the intrinsic sizes of each [RenderBox] during layout.
///
/// By default this is turned off since these checks are expensive. If you are
/// implementing your own children of [RenderBox] with custom intrinsics, turn
/// this on in your unit tests for additional validations.
bool debugCheckIntrinsicSizes = false;
/// Adds [Timeline] events for every [RenderObject] layout.
///
/// The timing information this flag exposes is not representative of the actual
/// cost of layout, because the overhead of adding timeline events is
/// significant relative to the time each object takes to lay out. However, it
/// can expose unexpected layout behavior in the timeline.
///
/// In debug builds, additional information is included in the trace (such as
/// the properties of render objects being laid out). Collecting this data is
/// expensive and further makes these traces non-representative of actual
/// performance. This data is omitted in profile builds.
///
/// For more information about performance debugging in Flutter, see
/// <https://flutter.dev/docs/perf/rendering>.
///
/// See also:
///
/// * [debugPrintLayouts], which does something similar for layout but using
/// console output.
/// * [debugProfileBuildsEnabled], which does something similar for widgets
/// being rebuilt.
/// * [debugProfilePaintsEnabled], which does something similar for painting.
/// * [debugEnhanceLayoutTimelineArguments], which enhances the trace with
/// debugging information related to [RenderObject] layouts.
bool debugProfileLayoutsEnabled = false;
/// Adds [Timeline] events for every [RenderObject] painted.
///
/// The timing information this flag exposes is not representative of actual
/// paints, because the overhead of adding timeline events is significant
/// relative to the time each object takes to paint. However, it can expose
/// unexpected painting in the timeline.
///
/// In debug builds, additional information is included in the trace (such as
/// the properties of render objects being painted). Collecting this data is
/// expensive and further makes these traces non-representative of actual
/// performance. This data is omitted in profile builds.
///
/// For more information about performance debugging in Flutter, see
/// <https://flutter.dev/docs/perf/rendering>.
///
/// See also:
///
/// * [debugProfileBuildsEnabled], which does something similar for widgets
/// being rebuilt, and [debugPrintRebuildDirtyWidgets], its console
/// equivalent.
/// * [debugProfileLayoutsEnabled], which does something similar for layout,
/// and [debugPrintLayouts], its console equivalent.
/// * The discussion at [RendererBinding.drawFrame].
/// * [RepaintBoundary], which can be used to contain repaints when unchanged
/// areas are being excessively repainted.
/// * [debugEnhancePaintTimelineArguments], which enhances the trace with
/// debugging information related to [RenderObject] paints.
bool debugProfilePaintsEnabled = false;
/// Adds debugging information to [Timeline] events related to [RenderObject]
/// layouts.
///
/// This flag will only add [Timeline] event arguments for debug builds.
/// Additional arguments will be added for the "LAYOUT" timeline event and for
/// all [RenderObject] layout [Timeline] events, which are the events that are
/// added when [debugProfileLayoutsEnabled] is true. The debugging information
/// that will be added in trace arguments includes stats around [RenderObject]
/// dirty states and [RenderObject] diagnostic information (i.e. [RenderObject]
/// properties).
///
/// See also:
///
/// * [debugProfileLayoutsEnabled], which adds [Timeline] events for every
/// [RenderObject] layout.
/// * [debugEnhancePaintTimelineArguments], which does something similar for
/// events related to [RenderObject] paints.
/// * [debugEnhanceBuildTimelineArguments], which does something similar for
/// events related to [Widget] builds.
bool debugEnhanceLayoutTimelineArguments = false;
/// Adds debugging information to [Timeline] events related to [RenderObject]
/// paints.
///
/// This flag will only add [Timeline] event arguments for debug builds.
/// Additional arguments will be added for the "PAINT" timeline event and for
/// all [RenderObject] paint [Timeline] events, which are the [Timeline] events
/// that are added when [debugProfilePaintsEnabled] is true. The debugging
/// information that will be added in trace arguments includes stats around
/// [RenderObject] dirty states and [RenderObject] diagnostic information
/// (i.e. [RenderObject] properties).
///
/// See also:
///
/// * [debugProfilePaintsEnabled], which adds [Timeline] events for every
/// [RenderObject] paint.
/// * [debugEnhanceLayoutTimelineArguments], which does something similar for
/// events related to [RenderObject] layouts.
/// * [debugEnhanceBuildTimelineArguments], which does something similar for
/// events related to [Widget] builds.
bool debugEnhancePaintTimelineArguments = false;
/// Signature for [debugOnProfilePaint] implementations.
typedef ProfilePaintCallback = void Function(RenderObject renderObject);
/// Callback invoked for every [RenderObject] painted each frame.
///
/// This callback is only invoked in debug builds.
///
/// See also:
///
/// * [debugProfilePaintsEnabled], which does something similar but adds
/// [dart:developer.Timeline] events instead of invoking a callback.
/// * [debugOnRebuildDirtyWidget], which does something similar for widgets
/// being built.
/// * [WidgetInspectorService], which uses the [debugOnProfilePaint]
/// callback to generate aggregate profile statistics describing what paints
/// occurred when the `ext.flutter.inspector.trackRepaintWidgets` service
/// extension is enabled.
ProfilePaintCallback? debugOnProfilePaint;
/// Setting to true will cause all clipping effects from the layer tree to be
/// ignored.
///
/// Can be used to debug whether objects being clipped are painting excessively
/// in clipped areas. Can also be used to check whether excessive use of
/// clipping is affecting performance.
///
/// This will not reduce the number of [Layer] objects created; the compositing
/// strategy is unaffected. It merely causes the clipping layers to be skipped
/// when building the scene.
bool debugDisableClipLayers = false;
/// Setting to true will cause all physical modeling effects from the layer
/// tree, such as shadows from elevations, to be ignored.
///
/// Can be used to check whether excessive use of physical models is affecting
/// performance.
///
/// This will not reduce the number of [Layer] objects created; the compositing
/// strategy is unaffected. It merely causes the physical shape layers to be
/// skipped when building the scene.
bool debugDisablePhysicalShapeLayers = false;
/// Setting to true will cause all opacity effects from the layer tree to be
/// ignored.
///
/// An optimization to not paint the child at all when opacity is 0 will still
/// remain.
///
/// Can be used to check whether excessive use of opacity effects is affecting
/// performance.
///
/// This will not reduce the number of [Layer] objects created; the compositing
/// strategy is unaffected. It merely causes the opacity layers to be skipped
/// when building the scene.
bool debugDisableOpacityLayers = false;
void _debugDrawDoubleRect(Canvas canvas, Rect outerRect, Rect innerRect, Color color) {
final Path path = Path()
..fillType = PathFillType.evenOdd
..addRect(outerRect)
..addRect(innerRect);
final Paint paint = Paint()
..color = color;
canvas.drawPath(path, paint);
}
/// Paint a diagram showing the given area as padding.
///
/// The `innerRect` argument represents the position of the child, if any.
///
/// When `innerRect` is null, the method draws the entire `outerRect` in a
/// grayish color representing _spacing_.
///
/// When `innerRect` is non-null, the method draws the padding region around the
/// `innerRect` in a tealish color, with a solid outline around the inner
/// region.
///
/// This method is used by [RenderPadding.debugPaintSize] when
/// [debugPaintSizeEnabled] is true.
void debugPaintPadding(Canvas canvas, Rect outerRect, Rect? innerRect, { double outlineWidth = 2.0 }) {
assert(() {
if (innerRect != null && !innerRect.isEmpty) {
_debugDrawDoubleRect(canvas, outerRect, innerRect, const Color(0x900090FF));
_debugDrawDoubleRect(canvas, innerRect.inflate(outlineWidth).intersect(outerRect), innerRect, const Color(0xFF0090FF));
} else {
final Paint paint = Paint()
..color = const Color(0x90909090);
canvas.drawRect(outerRect, paint);
}
return true;
}());
}
/// Returns true if none of the rendering library debug variables have been changed.
///
/// This function is used by the test framework to ensure that debug variables
/// haven't been inadvertently changed.
///
/// See [the rendering library](rendering/rendering-library.html) for a complete
/// list.
///
/// The `debugCheckIntrinsicSizesOverride` argument can be provided to override
/// the expected value for [debugCheckIntrinsicSizes]. (This exists because the
/// test framework itself overrides this value in some cases.)
bool debugAssertAllRenderVarsUnset(String reason, { bool debugCheckIntrinsicSizesOverride = false }) {
assert(() {
if (debugPaintSizeEnabled ||
debugPaintBaselinesEnabled ||
debugPaintLayerBordersEnabled ||
debugPaintPointersEnabled ||
debugRepaintRainbowEnabled ||
debugRepaintTextRainbowEnabled ||
debugCurrentRepaintColor != _kDebugDefaultRepaintColor ||
debugPrintMarkNeedsLayoutStacks ||
debugPrintMarkNeedsPaintStacks ||
debugPrintLayouts ||
debugCheckIntrinsicSizes != debugCheckIntrinsicSizesOverride ||
debugProfileLayoutsEnabled ||
debugProfilePaintsEnabled ||
debugOnProfilePaint != null ||
debugDisableClipLayers ||
debugDisablePhysicalShapeLayers ||
debugDisableOpacityLayers) {
throw FlutterError(reason);
}
return true;
}());
return true;
}
/// Returns true if the given [Axis] is bounded within the given
/// [BoxConstraints] in both the main and cross axis, throwing an exception
/// otherwise.
///
/// This is used by viewports during `performLayout` and `computeDryLayout`
/// because bounded constraints are required in order to layout their children.
bool debugCheckHasBoundedAxis(Axis axis, BoxConstraints constraints) {
assert(() {
if (!constraints.hasBoundedHeight || !constraints.hasBoundedWidth) {
switch (axis) {
case Axis.vertical:
if (!constraints.hasBoundedHeight) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Vertical viewport was given unbounded height.'),
ErrorDescription(
'Viewports expand in the scrolling direction to fill their container. '
'In this case, a vertical viewport was given an unlimited amount of '
'vertical space in which to expand. This situation typically happens '
'when a scrollable widget is nested inside another scrollable widget.',
),
ErrorHint(
'If this widget is always nested in a scrollable widget there '
'is no need to use a viewport because there will always be enough '
'vertical space for the children. In this case, consider using a '
'Column or Wrap instead. Otherwise, consider using a '
'CustomScrollView to concatenate arbitrary slivers into a '
'single scrollable.',
),
]);
}
if (!constraints.hasBoundedWidth) {
throw FlutterError(
'Vertical viewport was given unbounded width.\n'
'Viewports expand in the cross axis to fill their container and '
'constrain their children to match their extent in the cross axis. '
'In this case, a vertical viewport was given an unlimited amount of '
'horizontal space in which to expand.',
);
}
case Axis.horizontal:
if (!constraints.hasBoundedWidth) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Horizontal viewport was given unbounded width.'),
ErrorDescription(
'Viewports expand in the scrolling direction to fill their container. '
'In this case, a horizontal viewport was given an unlimited amount of '
'horizontal space in which to expand. This situation typically happens '
'when a scrollable widget is nested inside another scrollable widget.',
),
ErrorHint(
'If this widget is always nested in a scrollable widget there '
'is no need to use a viewport because there will always be enough '
'horizontal space for the children. In this case, consider using a '
'Row or Wrap instead. Otherwise, consider using a '
'CustomScrollView to concatenate arbitrary slivers into a '
'single scrollable.',
),
]);
}
if (!constraints.hasBoundedHeight) {
throw FlutterError(
'Horizontal viewport was given unbounded height.\n'
'Viewports expand in the cross axis to fill their container and '
'constrain their children to match their extent in the cross axis. '
'In this case, a horizontal viewport was given an unlimited amount of '
'vertical space in which to expand.',
);
}
}
}
return true;
}());
return true;
}
| flutter/packages/flutter/lib/src/rendering/debug.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/debug.dart",
"repo_id": "flutter",
"token_count": 5209
} | 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/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/services.dart';
import 'box.dart';
import 'layer.dart';
import 'object.dart';
/// How an embedded platform view behave during hit tests.
enum PlatformViewHitTestBehavior {
/// Opaque targets can be hit by hit tests, causing them to both receive
/// events within their bounds and prevent targets visually behind them from
/// also receiving events.
opaque,
/// Translucent targets both receive events within their bounds and permit
/// targets visually behind them to also receive events.
translucent,
/// Transparent targets don't receive events within their bounds and permit
/// targets visually behind them to receive events.
transparent,
}
enum _PlatformViewState {
uninitialized,
resizing,
ready,
}
bool _factoryTypesSetEquals<T>(Set<Factory<T>>? a, Set<Factory<T>>? b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
return setEquals(_factoriesTypeSet(a), _factoriesTypeSet(b));
}
Set<Type> _factoriesTypeSet<T>(Set<Factory<T>> factories) {
return factories.map<Type>((Factory<T> factory) => factory.type).toSet();
}
/// A render object for an Android view.
///
/// Requires Android API level 23 or greater.
///
/// [RenderAndroidView] is responsible for sizing, displaying and passing touch events to an
/// Android [View](https://developer.android.com/reference/android/view/View).
///
/// {@template flutter.rendering.RenderAndroidView.layout}
/// The render object's layout behavior is to fill all available space, the parent of this object must
/// provide bounded layout constraints.
/// {@endtemplate}
///
/// {@template flutter.rendering.RenderAndroidView.gestures}
/// The render object 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 with factories in the `gestureRecognizers` constructor parameter or
/// by calling `updateGestureRecognizers`. If the set of gesture recognizers is empty, the gesture
/// will be dispatched to the platform view iff it was not claimed by any other gesture recognizer.
/// {@endtemplate}
///
/// See also:
///
/// * [AndroidView] which is a widget that is used to show an Android view.
/// * [PlatformViewsService] which is a service for controlling platform views.
class RenderAndroidView extends PlatformViewRenderBox {
/// Creates a render object for an Android view.
RenderAndroidView({
required AndroidViewController viewController,
required PlatformViewHitTestBehavior hitTestBehavior,
required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
Clip clipBehavior = Clip.hardEdge,
}) : _viewController = viewController,
_clipBehavior = clipBehavior,
super(controller: viewController, hitTestBehavior: hitTestBehavior, gestureRecognizers: gestureRecognizers) {
_viewController.pointTransformer = (Offset offset) => globalToLocal(offset);
updateGestureRecognizers(gestureRecognizers);
_viewController.addOnPlatformViewCreatedListener(_onPlatformViewCreated);
this.hitTestBehavior = hitTestBehavior;
_setOffset();
}
_PlatformViewState _state = _PlatformViewState.uninitialized;
Size? _currentTextureSize;
bool _isDisposed = false;
/// The Android view controller for the Android view associated with this render object.
@override
AndroidViewController get controller => _viewController;
AndroidViewController _viewController;
/// Sets a new Android view controller.
@override
set controller(AndroidViewController controller) {
assert(!_isDisposed);
if (_viewController == controller) {
return;
}
_viewController.removeOnPlatformViewCreatedListener(_onPlatformViewCreated);
super.controller = controller;
_viewController = controller;
_viewController.pointTransformer = (Offset offset) => globalToLocal(offset);
_sizePlatformView();
if (_viewController.isCreated) {
markNeedsSemanticsUpdate();
}
_viewController.addOnPlatformViewCreatedListener(_onPlatformViewCreated);
}
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
Clip get clipBehavior => _clipBehavior;
Clip _clipBehavior = Clip.hardEdge;
set clipBehavior(Clip value) {
if (value != _clipBehavior) {
_clipBehavior = value;
markNeedsPaint();
markNeedsSemanticsUpdate();
}
}
void _onPlatformViewCreated(int id) {
assert(!_isDisposed);
markNeedsSemanticsUpdate();
}
@override
bool get sizedByParent => true;
@override
bool get alwaysNeedsCompositing => true;
@override
bool get isRepaintBoundary => true;
@override
@protected
Size computeDryLayout(covariant BoxConstraints constraints) {
return constraints.biggest;
}
@override
void performResize() {
super.performResize();
_sizePlatformView();
}
Future<void> _sizePlatformView() async {
// Android virtual displays cannot have a zero size.
// Trying to size it to 0 crashes the app, which was happening when starting the app
// with a locked screen (see: https://github.com/flutter/flutter/issues/20456).
if (_state == _PlatformViewState.resizing || size.isEmpty) {
return;
}
_state = _PlatformViewState.resizing;
markNeedsPaint();
Size targetSize;
do {
targetSize = size;
_currentTextureSize = await _viewController.setSize(targetSize);
if (_isDisposed) {
return;
}
// We've resized the platform view to targetSize, but it is possible that
// while we were resizing the render object's size was changed again.
// In that case we will resize the platform view again.
} while (size != targetSize);
_state = _PlatformViewState.ready;
markNeedsPaint();
}
// Sets the offset of the underlying platform view on the platform side.
//
// This allows the Android native view to draw the a11y highlights in the same
// location on the screen as the platform view widget in the Flutter framework.
//
// It also allows platform code to obtain the correct position of the Android
// native view on the screen.
void _setOffset() {
SchedulerBinding.instance.addPostFrameCallback((_) async {
if (!_isDisposed) {
if (attached) {
await _viewController.setOffset(localToGlobal(Offset.zero));
}
// Schedule a new post frame callback.
_setOffset();
}
}, debugLabel: 'RenderAndroidView.setOffset');
}
@override
void paint(PaintingContext context, Offset offset) {
if (_viewController.textureId == null || _currentTextureSize == null) {
return;
}
// As resizing the Android view happens asynchronously we don't know exactly when is a
// texture frame with the new size is ready for consumption.
// TextureLayer is unaware of the texture frame's size and always maps it to the
// specified rect. If the rect we provide has a different size from the current texture frame's
// size the texture frame will be scaled.
// To prevent unwanted scaling artifacts while resizing, clip the texture.
// This guarantees that the size of the texture frame we're painting is always
// _currentAndroidTextureSize.
final bool isTextureLargerThanWidget = _currentTextureSize!.width > size.width ||
_currentTextureSize!.height > size.height;
if (isTextureLargerThanWidget && clipBehavior != Clip.none) {
_clipRectLayer.layer = context.pushClipRect(
true,
offset,
offset & size,
_paintTexture,
clipBehavior: clipBehavior,
oldLayer: _clipRectLayer.layer,
);
return;
}
_clipRectLayer.layer = null;
_paintTexture(context, offset);
}
final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>();
@override
void dispose() {
_isDisposed = true;
_clipRectLayer.layer = null;
_viewController.removeOnPlatformViewCreatedListener(_onPlatformViewCreated);
super.dispose();
}
void _paintTexture(PaintingContext context, Offset offset) {
if (_currentTextureSize == null) {
return;
}
context.addLayer(TextureLayer(
rect: offset & _currentTextureSize!,
textureId: _viewController.textureId!,
));
}
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
// Don't call the super implementation since `platformViewId` should
// be set only when the platform view is created, but the concept of
// a "created" platform view belongs to this subclass.
config.isSemanticBoundary = true;
if (_viewController.isCreated) {
config.platformViewId = _viewController.viewId;
}
}
}
/// Common render-layer functionality for iOS and macOS platform views.
///
/// Provides the basic rendering logic for iOS and macOS platformviews.
/// Subclasses shall override handleEvent in order to execute custom event logic.
/// T represents the class of the view controller for the corresponding widget.
abstract class RenderDarwinPlatformView<T extends DarwinPlatformViewController> extends RenderBox {
/// Creates a render object for a platform view.
RenderDarwinPlatformView({
required T viewController,
required this.hitTestBehavior,
required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
}) : _viewController = viewController {
updateGestureRecognizers(gestureRecognizers);
}
/// The unique identifier of the platform view controlled by this controller.
T get viewController => _viewController;
T _viewController;
set viewController(T value) {
if (_viewController == value) {
return;
}
final bool needsSemanticsUpdate = _viewController.id != value.id;
_viewController = value;
markNeedsPaint();
if (needsSemanticsUpdate) {
markNeedsSemanticsUpdate();
}
}
/// How to behave during hit testing.
// The implicit setter is enough here as changing this value will just affect
// any newly arriving events there's nothing we need to invalidate.
PlatformViewHitTestBehavior hitTestBehavior;
@override
bool get sizedByParent => true;
@override
bool get alwaysNeedsCompositing => true;
@override
bool get isRepaintBoundary => true;
PointerEvent? _lastPointerDownEvent;
_UiKitViewGestureRecognizer? _gestureRecognizer;
@override
@protected
Size computeDryLayout(covariant BoxConstraints constraints) {
return constraints.biggest;
}
@override
void paint(PaintingContext context, Offset offset) {
context.addLayer(PlatformViewLayer(
rect: offset & size,
viewId: _viewController.id,
));
}
@override
bool hitTest(BoxHitTestResult result, { Offset? position }) {
if (hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position!)) {
return false;
}
result.add(BoxHitTestEntry(this, position));
return hitTestBehavior == PlatformViewHitTestBehavior.opaque;
}
@override
bool hitTestSelf(Offset position) => hitTestBehavior != PlatformViewHitTestBehavior.transparent;
// This is registered as a global PointerRoute while the render object is attached.
void _handleGlobalPointerEvent(PointerEvent event) {
if (event is! PointerDownEvent) {
return;
}
if (!(Offset.zero & size).contains(globalToLocal(event.position))) {
return;
}
if ((event.original ?? event) != _lastPointerDownEvent) {
// The pointer event is in the bounds of this render box, but we didn't get it in handleEvent.
// This means that the pointer event was absorbed by a different render object.
// Since on the platform side the FlutterTouchIntercepting view is seeing all events that are
// within its bounds we need to tell it to reject the current touch sequence.
_viewController.rejectGesture();
}
_lastPointerDownEvent = null;
}
@override
void describeSemanticsConfiguration (SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
config.isSemanticBoundary = true;
config.platformViewId = _viewController.id;
}
@override
void attach(PipelineOwner owner) {
super.attach(owner);
GestureBinding.instance.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent);
}
@override
void detach() {
GestureBinding.instance.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent);
super.detach();
}
/// {@macro flutter.rendering.PlatformViewRenderBox.updateGestureRecognizers}
void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers);
}
/// A render object for an iOS UIKit UIView.
///
/// [RenderUiKitView] is responsible for sizing and displaying an iOS
/// [UIView](https://developer.apple.com/documentation/uikit/uiview).
///
/// UIViews are added as subviews of the FlutterView and are composited by Quartz.
///
/// The viewController is typically generated by [PlatformViewsRegistry.getNextPlatformViewId], the UIView
/// must have been created by calling [PlatformViewsService.initUiKitView].
///
/// {@macro flutter.rendering.RenderAndroidView.layout}
///
/// {@macro flutter.rendering.RenderAndroidView.gestures}
///
/// See also:
///
/// * [UiKitView], which is a widget that is used to show a UIView.
/// * [PlatformViewsService], which is a service for controlling platform views.
class RenderUiKitView extends RenderDarwinPlatformView<UiKitViewController> {
/// Creates a render object for an iOS UIView.
RenderUiKitView({
required super.viewController,
required super.hitTestBehavior,
required super.gestureRecognizers,
});
/// {@macro flutter.rendering.PlatformViewRenderBox.updateGestureRecognizers}
@override
void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
assert(
_factoriesTypeSet(gestureRecognizers).length == gestureRecognizers.length,
'There were multiple gesture recognizer factories for the same type, there must only be a single '
'gesture recognizer factory for each gesture recognizer type.',
);
if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) {
return;
}
_gestureRecognizer?.dispose();
_gestureRecognizer = _UiKitViewGestureRecognizer(viewController, gestureRecognizers);
}
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
if (event is! PointerDownEvent) {
return;
}
_gestureRecognizer!.addPointer(event);
_lastPointerDownEvent = event.original ?? event;
}
@override
void detach() {
_gestureRecognizer!.reset();
super.detach();
}
@override
void dispose() {
_gestureRecognizer?.dispose();
super.dispose();
}
}
/// A render object for a macOS platform view.
class RenderAppKitView extends RenderDarwinPlatformView<AppKitViewController> {
/// Creates a render object for a macOS AppKitView.
RenderAppKitView({
required super.viewController,
required super.hitTestBehavior,
required super.gestureRecognizers,
});
// TODO(schectman): Add gesture functionality to macOS platform view when implemented.
// https://github.com/flutter/flutter/issues/128519
// This method will need to behave the same as the same-named method for RenderUiKitView,
// but use a _AppKitViewGestureRecognizer or equivalent, whose constructor shall accept an
// AppKitViewController.
@override
void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {}
}
// This recognizer constructs gesture recognizers from a set of gesture recognizer factories
// it was give, adds all of them to a gesture arena team with the _UiKitViewGestureRecognizer
// as the team captain.
// When the team wins a gesture the recognizer notifies the engine that it should release
// the touch sequence to the embedded UIView.
class _UiKitViewGestureRecognizer extends OneSequenceGestureRecognizer {
_UiKitViewGestureRecognizer(
this.controller,
this.gestureRecognizerFactories
) {
team = GestureArenaTeam()
..captain = this;
_gestureRecognizers = gestureRecognizerFactories.map(
(Factory<OneSequenceGestureRecognizer> recognizerFactory) {
final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor();
gestureRecognizer.team = team;
// The below gesture recognizers requires at least one non-empty callback to
// compete in the gesture arena.
// https://github.com/flutter/flutter/issues/35394#issuecomment-562285087
if (gestureRecognizer is LongPressGestureRecognizer) {
gestureRecognizer.onLongPress ??= (){};
} else if (gestureRecognizer is DragGestureRecognizer) {
gestureRecognizer.onDown ??= (_){};
} else if (gestureRecognizer is TapGestureRecognizer) {
gestureRecognizer.onTapDown ??= (_){};
}
return gestureRecognizer;
},
).toSet();
}
// 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>> gestureRecognizerFactories;
late Set<OneSequenceGestureRecognizer> _gestureRecognizers;
final UiKitViewController controller;
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) {
recognizer.addPointer(event);
}
}
@override
String get debugDescription => 'UIKit view';
@override
void didStopTrackingLastPointer(int pointer) { }
@override
void handleEvent(PointerEvent event) {
stopTrackingIfPointerNoLongerDown(event);
}
@override
void acceptGesture(int pointer) {
controller.acceptGesture();
}
@override
void rejectGesture(int pointer) {
controller.rejectGesture();
}
void reset() {
resolve(GestureDisposition.rejected);
}
}
typedef _HandlePointerEvent = Future<void> Function(PointerEvent event);
// This recognizer constructs gesture recognizers from a set of gesture recognizer factories
// it was give, adds all of them to a gesture arena team with the _PlatformViewGestureRecognizer
// as the team captain.
// As long as the gesture arena is unresolved, the recognizer caches all pointer events.
// When the team wins, the recognizer sends all the cached pointer events to `_handlePointerEvent`, and
// sets itself to a "forwarding mode" where it will forward any new pointer event to `_handlePointerEvent`.
class _PlatformViewGestureRecognizer extends OneSequenceGestureRecognizer {
_PlatformViewGestureRecognizer(
_HandlePointerEvent handlePointerEvent,
this.gestureRecognizerFactories
) {
team = GestureArenaTeam()
..captain = this;
_gestureRecognizers = gestureRecognizerFactories.map(
(Factory<OneSequenceGestureRecognizer> recognizerFactory) {
final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor();
gestureRecognizer.team = team;
// The below gesture recognizers requires at least one non-empty callback to
// compete in the gesture arena.
// https://github.com/flutter/flutter/issues/35394#issuecomment-562285087
if (gestureRecognizer is LongPressGestureRecognizer) {
gestureRecognizer.onLongPress ??= (){};
} else if (gestureRecognizer is DragGestureRecognizer) {
gestureRecognizer.onDown ??= (_){};
} else if (gestureRecognizer is TapGestureRecognizer) {
gestureRecognizer.onTapDown ??= (_){};
}
return gestureRecognizer;
},
).toSet();
_handlePointerEvent = handlePointerEvent;
}
late _HandlePointerEvent _handlePointerEvent;
// Maps a pointer to a list of its cached pointer events.
// Before the arena for a pointer is resolved all events are cached here, if we win the arena
// the cached events are dispatched to `_handlePointerEvent`, if we lose the arena we clear the cache for
// the pointer.
final Map<int, List<PointerEvent>> cachedEvents = <int, List<PointerEvent>>{};
// Pointer for which we have already won the arena, events for pointers in this set are
// immediately dispatched to `_handlePointerEvent`.
final Set<int> forwardedPointers = <int>{};
// 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>> gestureRecognizerFactories;
late Set<OneSequenceGestureRecognizer> _gestureRecognizers;
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
for (final OneSequenceGestureRecognizer recognizer in _gestureRecognizers) {
recognizer.addPointer(event);
}
}
@override
String get debugDescription => 'Platform view';
@override
void didStopTrackingLastPointer(int pointer) { }
@override
void handleEvent(PointerEvent event) {
if (!forwardedPointers.contains(event.pointer)) {
_cacheEvent(event);
} else {
_handlePointerEvent(event);
}
stopTrackingIfPointerNoLongerDown(event);
}
@override
void acceptGesture(int pointer) {
_flushPointerCache(pointer);
forwardedPointers.add(pointer);
}
@override
void rejectGesture(int pointer) {
stopTrackingPointer(pointer);
cachedEvents.remove(pointer);
}
void _cacheEvent(PointerEvent event) {
if (!cachedEvents.containsKey(event.pointer)) {
cachedEvents[event.pointer] = <PointerEvent> [];
}
cachedEvents[event.pointer]!.add(event);
}
void _flushPointerCache(int pointer) {
cachedEvents.remove(pointer)?.forEach(_handlePointerEvent);
}
@override
void stopTrackingPointer(int pointer) {
super.stopTrackingPointer(pointer);
forwardedPointers.remove(pointer);
}
void reset() {
forwardedPointers.forEach(super.stopTrackingPointer);
forwardedPointers.clear();
cachedEvents.keys.forEach(super.stopTrackingPointer);
cachedEvents.clear();
resolve(GestureDisposition.rejected);
}
}
/// A render object for embedding a platform view.
///
/// [PlatformViewRenderBox] presents a platform view by adding a [PlatformViewLayer] layer,
/// integrates it with the gesture arenas system and adds relevant semantic nodes to the semantics tree.
class PlatformViewRenderBox extends RenderBox with _PlatformViewGestureMixin {
/// Creating a render object for a [PlatformViewSurface].
PlatformViewRenderBox({
required PlatformViewController controller,
required PlatformViewHitTestBehavior hitTestBehavior,
required Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
}) : assert(controller.viewId > -1),
_controller = controller {
this.hitTestBehavior = hitTestBehavior;
updateGestureRecognizers(gestureRecognizers);
}
/// The controller for this render object.
PlatformViewController get controller => _controller;
PlatformViewController _controller;
/// Setting this value to a new value will result in a repaint.
set controller(covariant PlatformViewController controller) {
assert(controller.viewId > -1);
if (_controller == controller) {
return;
}
final bool needsSemanticsUpdate = _controller.viewId != controller.viewId;
_controller = controller;
markNeedsPaint();
if (needsSemanticsUpdate) {
markNeedsSemanticsUpdate();
}
}
/// {@template flutter.rendering.PlatformViewRenderBox.updateGestureRecognizers}
/// Updates which gestures should be forwarded to the platform view.
///
/// Gesture recognizers created by factories in this set participate in the gesture arena for each
/// pointer that was put down on the render box. If any of the recognizers on this list wins the
/// gesture arena, the entire pointer event sequence starting from the pointer down event
/// will be dispatched to the Android view.
///
/// The `gestureRecognizers` property must not contain more than one factory with the same [Factory.type].
///
/// Setting a new set of gesture recognizer factories with the same [Factory.type]s as the current
/// set has no effect, because the factories' constructors would have already been called with the previous set.
/// {@endtemplate}
///
/// Any active gesture arena the `PlatformView` participates in is rejected when the
/// set of gesture recognizers is changed.
void updateGestureRecognizers(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
_updateGestureRecognizersWithCallBack(gestureRecognizers, _controller.dispatchPointerEvent);
}
@override
bool get sizedByParent => true;
@override
bool get alwaysNeedsCompositing => true;
@override
bool get isRepaintBoundary => true;
@override
@protected
Size computeDryLayout(covariant BoxConstraints constraints) {
return constraints.biggest;
}
@override
void paint(PaintingContext context, Offset offset) {
context.addLayer(PlatformViewLayer(
rect: offset & size,
viewId: _controller.viewId,
));
}
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
config.isSemanticBoundary = true;
config.platformViewId = _controller.viewId;
}
}
/// The Mixin handling the pointer events and gestures of a platform view render box.
mixin _PlatformViewGestureMixin on RenderBox implements MouseTrackerAnnotation {
/// How to behave during hit testing.
// Changing _hitTestBehavior might affect which objects are considered hovered over.
set hitTestBehavior(PlatformViewHitTestBehavior value) {
if (value != _hitTestBehavior) {
_hitTestBehavior = value;
if (owner != null) {
markNeedsPaint();
}
}
}
PlatformViewHitTestBehavior? _hitTestBehavior;
_HandlePointerEvent? _handlePointerEvent;
/// {@macro flutter.rendering.RenderAndroidView.updateGestureRecognizers}
///
/// Any active gesture arena the `PlatformView` participates in is rejected when the
/// set of gesture recognizers is changed.
void _updateGestureRecognizersWithCallBack(Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers, _HandlePointerEvent handlePointerEvent) {
assert(
_factoriesTypeSet(gestureRecognizers).length == gestureRecognizers.length,
'There were multiple gesture recognizer factories for the same type, there must only be a single '
'gesture recognizer factory for each gesture recognizer type.',
);
if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) {
return;
}
_gestureRecognizer?.dispose();
_gestureRecognizer = _PlatformViewGestureRecognizer(handlePointerEvent, gestureRecognizers);
_handlePointerEvent = handlePointerEvent;
}
_PlatformViewGestureRecognizer? _gestureRecognizer;
@override
bool hitTest(BoxHitTestResult result, { required Offset position }) {
if (_hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position)) {
return false;
}
result.add(BoxHitTestEntry(this, position));
return _hitTestBehavior == PlatformViewHitTestBehavior.opaque;
}
@override
bool hitTestSelf(Offset position) => _hitTestBehavior != PlatformViewHitTestBehavior.transparent;
@override
PointerEnterEventListener? get onEnter => null;
@override
PointerExitEventListener? get onExit => null;
@override
MouseCursor get cursor => MouseCursor.uncontrolled;
@override
bool get validForMouseTracker => true;
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
if (event is PointerDownEvent) {
_gestureRecognizer!.addPointer(event);
}
if (event is PointerHoverEvent) {
_handlePointerEvent?.call(event);
}
}
@override
void detach() {
_gestureRecognizer!.reset();
super.detach();
}
@override
void dispose() {
_gestureRecognizer?.dispose();
super.dispose();
}
}
| flutter/packages/flutter/lib/src/rendering/platform_view.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/platform_view.dart",
"repo_id": "flutter",
"token_count": 9113
} | 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 'dart:math' as math;
import 'dart:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'box.dart';
import 'layer.dart';
import 'layout_helper.dart';
import 'object.dart';
/// An immutable 2D, axis-aligned, floating-point rectangle whose coordinates
/// are given relative to another rectangle's edges, known as the container.
/// Since the dimensions of the rectangle are relative to those of the
/// container, this class has no width and height members. To determine the
/// width or height of the rectangle, convert it to a [Rect] using [toRect()]
/// (passing the container's own Rect), and then examine that object.
@immutable
class RelativeRect {
/// Creates a RelativeRect with the given values.
const RelativeRect.fromLTRB(this.left, this.top, this.right, this.bottom);
/// Creates a RelativeRect from a Rect and a Size. The Rect (first argument)
/// and the RelativeRect (the output) are in the coordinate space of the
/// rectangle described by the Size, with 0,0 being at the top left.
RelativeRect.fromSize(Rect rect, Size container)
: left = rect.left,
top = rect.top,
right = container.width - rect.right,
bottom = container.height - rect.bottom;
/// Creates a RelativeRect from two Rects. The second Rect provides the
/// container, the first provides the rectangle, in the same coordinate space,
/// that is to be converted to a RelativeRect. The output will be in the
/// container's coordinate space.
///
/// For example, if the top left of the rect is at 0,0, and the top left of
/// the container is at 100,100, then the top left of the output will be at
/// -100,-100.
///
/// If the first rect is actually in the container's coordinate space, then
/// use [RelativeRect.fromSize] and pass the container's size as the second
/// argument instead.
RelativeRect.fromRect(Rect rect, Rect container)
: left = rect.left - container.left,
top = rect.top - container.top,
right = container.right - rect.right,
bottom = container.bottom - rect.bottom;
/// Creates a RelativeRect from horizontal position using `start` and `end`
/// rather than `left` and `right`.
///
/// If `textDirection` is [TextDirection.rtl], then the `start` argument is
/// used for the [right] property and the `end` argument is used for the
/// [left] property. Otherwise, if `textDirection` is [TextDirection.ltr],
/// then the `start` argument is used for the [left] property and the `end`
/// argument is used for the [right] property.
factory RelativeRect.fromDirectional({
required TextDirection textDirection,
required double start,
required double top,
required double end,
required double bottom,
}) {
final (double left, double right) = switch (textDirection) {
TextDirection.rtl => (end, start),
TextDirection.ltr => (start, end),
};
return RelativeRect.fromLTRB(left, top, right, bottom);
}
/// A rect that covers the entire container.
static const RelativeRect fill = RelativeRect.fromLTRB(0.0, 0.0, 0.0, 0.0);
/// Distance from the left side of the container to the left side of this rectangle.
///
/// May be negative if the left side of the rectangle is outside of the container.
final double left;
/// Distance from the top side of the container to the top side of this rectangle.
///
/// May be negative if the top side of the rectangle is outside of the container.
final double top;
/// Distance from the right side of the container to the right side of this rectangle.
///
/// May be positive if the right side of the rectangle is outside of the container.
final double right;
/// Distance from the bottom side of the container to the bottom side of this rectangle.
///
/// May be positive if the bottom side of the rectangle is outside of the container.
final double bottom;
/// Returns whether any of the values are greater than zero.
///
/// This corresponds to one of the sides ([left], [top], [right], or [bottom]) having
/// some positive inset towards the center.
bool get hasInsets => left > 0.0 || top > 0.0 || right > 0.0 || bottom > 0.0;
/// Returns a new rectangle object translated by the given offset.
RelativeRect shift(Offset offset) {
return RelativeRect.fromLTRB(left + offset.dx, top + offset.dy, right - offset.dx, bottom - offset.dy);
}
/// Returns a new rectangle with edges moved outwards by the given delta.
RelativeRect inflate(double delta) {
return RelativeRect.fromLTRB(left - delta, top - delta, right - delta, bottom - delta);
}
/// Returns a new rectangle with edges moved inwards by the given delta.
RelativeRect deflate(double delta) {
return inflate(-delta);
}
/// Returns a new rectangle that is the intersection of the given rectangle and this rectangle.
RelativeRect intersect(RelativeRect other) {
return RelativeRect.fromLTRB(
math.max(left, other.left),
math.max(top, other.top),
math.max(right, other.right),
math.max(bottom, other.bottom),
);
}
/// Convert this [RelativeRect] to a [Rect], in the coordinate space of the container.
///
/// See also:
///
/// * [toSize], which returns the size part of the rect, based on the size of
/// the container.
Rect toRect(Rect container) {
return Rect.fromLTRB(left, top, container.width - right, container.height - bottom);
}
/// Convert this [RelativeRect] to a [Size], assuming a container with the given size.
///
/// See also:
///
/// * [toRect], which also computes the position relative to the container.
Size toSize(Size container) {
return Size(container.width - left - right, container.height - top - bottom);
}
/// Linearly interpolate between two RelativeRects.
///
/// If either rect is null, this function interpolates from [RelativeRect.fill].
///
/// {@macro dart.ui.shadow.lerp}
static RelativeRect? lerp(RelativeRect? a, RelativeRect? b, double t) {
if (identical(a, b)) {
return a;
}
if (a == null) {
return RelativeRect.fromLTRB(b!.left * t, b.top * t, b.right * t, b.bottom * t);
}
if (b == null) {
final double k = 1.0 - t;
return RelativeRect.fromLTRB(b!.left * k, b.top * k, b.right * k, b.bottom * k);
}
return RelativeRect.fromLTRB(
lerpDouble(a.left, b.left, t)!,
lerpDouble(a.top, b.top, t)!,
lerpDouble(a.right, b.right, t)!,
lerpDouble(a.bottom, b.bottom, t)!,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is RelativeRect
&& other.left == left
&& other.top == top
&& other.right == right
&& other.bottom == bottom;
}
@override
int get hashCode => Object.hash(left, top, right, bottom);
@override
String toString() => 'RelativeRect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})';
}
/// Parent data for use with [RenderStack].
class StackParentData extends ContainerBoxParentData<RenderBox> {
/// The distance by which the child's top edge is inset from the top of the stack.
double? top;
/// The distance by which the child's right edge is inset from the right of the stack.
double? right;
/// The distance by which the child's bottom edge is inset from the bottom of the stack.
double? bottom;
/// The distance by which the child's left edge is inset from the left of the stack.
double? left;
/// The child's width.
///
/// Ignored if both left and right are non-null.
double? width;
/// The child's height.
///
/// Ignored if both top and bottom are non-null.
double? height;
/// Get or set the current values in terms of a RelativeRect object.
RelativeRect get rect => RelativeRect.fromLTRB(left!, top!, right!, bottom!);
set rect(RelativeRect value) {
top = value.top;
right = value.right;
bottom = value.bottom;
left = value.left;
}
/// Whether this child is considered positioned.
///
/// A child is positioned if any of the top, right, bottom, or left properties
/// are non-null. Positioned children do not factor into determining the size
/// of the stack but are instead placed relative to the non-positioned
/// children in the stack.
bool get isPositioned => top != null || right != null || bottom != null || left != null || width != null || height != null;
@override
String toString() {
final List<String> values = <String>[
if (top != null) 'top=${debugFormatDouble(top)}',
if (right != null) 'right=${debugFormatDouble(right)}',
if (bottom != null) 'bottom=${debugFormatDouble(bottom)}',
if (left != null) 'left=${debugFormatDouble(left)}',
if (width != null) 'width=${debugFormatDouble(width)}',
if (height != null) 'height=${debugFormatDouble(height)}',
];
if (values.isEmpty) {
values.add('not positioned');
}
values.add(super.toString());
return values.join('; ');
}
}
/// How to size the non-positioned children of a [Stack].
///
/// This enum is used with [Stack.fit] and [RenderStack.fit] to control
/// how the [BoxConstraints] passed from the stack's parent to the stack's child
/// are adjusted.
///
/// See also:
///
/// * [Stack], the widget that uses this.
/// * [RenderStack], the render object that implements the stack algorithm.
enum StackFit {
/// The constraints passed to the stack from its parent are loosened.
///
/// For example, if the stack has constraints that force it to 350x600, then
/// this would allow the non-positioned children of the stack to have any
/// width from zero to 350 and any height from zero to 600.
///
/// See also:
///
/// * [Center], which loosens the constraints passed to its child and then
/// centers the child in itself.
/// * [BoxConstraints.loosen], which implements the loosening of box
/// constraints.
loose,
/// The constraints passed to the stack from its parent are tightened to the
/// biggest size allowed.
///
/// For example, if the stack has loose constraints with a width in the range
/// 10 to 100 and a height in the range 0 to 600, then the non-positioned
/// children of the stack would all be sized as 100 pixels wide and 600 high.
expand,
/// The constraints passed to the stack from its parent are passed unmodified
/// to the non-positioned children.
///
/// For example, if a [Stack] is an [Expanded] child of a [Row], the
/// horizontal constraints will be tight and the vertical constraints will be
/// loose.
passthrough,
}
/// Implements the stack layout algorithm.
///
/// In a stack layout, the children are positioned on top of each other in the
/// order in which they appear in the child list. First, the non-positioned
/// children (those with null values for top, right, bottom, and left) are
/// laid out and initially placed in the upper-left corner of the stack. The
/// stack is then sized to enclose all of the non-positioned children. If there
/// are no non-positioned children, the stack becomes as large as possible.
///
/// The final location of non-positioned children is determined by the alignment
/// parameter. The left of each non-positioned child becomes the
/// difference between the child's width and the stack's width scaled by
/// alignment.x. The top of each non-positioned child is computed
/// similarly and scaled by alignment.y. So if the alignment x and y properties
/// are 0.0 (the default) then the non-positioned children remain in the
/// upper-left corner. If the alignment x and y properties are 0.5 then the
/// non-positioned children are centered within the stack.
///
/// Next, the positioned children are laid out. If a child has top and bottom
/// values that are both non-null, the child is given a fixed height determined
/// by subtracting the sum of the top and bottom values from the height of the stack.
/// Similarly, if the child has right and left values that are both non-null,
/// the child is given a fixed width derived from the stack's width.
/// Otherwise, the child is given unbounded constraints in the non-fixed dimensions.
///
/// Once the child is laid out, the stack positions the child
/// according to the top, right, bottom, and left properties of their
/// [StackParentData]. For example, if the bottom value is 10.0, the
/// bottom edge of the child will be inset 10.0 pixels from the bottom
/// edge of the stack. If the child extends beyond the bounds of the
/// stack, the stack will clip the child's painting to the bounds of
/// the stack.
///
/// See also:
///
/// * [RenderFlow]
class RenderStack extends RenderBox
with ContainerRenderObjectMixin<RenderBox, StackParentData>,
RenderBoxContainerDefaultsMixin<RenderBox, StackParentData> {
/// Creates a stack render object.
///
/// By default, the non-positioned children of the stack are aligned by their
/// top left corners.
RenderStack({
List<RenderBox>? children,
AlignmentGeometry alignment = AlignmentDirectional.topStart,
TextDirection? textDirection,
StackFit fit = StackFit.loose,
Clip clipBehavior = Clip.hardEdge,
}) : _alignment = alignment,
_textDirection = textDirection,
_fit = fit,
_clipBehavior = clipBehavior {
addAll(children);
}
bool _hasVisualOverflow = false;
@override
void setupParentData(RenderBox child) {
if (child.parentData is! StackParentData) {
child.parentData = StackParentData();
}
}
Alignment? _resolvedAlignment;
void _resolve() {
if (_resolvedAlignment != null) {
return;
}
_resolvedAlignment = alignment.resolve(textDirection);
}
void _markNeedResolution() {
_resolvedAlignment = null;
markNeedsLayout();
}
/// How to align the non-positioned or partially-positioned children in the
/// stack.
///
/// The non-positioned children are placed relative to each other such that
/// the points determined by [alignment] are co-located. For example, if the
/// [alignment] is [Alignment.topLeft], then the top left corner of
/// each non-positioned child will be located at the same global coordinate.
///
/// Partially-positioned children, those that do not specify an alignment in a
/// particular axis (e.g. that have neither `top` nor `bottom` set), use the
/// alignment to determine how they should be positioned in that
/// under-specified axis.
///
/// If this is set to an [AlignmentDirectional] object, then [textDirection]
/// must not be null.
AlignmentGeometry get alignment => _alignment;
AlignmentGeometry _alignment;
set alignment(AlignmentGeometry value) {
if (_alignment == value) {
return;
}
_alignment = value;
_markNeedResolution();
}
/// The text direction with which to resolve [alignment].
///
/// This may be changed to null, but only after the [alignment] has been changed
/// to a value that does not depend on the direction.
TextDirection? get textDirection => _textDirection;
TextDirection? _textDirection;
set textDirection(TextDirection? value) {
if (_textDirection == value) {
return;
}
_textDirection = value;
_markNeedResolution();
}
/// How to size the non-positioned children in the stack.
///
/// The constraints passed into the [RenderStack] from its parent are either
/// loosened ([StackFit.loose]) or tightened to their biggest size
/// ([StackFit.expand]).
StackFit get fit => _fit;
StackFit _fit;
set fit(StackFit value) {
if (_fit != value) {
_fit = value;
markNeedsLayout();
}
}
/// {@macro flutter.material.Material.clipBehavior}
///
/// Stacks only clip children whose geometry overflow the stack. A child that
/// paints outside its bounds (e.g. a box with a shadow) will not be clipped,
/// regardless of the value of this property. Similarly, a child that itself
/// has a descendant that overflows the stack will not be clipped, as only the
/// geometry of the stack's direct children are considered.
///
/// To clip children whose geometry does not overflow the stack, consider
/// using a [RenderClipRect] render object.
///
/// Defaults to [Clip.hardEdge].
Clip get clipBehavior => _clipBehavior;
Clip _clipBehavior = Clip.hardEdge;
set clipBehavior(Clip value) {
if (value != _clipBehavior) {
_clipBehavior = value;
markNeedsPaint();
markNeedsSemanticsUpdate();
}
}
/// Helper function for calculating the intrinsics metrics of a Stack.
static double getIntrinsicDimension(RenderBox? firstChild, double Function(RenderBox child) mainChildSizeGetter) {
double extent = 0.0;
RenderBox? child = firstChild;
while (child != null) {
final StackParentData childParentData = child.parentData! as StackParentData;
if (!childParentData.isPositioned) {
extent = math.max(extent, mainChildSizeGetter(child));
}
assert(child.parentData == childParentData);
child = childParentData.nextSibling;
}
return extent;
}
@override
double computeMinIntrinsicWidth(double height) {
return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMinIntrinsicWidth(height));
}
@override
double computeMaxIntrinsicWidth(double height) {
return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMaxIntrinsicWidth(height));
}
@override
double computeMinIntrinsicHeight(double width) {
return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMinIntrinsicHeight(width));
}
@override
double computeMaxIntrinsicHeight(double width) {
return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMaxIntrinsicHeight(width));
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
return defaultComputeDistanceToHighestActualBaseline(baseline);
}
/// Lays out the positioned `child` according to `alignment` within a Stack of `size`.
///
/// Returns true when the child has visual overflow.
static bool layoutPositionedChild(RenderBox child, StackParentData childParentData, Size size, Alignment alignment) {
assert(childParentData.isPositioned);
assert(child.parentData == childParentData);
bool hasVisualOverflow = false;
BoxConstraints childConstraints = const BoxConstraints();
if (childParentData.left != null && childParentData.right != null) {
childConstraints = childConstraints.tighten(width: size.width - childParentData.right! - childParentData.left!);
} else if (childParentData.width != null) {
childConstraints = childConstraints.tighten(width: childParentData.width);
}
if (childParentData.top != null && childParentData.bottom != null) {
childConstraints = childConstraints.tighten(height: size.height - childParentData.bottom! - childParentData.top!);
} else if (childParentData.height != null) {
childConstraints = childConstraints.tighten(height: childParentData.height);
}
child.layout(childConstraints, parentUsesSize: true);
final double x;
if (childParentData.left != null) {
x = childParentData.left!;
} else if (childParentData.right != null) {
x = size.width - childParentData.right! - child.size.width;
} else {
x = alignment.alongOffset(size - child.size as Offset).dx;
}
if (x < 0.0 || x + child.size.width > size.width) {
hasVisualOverflow = true;
}
final double y;
if (childParentData.top != null) {
y = childParentData.top!;
} else if (childParentData.bottom != null) {
y = size.height - childParentData.bottom! - child.size.height;
} else {
y = alignment.alongOffset(size - child.size as Offset).dy;
}
if (y < 0.0 || y + child.size.height > size.height) {
hasVisualOverflow = true;
}
childParentData.offset = Offset(x, y);
return hasVisualOverflow;
}
@override
@protected
Size computeDryLayout(covariant BoxConstraints constraints) {
return _computeSize(
constraints: constraints,
layoutChild: ChildLayoutHelper.dryLayoutChild,
);
}
Size _computeSize({required BoxConstraints constraints, required ChildLayouter layoutChild}) {
_resolve();
assert(_resolvedAlignment != null);
bool hasNonPositionedChildren = false;
if (childCount == 0) {
return (constraints.biggest.isFinite) ? constraints.biggest : constraints.smallest;
}
double width = constraints.minWidth;
double height = constraints.minHeight;
final BoxConstraints nonPositionedConstraints = switch (fit) {
StackFit.loose => constraints.loosen(),
StackFit.expand => BoxConstraints.tight(constraints.biggest),
StackFit.passthrough => constraints,
};
RenderBox? child = firstChild;
while (child != null) {
final StackParentData childParentData = child.parentData! as StackParentData;
if (!childParentData.isPositioned) {
hasNonPositionedChildren = true;
final Size childSize = layoutChild(child, nonPositionedConstraints);
width = math.max(width, childSize.width);
height = math.max(height, childSize.height);
}
child = childParentData.nextSibling;
}
final Size size;
if (hasNonPositionedChildren) {
size = Size(width, height);
assert(size.width == constraints.constrainWidth(width));
assert(size.height == constraints.constrainHeight(height));
} else {
size = constraints.biggest;
}
assert(size.isFinite);
return size;
}
@override
void performLayout() {
final BoxConstraints constraints = this.constraints;
_hasVisualOverflow = false;
size = _computeSize(
constraints: constraints,
layoutChild: ChildLayoutHelper.layoutChild,
);
assert(_resolvedAlignment != null);
RenderBox? child = firstChild;
while (child != null) {
final StackParentData childParentData = child.parentData! as StackParentData;
if (!childParentData.isPositioned) {
childParentData.offset = _resolvedAlignment!.alongOffset(size - child.size as Offset);
} else {
_hasVisualOverflow = layoutPositionedChild(child, childParentData, size, _resolvedAlignment!) || _hasVisualOverflow;
}
assert(child.parentData == childParentData);
child = childParentData.nextSibling;
}
}
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return defaultHitTestChildren(result, position: position);
}
/// Override in subclasses to customize how the stack paints.
///
/// By default, the stack uses [defaultPaint]. This function is called by
/// [paint] after potentially applying a clip to contain visual overflow.
@protected
void paintStack(PaintingContext context, Offset offset) {
defaultPaint(context, offset);
}
@override
void paint(PaintingContext context, Offset offset) {
if (clipBehavior != Clip.none && _hasVisualOverflow) {
_clipRectLayer.layer = context.pushClipRect(
needsCompositing,
offset,
Offset.zero & size,
paintStack,
clipBehavior: clipBehavior,
oldLayer: _clipRectLayer.layer,
);
} else {
_clipRectLayer.layer = null;
paintStack(context, offset);
}
}
final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>();
@override
void dispose() {
_clipRectLayer.layer = null;
super.dispose();
}
@override
Rect? describeApproximatePaintClip(RenderObject child) {
switch (clipBehavior) {
case Clip.none:
return null;
case Clip.hardEdge:
case Clip.antiAlias:
case Clip.antiAliasWithSaveLayer:
return _hasVisualOverflow ? Offset.zero & size : null;
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
properties.add(EnumProperty<TextDirection>('textDirection', textDirection));
properties.add(EnumProperty<StackFit>('fit', fit));
properties.add(EnumProperty<Clip>('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge));
}
}
/// Implements the same layout algorithm as RenderStack but only paints the child
/// specified by index.
///
/// Although only one child is displayed, the cost of the layout algorithm is
/// still O(N), like an ordinary stack.
class RenderIndexedStack extends RenderStack {
/// Creates a stack render object that paints a single child.
///
/// If the [index] parameter is null, nothing is displayed.
RenderIndexedStack({
super.children,
super.alignment,
super.textDirection,
super.fit,
super.clipBehavior,
int? index = 0,
}) : _index = index;
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
final RenderBox? displayedChild = _childAtIndex();
if (displayedChild != null) {
visitor(displayedChild);
}
}
/// The index of the child to show, null if nothing is to be displayed.
int? get index => _index;
int? _index;
set index(int? value) {
if (_index != value) {
_index = value;
markNeedsLayout();
}
}
RenderBox? _childAtIndex() {
final int? index = this.index;
if (index == null) {
return null;
}
RenderBox? child = firstChild;
for (int i = 0; i < index && child != null; i += 1) {
child = childAfter(child);
}
assert(firstChild == null || child != null);
return child;
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
final RenderBox? displayedChild = _childAtIndex();
if (displayedChild == null) {
return null;
}
final StackParentData childParentData = displayedChild.parentData! as StackParentData;
final BaselineOffset offset = BaselineOffset(displayedChild.getDistanceToActualBaseline(baseline)) + childParentData.offset.dy;
return offset.offset;
}
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
final RenderBox? displayedChild = _childAtIndex();
if (displayedChild == null) {
return false;
}
final StackParentData childParentData = displayedChild.parentData! as StackParentData;
return result.addWithPaintOffset(
offset: childParentData.offset,
position: position,
hitTest: (BoxHitTestResult result, Offset transformed) {
assert(transformed == position - childParentData.offset);
return displayedChild.hitTest(result, position: transformed);
},
);
}
@override
void paintStack(PaintingContext context, Offset offset) {
final RenderBox? displayedChild = _childAtIndex();
if (displayedChild == null) {
return;
}
final StackParentData childParentData = displayedChild.parentData! as StackParentData;
context.paintChild(displayedChild, childParentData.offset + offset);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(IntProperty('index', index));
}
@override
List<DiagnosticsNode> debugDescribeChildren() {
final List<DiagnosticsNode> children = <DiagnosticsNode>[];
int i = 0;
RenderObject? child = firstChild;
while (child != null) {
children.add(child.toDiagnosticsNode(
name: 'child ${i + 1}',
style: i != index ? DiagnosticsTreeStyle.offstage : null,
));
child = (child.parentData! as StackParentData).nextSibling;
i += 1;
}
return children;
}
}
| flutter/packages/flutter/lib/src/rendering/stack.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/stack.dart",
"repo_id": "flutter",
"token_count": 8940
} | 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:math' as math;
import 'dart:ui' show Offset, Rect, SemanticsAction, SemanticsFlag, SemanticsUpdate, SemanticsUpdateBuilder, StringAttribute, TextDirection;
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart' show MatrixUtils, TransformProperty;
import 'package:flutter/services.dart';
import 'package:vector_math/vector_math_64.dart';
import 'binding.dart' show SemanticsBinding;
import 'semantics_event.dart';
export 'dart:ui' show Offset, Rect, SemanticsAction, SemanticsFlag, StringAttribute, TextDirection, VoidCallback;
export 'package:flutter/foundation.dart' show DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsTreeStyle, Key, TextTreeConfiguration;
export 'package:flutter/services.dart' show TextSelection;
export 'package:vector_math/vector_math_64.dart' show Matrix4;
export 'semantics_event.dart' show SemanticsEvent;
/// Signature for a function that is called for each [SemanticsNode].
///
/// Return false to stop visiting nodes.
///
/// Used by [SemanticsNode.visitChildren].
typedef SemanticsNodeVisitor = bool Function(SemanticsNode node);
/// Signature for [SemanticsAction]s that move the cursor.
///
/// If `extendSelection` is set to true the cursor movement should extend the
/// current selection or (if nothing is currently selected) start a selection.
typedef MoveCursorHandler = void Function(bool extendSelection);
/// Signature for the [SemanticsAction.setSelection] handlers to change the
/// text selection (or re-position the cursor) to `selection`.
typedef SetSelectionHandler = void Function(TextSelection selection);
/// Signature for the [SemanticsAction.setText] handlers to replace the
/// current text with the input `text`.
typedef SetTextHandler = void Function(String text);
/// Signature for a handler of a [SemanticsAction].
///
/// Returned by [SemanticsConfiguration.getActionHandler].
typedef SemanticsActionHandler = void Function(Object? args);
/// Signature for a function that receives a semantics update and returns no result.
///
/// Used by [SemanticsOwner.onSemanticsUpdate].
typedef SemanticsUpdateCallback = void Function(SemanticsUpdate update);
/// Signature for the [SemanticsConfiguration.childConfigurationsDelegate].
///
/// The input list contains all [SemanticsConfiguration]s that rendering
/// children want to merge upward. One can tag a render child with a
/// [SemanticsTag] and look up its [SemanticsConfiguration]s through
/// [SemanticsConfiguration.tagsChildrenWith].
///
/// The return value is the arrangement of these configs, including which
/// configs continue to merge upward and which configs form sibling merge group.
///
/// Use [ChildSemanticsConfigurationsResultBuilder] to generate the return
/// value.
typedef ChildSemanticsConfigurationsDelegate = ChildSemanticsConfigurationsResult Function(List<SemanticsConfiguration>);
final int _kUnblockedUserActions = SemanticsAction.didGainAccessibilityFocus.index
| SemanticsAction.didLoseAccessibilityFocus.index;
/// A tag for a [SemanticsNode].
///
/// Tags can be interpreted by the parent of a [SemanticsNode]
/// and depending on the presence of a tag the parent can for example decide
/// how to add the tagged node as a child. Tags are not sent to the engine.
///
/// As an example, the [RenderSemanticsGestureHandler] uses tags to determine
/// if a child node should be excluded from the scrollable area for semantic
/// purposes.
///
/// The provided [name] is only used for debugging. Two tags created with the
/// same [name] and the `new` operator are not considered identical. However,
/// two tags created with the same [name] and the `const` operator are always
/// identical.
class SemanticsTag {
/// Creates a [SemanticsTag].
///
/// The provided [name] is only used for debugging. Two tags created with the
/// same [name] and the `new` operator are not considered identical. However,
/// two tags created with the same [name] and the `const` operator are always
/// identical.
const SemanticsTag(this.name);
/// A human-readable name for this tag used for debugging.
///
/// This string is not used to determine if two tags are identical.
final String name;
@override
String toString() => '${objectRuntimeType(this, 'SemanticsTag')}($name)';
}
/// The result that contains the arrangement for the child
/// [SemanticsConfiguration]s.
///
/// When the [PipelineOwner] builds the semantics tree, it uses the returned
/// [ChildSemanticsConfigurationsResult] from
/// [SemanticsConfiguration.childConfigurationsDelegate] to decide how semantics nodes
/// should form.
///
/// Use [ChildSemanticsConfigurationsResultBuilder] to build the result.
class ChildSemanticsConfigurationsResult {
ChildSemanticsConfigurationsResult._(this.mergeUp, this.siblingMergeGroups);
/// Returns the [SemanticsConfiguration]s that are supposed to be merged into
/// the parent semantics node.
///
/// [SemanticsConfiguration]s that are either semantics boundaries or are
/// conflicting with other [SemanticsConfiguration]s will form explicit
/// semantics nodes. All others will be merged into the parent.
final List<SemanticsConfiguration> mergeUp;
/// The groups of child semantics configurations that want to merge together
/// and form a sibling [SemanticsNode].
///
/// All the [SemanticsConfiguration]s in a given group that are either
/// semantics boundaries or are conflicting with other
/// [SemanticsConfiguration]s of the same group will be excluded from the
/// sibling merge group and form independent semantics nodes as usual.
///
/// The result [SemanticsNode]s from the merges are attached as the sibling
/// nodes of the immediate parent semantics node. For example, a `RenderObjectA`
/// has a rendering child, `RenderObjectB`. If both of them form their own
/// semantics nodes, `SemanticsNodeA` and `SemanticsNodeB`, any semantics node
/// created from sibling merge groups of `RenderObjectB` will be attach to
/// `SemanticsNodeA` as a sibling of `SemanticsNodeB`.
final List<List<SemanticsConfiguration>> siblingMergeGroups;
}
/// The builder to build a [ChildSemanticsConfigurationsResult] based on its
/// annotations.
///
/// To use this builder, one can use [markAsMergeUp] and
/// [markAsSiblingMergeGroup] to annotate the arrangement of
/// [SemanticsConfiguration]s. Once all the configs are annotated, use [build]
/// to generate the [ChildSemanticsConfigurationsResult].
class ChildSemanticsConfigurationsResultBuilder {
/// Creates a [ChildSemanticsConfigurationsResultBuilder].
ChildSemanticsConfigurationsResultBuilder();
final List<SemanticsConfiguration> _mergeUp = <SemanticsConfiguration>[];
final List<List<SemanticsConfiguration>> _siblingMergeGroups = <List<SemanticsConfiguration>>[];
/// Marks the [SemanticsConfiguration] to be merged into the parent semantics
/// node.
///
/// The [SemanticsConfiguration] will be added to the
/// [ChildSemanticsConfigurationsResult.mergeUp] that this builder builds.
void markAsMergeUp(SemanticsConfiguration config) => _mergeUp.add(config);
/// Marks a group of [SemanticsConfiguration]s to merge together
/// and form a sibling [SemanticsNode].
///
/// The group of [SemanticsConfiguration]s will be added to the
/// [ChildSemanticsConfigurationsResult.siblingMergeGroups] that this builder builds.
void markAsSiblingMergeGroup(List<SemanticsConfiguration> configs) => _siblingMergeGroups.add(configs);
/// Builds a [ChildSemanticsConfigurationsResult] contains the arrangement.
ChildSemanticsConfigurationsResult build() {
assert((){
final Set<SemanticsConfiguration> seenConfigs = <SemanticsConfiguration>{};
for (final SemanticsConfiguration config in <SemanticsConfiguration>[..._mergeUp, ..._siblingMergeGroups.flattened]) {
assert(
seenConfigs.add(config),
'Duplicated SemanticsConfigurations. This can happen if the same '
'SemanticsConfiguration was marked twice in markAsMergeUp and/or '
'markAsSiblingMergeGroup'
);
}
return true;
}());
return ChildSemanticsConfigurationsResult._(_mergeUp, _siblingMergeGroups);
}
}
/// An identifier of a custom semantics action.
///
/// Custom semantics actions can be provided to make complex user
/// interactions more accessible. For instance, if an application has a
/// drag-and-drop list that requires the user to press and hold an item
/// to move it, users interacting with the application using a hardware
/// switch may have difficulty. This can be made accessible by creating custom
/// actions and pairing them with handlers that move a list item up or down in
/// the list.
///
/// In Android, these actions are presented in the local context menu. In iOS,
/// these are presented in the radial context menu.
///
/// Localization and text direction do not automatically apply to the provided
/// label or hint.
///
/// Instances of this class should either be instantiated with const or
/// new instances cached in static fields.
///
/// See also:
///
/// * [SemanticsProperties], where the handler for a custom action is provided.
@immutable
class CustomSemanticsAction {
/// Creates a new [CustomSemanticsAction].
///
/// The [label] must not be empty.
const CustomSemanticsAction({required String this.label})
: assert(label != ''),
hint = null,
action = null;
/// Creates a new [CustomSemanticsAction] that overrides a standard semantics
/// action.
///
/// The [hint] must not be empty.
const CustomSemanticsAction.overridingAction({required String this.hint, required SemanticsAction this.action})
: assert(hint != ''),
label = null;
/// The user readable name of this custom semantics action.
final String? label;
/// The hint description of this custom semantics action.
final String? hint;
/// The standard semantics action this action replaces.
final SemanticsAction? action;
@override
int get hashCode => Object.hash(label, hint, action);
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is CustomSemanticsAction
&& other.label == label
&& other.hint == hint
&& other.action == action;
}
@override
String toString() {
return 'CustomSemanticsAction(${_ids[this]}, label:$label, hint:$hint, action:$action)';
}
// Logic to assign a unique id to each custom action without requiring
// user specification.
static int _nextId = 0;
static final Map<int, CustomSemanticsAction> _actions = <int, CustomSemanticsAction>{};
static final Map<CustomSemanticsAction, int> _ids = <CustomSemanticsAction, int>{};
/// Get the identifier for a given `action`.
static int getIdentifier(CustomSemanticsAction action) {
int? result = _ids[action];
if (result == null) {
result = _nextId++;
_ids[action] = result;
_actions[result] = action;
}
return result;
}
/// Get the `action` for a given identifier.
static CustomSemanticsAction? getAction(int id) {
return _actions[id];
}
/// Resets internal state between tests. Does nothing if asserts are disabled.
@visibleForTesting
static void resetForTests() {
assert(() {
_actions.clear();
_ids.clear();
_nextId = 0;
return true;
}());
}
}
/// A string that carries a list of [StringAttribute]s.
@immutable
class AttributedString {
/// Creates a attributed string.
///
/// The [TextRange] in the [attributes] must be inside the length of the
/// [string].
///
/// The [attributes] must not be changed after the attributed string is
/// created.
AttributedString(
this.string, {
this.attributes = const <StringAttribute>[],
}) : assert(string.isNotEmpty || attributes.isEmpty),
assert(() {
for (final StringAttribute attribute in attributes) {
assert(
string.length >= attribute.range.start &&
string.length >= attribute.range.end,
'The range in $attribute is outside of the string $string',
);
}
return true;
}());
/// The plain string stored in the attributed string.
final String string;
/// The attributes this string carries.
///
/// The list must not be modified after this string is created.
final List<StringAttribute> attributes;
/// Returns a new [AttributedString] by concatenate the operands
///
/// The string attribute list of the returned [AttributedString] will contains
/// the string attributes from both operands with updated text ranges.
AttributedString operator +(AttributedString other) {
if (string.isEmpty) {
return other;
}
if (other.string.isEmpty) {
return this;
}
// None of the strings is empty.
final String newString = string + other.string;
final List<StringAttribute> newAttributes = List<StringAttribute>.of(attributes);
if (other.attributes.isNotEmpty) {
final int offset = string.length;
for (final StringAttribute attribute in other.attributes) {
final TextRange newRange = TextRange(
start: attribute.range.start + offset,
end: attribute.range.end + offset,
);
final StringAttribute adjustedAttribute = attribute.copy(range: newRange);
newAttributes.add(adjustedAttribute);
}
}
return AttributedString(newString, attributes: newAttributes);
}
/// Two [AttributedString]s are equal if their string and attributes are.
@override
bool operator ==(Object other) {
return other.runtimeType == runtimeType
&& other is AttributedString
&& other.string == string
&& listEquals<StringAttribute>(other.attributes, attributes);
}
@override
int get hashCode => Object.hash(string, attributes);
@override
String toString() {
return "${objectRuntimeType(this, 'AttributedString')}('$string', attributes: $attributes)";
}
}
/// A [DiagnosticsProperty] for [AttributedString]s, which shows a string
/// when there are no attributes, and more details otherwise.
class AttributedStringProperty extends DiagnosticsProperty<AttributedString> {
/// Create a diagnostics property for an [AttributedString] object.
///
/// Such properties are used with [SemanticsData] objects.
AttributedStringProperty(
String super.name,
super.value, {
super.showName,
this.showWhenEmpty = false,
super.defaultValue,
super.level,
super.description,
});
/// Whether to show the property when the [value] is an [AttributedString]
/// whose [AttributedString.string] is the empty string.
///
/// This overrides [defaultValue].
final bool showWhenEmpty;
@override
bool get isInteresting => super.isInteresting && (showWhenEmpty || (value != null && value!.string.isNotEmpty));
@override
String valueToString({TextTreeConfiguration? parentConfiguration}) {
if (value == null) {
return 'null';
}
String text = value!.string;
if (parentConfiguration != null &&
!parentConfiguration.lineBreakProperties) {
// This follows a similar pattern to StringProperty.
text = text.replaceAll('\n', r'\n');
}
if (value!.attributes.isEmpty) {
return '"$text"';
}
return '"$text" ${value!.attributes}'; // the attributes will be in square brackets since they're a list
}
}
/// Summary information about a [SemanticsNode] object.
///
/// A semantics node might [SemanticsNode.mergeAllDescendantsIntoThisNode],
/// which means the individual fields on the semantics node don't fully describe
/// the semantics at that node. This data structure contains the full semantics
/// for the node.
///
/// Typically obtained from [SemanticsNode.getSemanticsData].
@immutable
class SemanticsData with Diagnosticable {
/// Creates a semantics data object.
///
/// If [label] is not empty, then [textDirection] must also not be null.
SemanticsData({
required this.flags,
required this.actions,
required this.identifier,
required this.attributedLabel,
required this.attributedValue,
required this.attributedIncreasedValue,
required this.attributedDecreasedValue,
required this.attributedHint,
required this.tooltip,
required this.textDirection,
required this.rect,
required this.elevation,
required this.thickness,
required this.textSelection,
required this.scrollIndex,
required this.scrollChildCount,
required this.scrollPosition,
required this.scrollExtentMax,
required this.scrollExtentMin,
required this.platformViewId,
required this.maxValueLength,
required this.currentValueLength,
this.tags,
this.transform,
this.customSemanticsActionIds,
}) : assert(tooltip == '' || textDirection != null, 'A SemanticsData object with tooltip "$tooltip" had a null textDirection.'),
assert(attributedLabel.string == '' || textDirection != null, 'A SemanticsData object with label "${attributedLabel.string}" had a null textDirection.'),
assert(attributedValue.string == '' || textDirection != null, 'A SemanticsData object with value "${attributedValue.string}" had a null textDirection.'),
assert(attributedDecreasedValue.string == '' || textDirection != null, 'A SemanticsData object with decreasedValue "${attributedDecreasedValue.string}" had a null textDirection.'),
assert(attributedIncreasedValue.string == '' || textDirection != null, 'A SemanticsData object with increasedValue "${attributedIncreasedValue.string}" had a null textDirection.'),
assert(attributedHint.string == '' || textDirection != null, 'A SemanticsData object with hint "${attributedHint.string}" had a null textDirection.');
/// A bit field of [SemanticsFlag]s that apply to this node.
final int flags;
/// A bit field of [SemanticsAction]s that apply to this node.
final int actions;
/// {@macro flutter.semantics.SemanticsProperties.identifier}
final String identifier;
/// A textual description for the current label of the node.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedLabel].
String get label => attributedLabel.string;
/// A textual description for the current label of the node in
/// [AttributedString] format.
///
/// The reading direction is given by [textDirection].
///
/// See also [label], which exposes just the raw text.
final AttributedString attributedLabel;
/// A textual description for the current value of the node.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedValue].
String get value => attributedValue.string;
/// A textual description for the current value of the node in
/// [AttributedString] format.
///
/// The reading direction is given by [textDirection].
///
/// See also [value], which exposes just the raw text.
final AttributedString attributedValue;
/// The value that [value] will become after performing a
/// [SemanticsAction.increase] action.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedIncreasedValue].
String get increasedValue => attributedIncreasedValue.string;
/// The value that [value] will become after performing a
/// [SemanticsAction.increase] action in [AttributedString] format.
///
/// The reading direction is given by [textDirection].
///
/// See also [increasedValue], which exposes just the raw text.
final AttributedString attributedIncreasedValue;
/// The value that [value] will become after performing a
/// [SemanticsAction.decrease] action.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedDecreasedValue].
String get decreasedValue => attributedDecreasedValue.string;
/// The value that [value] will become after performing a
/// [SemanticsAction.decrease] action in [AttributedString] format.
///
/// The reading direction is given by [textDirection].
///
/// See also [decreasedValue], which exposes just the raw text.
final AttributedString attributedDecreasedValue;
/// A brief description of the result of performing an action on this node.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedHint].
String get hint => attributedHint.string;
/// A brief description of the result of performing an action on this node
/// in [AttributedString] format.
///
/// The reading direction is given by [textDirection].
///
/// See also [hint], which exposes just the raw text.
final AttributedString attributedHint;
/// A textual description of the widget's tooltip.
///
/// The reading direction is given by [textDirection].
final String tooltip;
/// The reading direction for the text in [label], [value],
/// [increasedValue], [decreasedValue], and [hint].
final TextDirection? textDirection;
/// The currently selected text (or the position of the cursor) within [value]
/// if this node represents a text field.
final TextSelection? textSelection;
/// The total number of scrollable children that contribute to semantics.
///
/// If the number of children are unknown or unbounded, this value will be
/// null.
final int? scrollChildCount;
/// The index of the first visible semantic child of a scroll node.
final int? scrollIndex;
/// Indicates the current scrolling position in logical pixels if the node is
/// scrollable.
///
/// The properties [scrollExtentMin] and [scrollExtentMax] indicate the valid
/// in-range values for this property. The value for [scrollPosition] may
/// (temporarily) be outside that range, e.g. during an overscroll.
///
/// See also:
///
/// * [ScrollPosition.pixels], from where this value is usually taken.
final double? scrollPosition;
/// Indicates the maximum in-range value for [scrollPosition] if the node is
/// scrollable.
///
/// This value may be infinity if the scroll is unbound.
///
/// See also:
///
/// * [ScrollPosition.maxScrollExtent], from where this value is usually taken.
final double? scrollExtentMax;
/// Indicates the minimum in-range value for [scrollPosition] if the node is
/// scrollable.
///
/// This value may be infinity if the scroll is unbound.
///
/// See also:
///
/// * [ScrollPosition.minScrollExtent], from where this value is usually taken.
final double? scrollExtentMin;
/// The id of the platform view, whose semantics nodes will be added as
/// children to this node.
///
/// If this value is non-null, the SemanticsNode must not have any children
/// as those would be replaced by the semantics nodes of the referenced
/// platform view.
///
/// See also:
///
/// * [AndroidView], which is the platform view for Android.
/// * [UiKitView], which is the platform view for iOS.
final int? platformViewId;
/// The maximum number of characters that can be entered into an editable
/// text field.
///
/// For the purpose of this function a character is defined as one Unicode
/// scalar value.
///
/// This should only be set when [SemanticsFlag.isTextField] is set. Defaults
/// to null, which means no limit is imposed on the text field.
final int? maxValueLength;
/// The current number of characters that have been entered into an editable
/// text field.
///
/// For the purpose of this function a character is defined as one Unicode
/// scalar value.
///
/// This should only be set when [SemanticsFlag.isTextField] is set. This must
/// be set when [maxValueLength] is set.
final int? currentValueLength;
/// The bounding box for this node in its coordinate system.
final Rect rect;
/// The set of [SemanticsTag]s associated with this node.
final Set<SemanticsTag>? tags;
/// The transform from this node's coordinate system to its parent's coordinate system.
///
/// By default, the transform is null, which represents the identity
/// transformation (i.e., that this node has the same coordinate system as its
/// parent).
final Matrix4? transform;
/// The elevation of this node relative to the parent semantics node.
///
/// See also:
///
/// * [SemanticsConfiguration.elevation] for a detailed discussion regarding
/// elevation and semantics.
final double elevation;
/// The extent of this node along the z-axis beyond its [elevation]
///
/// See also:
///
/// * [SemanticsConfiguration.thickness] for a more detailed definition.
final double thickness;
/// The identifiers for the custom semantics actions and standard action
/// overrides for this node.
///
/// The list must be sorted in increasing order.
///
/// See also:
///
/// * [CustomSemanticsAction], for an explanation of custom actions.
final List<int>? customSemanticsActionIds;
/// Whether [flags] contains the given flag.
bool hasFlag(SemanticsFlag flag) => (flags & flag.index) != 0;
/// Whether [actions] contains the given action.
bool hasAction(SemanticsAction action) => (actions & action.index) != 0;
@override
String toStringShort() => objectRuntimeType(this, 'SemanticsData');
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Rect>('rect', rect, showName: false));
properties.add(TransformProperty('transform', transform, showName: false, defaultValue: null));
properties.add(DoubleProperty('elevation', elevation, defaultValue: 0.0));
properties.add(DoubleProperty('thickness', thickness, defaultValue: 0.0));
final List<String> actionSummary = <String>[
for (final SemanticsAction action in SemanticsAction.values)
if ((actions & action.index) != 0)
action.name,
];
final List<String?> customSemanticsActionSummary = customSemanticsActionIds!
.map<String?>((int actionId) => CustomSemanticsAction.getAction(actionId)!.label)
.toList();
properties.add(IterableProperty<String>('actions', actionSummary, ifEmpty: null));
properties.add(IterableProperty<String?>('customActions', customSemanticsActionSummary, ifEmpty: null));
final List<String> flagSummary = <String>[
for (final SemanticsFlag flag in SemanticsFlag.values)
if ((flags & flag.index) != 0)
flag.name,
];
properties.add(IterableProperty<String>('flags', flagSummary, ifEmpty: null));
properties.add(StringProperty('identifier', identifier, defaultValue: ''));
properties.add(AttributedStringProperty('label', attributedLabel));
properties.add(AttributedStringProperty('value', attributedValue));
properties.add(AttributedStringProperty('increasedValue', attributedIncreasedValue));
properties.add(AttributedStringProperty('decreasedValue', attributedDecreasedValue));
properties.add(AttributedStringProperty('hint', attributedHint));
properties.add(StringProperty('tooltip', tooltip, defaultValue: ''));
properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
if (textSelection?.isValid ?? false) {
properties.add(MessageProperty('textSelection', '[${textSelection!.start}, ${textSelection!.end}]'));
}
properties.add(IntProperty('platformViewId', platformViewId, defaultValue: null));
properties.add(IntProperty('maxValueLength', maxValueLength, defaultValue: null));
properties.add(IntProperty('currentValueLength', currentValueLength, defaultValue: null));
properties.add(IntProperty('scrollChildren', scrollChildCount, defaultValue: null));
properties.add(IntProperty('scrollIndex', scrollIndex, defaultValue: null));
properties.add(DoubleProperty('scrollExtentMin', scrollExtentMin, defaultValue: null));
properties.add(DoubleProperty('scrollPosition', scrollPosition, defaultValue: null));
properties.add(DoubleProperty('scrollExtentMax', scrollExtentMax, defaultValue: null));
}
@override
bool operator ==(Object other) {
return other is SemanticsData
&& other.flags == flags
&& other.actions == actions
&& other.identifier == identifier
&& other.attributedLabel == attributedLabel
&& other.attributedValue == attributedValue
&& other.attributedIncreasedValue == attributedIncreasedValue
&& other.attributedDecreasedValue == attributedDecreasedValue
&& other.attributedHint == attributedHint
&& other.tooltip == tooltip
&& other.textDirection == textDirection
&& other.rect == rect
&& setEquals(other.tags, tags)
&& other.scrollChildCount == scrollChildCount
&& other.scrollIndex == scrollIndex
&& other.textSelection == textSelection
&& other.scrollPosition == scrollPosition
&& other.scrollExtentMax == scrollExtentMax
&& other.scrollExtentMin == scrollExtentMin
&& other.platformViewId == platformViewId
&& other.maxValueLength == maxValueLength
&& other.currentValueLength == currentValueLength
&& other.transform == transform
&& other.elevation == elevation
&& other.thickness == thickness
&& _sortedListsEqual(other.customSemanticsActionIds, customSemanticsActionIds);
}
@override
int get hashCode => Object.hash(
flags,
actions,
identifier,
attributedLabel,
attributedValue,
attributedIncreasedValue,
attributedDecreasedValue,
attributedHint,
tooltip,
textDirection,
rect,
tags,
textSelection,
scrollChildCount,
scrollIndex,
scrollPosition,
scrollExtentMax,
scrollExtentMin,
platformViewId,
Object.hash(
maxValueLength,
currentValueLength,
transform,
elevation,
thickness,
customSemanticsActionIds == null ? null : Object.hashAll(customSemanticsActionIds!),
),
);
static bool _sortedListsEqual(List<int>? left, List<int>? right) {
if (left == null && right == null) {
return true;
}
if (left != null && right != null) {
if (left.length != right.length) {
return false;
}
for (int i = 0; i < left.length; i++) {
if (left[i] != right[i]) {
return false;
}
}
return true;
}
return false;
}
}
class _SemanticsDiagnosticableNode extends DiagnosticableNode<SemanticsNode> {
_SemanticsDiagnosticableNode({
super.name,
required super.value,
required super.style,
required this.childOrder,
});
final DebugSemanticsDumpOrder childOrder;
@override
List<DiagnosticsNode> getChildren() => value.debugDescribeChildren(childOrder: childOrder);
}
/// Provides hint values which override the default hints on supported
/// platforms.
///
/// On iOS, these values are always ignored.
@immutable
class SemanticsHintOverrides extends DiagnosticableTree {
/// Creates a semantics hint overrides.
const SemanticsHintOverrides({
this.onTapHint,
this.onLongPressHint,
}) : assert(onTapHint != ''),
assert(onLongPressHint != '');
/// The hint text for a tap action.
///
/// If null, the standard hint is used instead.
///
/// The hint should describe what happens when a tap occurs, not the
/// manner in which a tap is accomplished.
///
/// Bad: 'Double tap to show movies'.
/// Good: 'show movies'.
final String? onTapHint;
/// The hint text for a long press action.
///
/// If null, the standard hint is used instead.
///
/// The hint should describe what happens when a long press occurs, not
/// the manner in which the long press is accomplished.
///
/// Bad: 'Double tap and hold to show tooltip'.
/// Good: 'show tooltip'.
final String? onLongPressHint;
/// Whether there are any non-null hint values.
bool get isNotEmpty => onTapHint != null || onLongPressHint != null;
@override
int get hashCode => Object.hash(onTapHint, onLongPressHint);
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is SemanticsHintOverrides
&& other.onTapHint == onTapHint
&& other.onLongPressHint == onLongPressHint;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(StringProperty('onTapHint', onTapHint, defaultValue: null));
properties.add(StringProperty('onLongPressHint', onLongPressHint, defaultValue: null));
}
}
/// Contains properties used by assistive technologies to make the application
/// more accessible.
///
/// The properties of this class are used to generate a [SemanticsNode]s in the
/// semantics tree.
@immutable
class SemanticsProperties extends DiagnosticableTree {
/// Creates a semantic annotation.
const SemanticsProperties({
this.enabled,
this.checked,
this.mixed,
this.expanded,
this.selected,
this.toggled,
this.button,
this.link,
this.header,
this.textField,
this.slider,
this.keyboardKey,
this.readOnly,
this.focusable,
this.focused,
this.inMutuallyExclusiveGroup,
this.hidden,
this.obscured,
this.multiline,
this.scopesRoute,
this.namesRoute,
this.image,
this.liveRegion,
this.maxValueLength,
this.currentValueLength,
this.identifier,
this.label,
this.attributedLabel,
this.value,
this.attributedValue,
this.increasedValue,
this.attributedIncreasedValue,
this.decreasedValue,
this.attributedDecreasedValue,
this.hint,
this.tooltip,
this.attributedHint,
this.hintOverrides,
this.textDirection,
this.sortKey,
this.tagForChildren,
this.onTap,
this.onLongPress,
this.onScrollLeft,
this.onScrollRight,
this.onScrollUp,
this.onScrollDown,
this.onIncrease,
this.onDecrease,
this.onCopy,
this.onCut,
this.onPaste,
this.onMoveCursorForwardByCharacter,
this.onMoveCursorBackwardByCharacter,
this.onMoveCursorForwardByWord,
this.onMoveCursorBackwardByWord,
this.onSetSelection,
this.onSetText,
this.onDidGainAccessibilityFocus,
this.onDidLoseAccessibilityFocus,
this.onDismiss,
this.customSemanticsActions,
}) : assert(label == null || attributedLabel == null, 'Only one of label or attributedLabel should be provided'),
assert(value == null || attributedValue == null, 'Only one of value or attributedValue should be provided'),
assert(increasedValue == null || attributedIncreasedValue == null, 'Only one of increasedValue or attributedIncreasedValue should be provided'),
assert(decreasedValue == null || attributedDecreasedValue == null, 'Only one of decreasedValue or attributedDecreasedValue should be provided'),
assert(hint == null || attributedHint == null, 'Only one of hint or attributedHint should be provided');
/// If non-null, indicates that this subtree represents something that can be
/// in an enabled or disabled state.
///
/// For example, a button that a user can currently interact with would set
/// this field to true. A button that currently does not respond to user
/// interactions would set this field to false.
final bool? enabled;
/// If non-null, indicates that this subtree represents a checkbox
/// or similar widget with a "checked" state, and what its current
/// state is.
///
/// When the [Checkbox.value] of a tristate Checkbox is null,
/// indicating a mixed-state, this value shall be false, in which
/// case, [mixed] will be true.
///
/// This is mutually exclusive with [toggled] and [mixed].
final bool? checked;
/// If non-null, indicates that this subtree represents a checkbox
/// or similar widget with a "half-checked" state or similar, and
/// whether it is currently in this half-checked state.
///
/// This must be null when [Checkbox.tristate] is false, or
/// when the widget is not a checkbox. When a tristate
/// checkbox is fully unchecked/checked, this value shall
/// be false.
///
/// This is mutually exclusive with [checked] and [toggled].
final bool? mixed;
/// If non-null, indicates that this subtree represents something
/// that can be in an "expanded" or "collapsed" state.
///
/// For example, if a [SubmenuButton] is opened, this property
/// should be set to true; otherwise, this property should be
/// false.
final bool? expanded;
/// If non-null, indicates that this subtree represents a toggle switch
/// or similar widget with an "on" state, and what its current
/// state is.
///
/// This is mutually exclusive with [checked] and [mixed].
final bool? toggled;
/// If non-null indicates that this subtree represents something that can be
/// in a selected or unselected state, and what its current state is.
///
/// The active tab in a tab bar for example is considered "selected", whereas
/// all other tabs are unselected.
final bool? selected;
/// If non-null, indicates that this subtree represents a button.
///
/// TalkBack/VoiceOver provides users with the hint "button" when a button
/// is focused.
final bool? button;
/// If non-null, indicates that this subtree represents a link.
///
/// iOS's VoiceOver provides users with a unique hint when a link is focused.
/// Android's Talkback will announce a link hint the same way it does a
/// button.
final bool? link;
/// If non-null, indicates that this subtree represents a header.
///
/// A header divides into sections. For example, an address book application
/// might define headers A, B, C, etc. to divide the list of alphabetically
/// sorted contacts into sections.
final bool? header;
/// If non-null, indicates that this subtree represents a text field.
///
/// TalkBack/VoiceOver provide special affordances to enter text into a
/// text field.
final bool? textField;
/// If non-null, indicates that this subtree represents a slider.
///
/// Talkback/\VoiceOver provides users with the hint "slider" when a
/// slider is focused.
final bool? slider;
/// If non-null, indicates that this subtree represents a keyboard key.
final bool? keyboardKey;
/// If non-null, indicates that this subtree is read only.
///
/// Only applicable when [textField] is true.
///
/// TalkBack/VoiceOver will treat it as non-editable text field.
final bool? readOnly;
/// If non-null, whether the node is able to hold input focus.
///
/// If [focusable] is set to false, then [focused] must not be true.
///
/// Input focus indicates that the node will receive keyboard events. It is not
/// to be confused with accessibility focus. Accessibility focus is the
/// green/black rectangular highlight that TalkBack/VoiceOver draws around the
/// element it is reading, and is separate from input focus.
final bool? focusable;
/// If non-null, whether the node currently holds input focus.
///
/// At most one node in the tree should hold input focus at any point in time,
/// and it should not be set to true if [focusable] is false.
///
/// Input focus indicates that the node will receive keyboard events. It is not
/// to be confused with accessibility focus. Accessibility focus is the
/// green/black rectangular highlight that TalkBack/VoiceOver draws around the
/// element it is reading, and is separate from input focus.
final bool? focused;
/// If non-null, whether a semantic node is in a mutually exclusive group.
///
/// For example, a radio button is in a mutually exclusive group because only
/// one radio button in that group can be marked as [checked].
final bool? inMutuallyExclusiveGroup;
/// If non-null, whether the node is considered hidden.
///
/// Hidden elements are currently not visible on screen. They may be covered
/// by other elements or positioned outside of the visible area of a viewport.
///
/// Hidden elements cannot gain accessibility focus though regular touch. The
/// only way they can be focused is by moving the focus to them via linear
/// navigation.
///
/// Platforms are free to completely ignore hidden elements and new platforms
/// are encouraged to do so.
///
/// Instead of marking an element as hidden it should usually be excluded from
/// the semantics tree altogether. Hidden elements are only included in the
/// semantics tree to work around platform limitations and they are mainly
/// used to implement accessibility scrolling on iOS.
final bool? hidden;
/// If non-null, whether [value] should be obscured.
///
/// This option is usually set in combination with [textField] to indicate
/// that the text field contains a password (or other sensitive information).
/// Doing so instructs screen readers to not read out the [value].
final bool? obscured;
/// Whether the [value] is coming from a field that supports multiline text
/// editing.
///
/// This option is only meaningful when [textField] is true to indicate
/// whether it's a single-line or multiline text field.
///
/// This option is null when [textField] is false.
final bool? multiline;
/// If non-null, whether the node corresponds to the root of a subtree for
/// which a route name should be announced.
///
/// Generally, this is set in combination with
/// [SemanticsConfiguration.explicitChildNodes], since nodes with this flag
/// are not considered focusable by Android or iOS.
///
/// See also:
///
/// * [SemanticsFlag.scopesRoute] for a description of how the announced
/// value is selected.
final bool? scopesRoute;
/// If non-null, whether the node contains the semantic label for a route.
///
/// See also:
///
/// * [SemanticsFlag.namesRoute] for a description of how the name is used.
final bool? namesRoute;
/// If non-null, whether the node represents an image.
///
/// See also:
///
/// * [SemanticsFlag.isImage], for the flag this setting controls.
final bool? image;
/// If non-null, whether the node should be considered a live region.
///
/// A live region indicates that updates to semantics node are important.
/// Platforms may use this information to make polite announcements to the
/// user to inform them of updates to this node.
///
/// An example of a live region is a [SnackBar] widget. On Android and iOS,
/// live region causes a polite announcement to be generated automatically,
/// even if the widget does not have accessibility focus. This announcement
/// may not be spoken if the OS accessibility services are already
/// announcing something else, such as reading the label of a focused widget
/// or providing a system announcement.
///
/// See also:
///
/// * [SemanticsFlag.isLiveRegion], the semantics flag this setting controls.
/// * [SemanticsConfiguration.liveRegion], for a full description of a live region.
final bool? liveRegion;
/// The maximum number of characters that can be entered into an editable
/// text field.
///
/// For the purpose of this function a character is defined as one Unicode
/// scalar value.
///
/// This should only be set when [textField] is true. Defaults to null,
/// which means no limit is imposed on the text field.
final int? maxValueLength;
/// The current number of characters that have been entered into an editable
/// text field.
///
/// For the purpose of this function a character is defined as one Unicode
/// scalar value.
///
/// This should only be set when [textField] is true. Must be set when
/// [maxValueLength] is set.
final int? currentValueLength;
/// {@template flutter.semantics.SemanticsProperties.identifier}
/// Provides an identifier for the semantics node in native accessibility hierarchy.
///
/// This value is not exposed to the users of the app.
///
/// It's usually used for UI testing with tools that work by querying the
/// native accessibility, like UIAutomator, XCUITest, or Appium.
///
/// On Android, this is used for `AccessibilityNodeInfo.setViewIdResourceName`.
/// It'll be appear in accessibility hierarchy as `resource-id`.
///
/// On iOS, this will set `UIAccessibilityElement.accessibilityIdentifier`.
/// {@endtemplate}
final String? identifier;
/// Provides a textual description of the widget.
///
/// If a label is provided, there must either by an ambient [Directionality]
/// or an explicit [textDirection] should be provided.
///
/// Callers must not provide both [label] and [attributedLabel]. One or both
/// must be null.
///
/// See also:
///
/// * [SemanticsConfiguration.label] for a description of how this is exposed
/// in TalkBack and VoiceOver.
/// * [attributedLabel] for an [AttributedString] version of this property.
final String? label;
/// Provides an [AttributedString] version of textual description of the widget.
///
/// If a [attributedLabel] is provided, there must either by an ambient
/// [Directionality] or an explicit [textDirection] should be provided.
///
/// Callers must not provide both [label] and [attributedLabel]. One or both
/// must be null.
///
/// See also:
///
/// * [SemanticsConfiguration.attributedLabel] for a description of how this
/// is exposed in TalkBack and VoiceOver.
/// * [label] for a plain string version of this property.
final AttributedString? attributedLabel;
/// Provides a textual description of the value of the widget.
///
/// If a value is provided, there must either by an ambient [Directionality]
/// or an explicit [textDirection] should be provided.
///
/// Callers must not provide both [value] and [attributedValue], One or both
/// must be null.
///
/// See also:
///
/// * [SemanticsConfiguration.value] for a description of how this is exposed
/// in TalkBack and VoiceOver.
/// * [attributedLabel] for an [AttributedString] version of this property.
final String? value;
/// Provides an [AttributedString] version of textual description of the value
/// of the widget.
///
/// If a [attributedValue] is provided, there must either by an ambient
/// [Directionality] or an explicit [textDirection] should be provided.
///
/// Callers must not provide both [value] and [attributedValue], One or both
/// must be null.
///
/// See also:
///
/// * [SemanticsConfiguration.attributedValue] for a description of how this
/// is exposed in TalkBack and VoiceOver.
/// * [value] for a plain string version of this property.
final AttributedString? attributedValue;
/// The value that [value] or [attributedValue] will become after a
/// [SemanticsAction.increase] action has been performed on this widget.
///
/// If a value is provided, [onIncrease] must also be set and there must
/// either be an ambient [Directionality] or an explicit [textDirection]
/// must be provided.
///
/// Callers must not provide both [increasedValue] and
/// [attributedIncreasedValue], One or both must be null.
///
/// See also:
///
/// * [SemanticsConfiguration.increasedValue] for a description of how this
/// is exposed in TalkBack and VoiceOver.
/// * [attributedIncreasedValue] for an [AttributedString] version of this
/// property.
final String? increasedValue;
/// The [AttributedString] that [value] or [attributedValue] will become after
/// a [SemanticsAction.increase] action has been performed on this widget.
///
/// If a [attributedIncreasedValue] is provided, [onIncrease] must also be set
/// and there must either be an ambient [Directionality] or an explicit
/// [textDirection] must be provided.
///
/// Callers must not provide both [increasedValue] and
/// [attributedIncreasedValue], One or both must be null.
///
/// See also:
///
/// * [SemanticsConfiguration.attributedIncreasedValue] for a description of
/// how this is exposed in TalkBack and VoiceOver.
/// * [increasedValue] for a plain string version of this property.
final AttributedString? attributedIncreasedValue;
/// The value that [value] or [attributedValue] will become after a
/// [SemanticsAction.decrease] action has been performed on this widget.
///
/// If a value is provided, [onDecrease] must also be set and there must
/// either be an ambient [Directionality] or an explicit [textDirection]
/// must be provided.
///
/// Callers must not provide both [decreasedValue] and
/// [attributedDecreasedValue], One or both must be null.
///
/// See also:
///
/// * [SemanticsConfiguration.decreasedValue] for a description of how this
/// is exposed in TalkBack and VoiceOver.
/// * [attributedDecreasedValue] for an [AttributedString] version of this
/// property.
final String? decreasedValue;
/// The [AttributedString] that [value] or [attributedValue] will become after
/// a [SemanticsAction.decrease] action has been performed on this widget.
///
/// If a [attributedDecreasedValue] is provided, [onDecrease] must also be set
/// and there must either be an ambient [Directionality] or an explicit
/// [textDirection] must be provided.
///
/// Callers must not provide both [decreasedValue] and
/// [attributedDecreasedValue], One or both must be null/// provided.
///
/// See also:
///
/// * [SemanticsConfiguration.attributedDecreasedValue] for a description of
/// how this is exposed in TalkBack and VoiceOver.
/// * [decreasedValue] for a plain string version of this property.
final AttributedString? attributedDecreasedValue;
/// Provides a brief textual description of the result of an action performed
/// on the widget.
///
/// If a hint is provided, there must either be an ambient [Directionality]
/// or an explicit [textDirection] should be provided.
///
/// Callers must not provide both [hint] and [attributedHint], One or both
/// must be null.
///
/// See also:
///
/// * [SemanticsConfiguration.hint] for a description of how this is exposed
/// in TalkBack and VoiceOver.
/// * [attributedHint] for an [AttributedString] version of this property.
final String? hint;
/// Provides an [AttributedString] version of brief textual description of the
/// result of an action performed on the widget.
///
/// If a [attributedHint] is provided, there must either by an ambient
/// [Directionality] or an explicit [textDirection] should be provided.
///
/// Callers must not provide both [hint] and [attributedHint], One or both
/// must be null.
///
/// See also:
///
/// * [SemanticsConfiguration.attributedHint] for a description of how this
/// is exposed in TalkBack and VoiceOver.
/// * [hint] for a plain string version of this property.
final AttributedString? attributedHint;
/// Provides a textual description of the widget's tooltip.
///
/// In Android, this property sets the `AccessibilityNodeInfo.setTooltipText`.
/// In iOS, this property is appended to the end of the
/// `UIAccessibilityElement.accessibilityLabel`.
///
/// If a [tooltip] is provided, there must either by an ambient
/// [Directionality] or an explicit [textDirection] should be provided.
final String? tooltip;
/// Provides hint values which override the default hints on supported
/// platforms.
///
/// On Android, If no hint overrides are used then default [hint] will be
/// combined with the [label]. Otherwise, the [hint] will be ignored as long
/// as there as at least one non-null hint override.
///
/// On iOS, these are always ignored and the default [hint] is used instead.
final SemanticsHintOverrides? hintOverrides;
/// The reading direction of the [label], [value], [increasedValue],
/// [decreasedValue], and [hint].
///
/// Defaults to the ambient [Directionality].
final TextDirection? textDirection;
/// Determines the position of this node among its siblings in the traversal
/// sort order.
///
/// This is used to describe the order in which the semantic node should be
/// traversed by the accessibility services on the platform (e.g. VoiceOver
/// on iOS and TalkBack on Android).
final SemanticsSortKey? sortKey;
/// A tag to be applied to the child [SemanticsNode]s of this widget.
///
/// The tag is added to all child [SemanticsNode]s that pass through the
/// [RenderObject] corresponding to this widget while looking to be attached
/// to a parent SemanticsNode.
///
/// Tags are used to communicate to a parent SemanticsNode that a child
/// SemanticsNode was passed through a particular RenderObject. The parent can
/// use this information to determine the shape of the semantics tree.
///
/// See also:
///
/// * [SemanticsConfiguration.addTagForChildren], to which the tags provided
/// here will be passed.
final SemanticsTag? tagForChildren;
/// The handler for [SemanticsAction.tap].
///
/// This is the semantic equivalent of a user briefly tapping the screen with
/// the finger without moving it. For example, a button should implement this
/// action.
///
/// VoiceOver users on iOS and TalkBack users on Android *may* trigger this
/// action by double-tapping the screen while an element is focused.
///
/// Note: different OSes or assistive technologies may decide to interpret
/// user inputs differently. Some may simulate real screen taps, while others
/// may call semantics tap. One way to handle taps properly is to provide the
/// same handler to both gesture tap and semantics tap.
final VoidCallback? onTap;
/// The handler for [SemanticsAction.longPress].
///
/// This is the semantic equivalent of a user pressing and holding the screen
/// with the finger for a few seconds without moving it.
///
/// VoiceOver users on iOS and TalkBack users on Android *may* trigger this
/// action by double-tapping the screen without lifting the finger after the
/// second tap.
///
/// Note: different OSes or assistive technologies may decide to interpret
/// user inputs differently. Some may simulate real long presses, while others
/// may call semantics long press. One way to handle long press properly is to
/// provide the same handler to both gesture long press and semantics long
/// press.
final VoidCallback? onLongPress;
/// The handler for [SemanticsAction.scrollLeft].
///
/// This is the semantic equivalent of a user moving their finger across the
/// screen from right to left. It should be recognized by controls that are
/// horizontally scrollable.
///
/// VoiceOver users on iOS can trigger this action by swiping left with three
/// fingers. TalkBack users on Android can trigger this action by swiping
/// right and then left in one motion path. On Android, [onScrollUp] and
/// [onScrollLeft] share the same gesture. Therefore, only on of them should
/// be provided.
final VoidCallback? onScrollLeft;
/// The handler for [SemanticsAction.scrollRight].
///
/// This is the semantic equivalent of a user moving their finger across the
/// screen from left to right. It should be recognized by controls that are
/// horizontally scrollable.
///
/// VoiceOver users on iOS can trigger this action by swiping right with three
/// fingers. TalkBack users on Android can trigger this action by swiping
/// left and then right in one motion path. On Android, [onScrollDown] and
/// [onScrollRight] share the same gesture. Therefore, only on of them should
/// be provided.
final VoidCallback? onScrollRight;
/// The handler for [SemanticsAction.scrollUp].
///
/// This is the semantic equivalent of a user moving their finger across the
/// screen from bottom to top. It should be recognized by controls that are
/// vertically scrollable.
///
/// VoiceOver users on iOS can trigger this action by swiping up with three
/// fingers. TalkBack users on Android can trigger this action by swiping
/// right and then left in one motion path. On Android, [onScrollUp] and
/// [onScrollLeft] share the same gesture. Therefore, only on of them should
/// be provided.
final VoidCallback? onScrollUp;
/// The handler for [SemanticsAction.scrollDown].
///
/// This is the semantic equivalent of a user moving their finger across the
/// screen from top to bottom. It should be recognized by controls that are
/// vertically scrollable.
///
/// VoiceOver users on iOS can trigger this action by swiping down with three
/// fingers. TalkBack users on Android can trigger this action by swiping
/// left and then right in one motion path. On Android, [onScrollDown] and
/// [onScrollRight] share the same gesture. Therefore, only on of them should
/// be provided.
final VoidCallback? onScrollDown;
/// The handler for [SemanticsAction.increase].
///
/// This is a request to increase the value represented by the widget. For
/// example, this action might be recognized by a slider control.
///
/// If a [value] is set, [increasedValue] must also be provided and
/// [onIncrease] must ensure that [value] will be set to [increasedValue].
///
/// VoiceOver users on iOS can trigger this action by swiping up with one
/// finger. TalkBack users on Android can trigger this action by pressing the
/// volume up button.
final VoidCallback? onIncrease;
/// The handler for [SemanticsAction.decrease].
///
/// This is a request to decrease the value represented by the widget. For
/// example, this action might be recognized by a slider control.
///
/// If a [value] is set, [decreasedValue] must also be provided and
/// [onDecrease] must ensure that [value] will be set to [decreasedValue].
///
/// VoiceOver users on iOS can trigger this action by swiping down with one
/// finger. TalkBack users on Android can trigger this action by pressing the
/// volume down button.
final VoidCallback? onDecrease;
/// The handler for [SemanticsAction.copy].
///
/// This is a request to copy the current selection to the clipboard.
///
/// TalkBack users on Android can trigger this action from the local context
/// menu of a text field, for example.
final VoidCallback? onCopy;
/// The handler for [SemanticsAction.cut].
///
/// This is a request to cut the current selection and place it in the
/// clipboard.
///
/// TalkBack users on Android can trigger this action from the local context
/// menu of a text field, for example.
final VoidCallback? onCut;
/// The handler for [SemanticsAction.paste].
///
/// This is a request to paste the current content of the clipboard.
///
/// TalkBack users on Android can trigger this action from the local context
/// menu of a text field, for example.
final VoidCallback? onPaste;
/// The handler for [SemanticsAction.moveCursorForwardByCharacter].
///
/// This handler is invoked when the user wants to move the cursor in a
/// text field forward by one character.
///
/// TalkBack users can trigger this by pressing the volume up key while the
/// input focus is in a text field.
final MoveCursorHandler? onMoveCursorForwardByCharacter;
/// The handler for [SemanticsAction.moveCursorBackwardByCharacter].
///
/// This handler is invoked when the user wants to move the cursor in a
/// text field backward by one character.
///
/// TalkBack users can trigger this by pressing the volume down key while the
/// input focus is in a text field.
final MoveCursorHandler? onMoveCursorBackwardByCharacter;
/// The handler for [SemanticsAction.moveCursorForwardByWord].
///
/// This handler is invoked when the user wants to move the cursor in a
/// text field backward by one word.
///
/// TalkBack users can trigger this by pressing the volume down key while the
/// input focus is in a text field.
final MoveCursorHandler? onMoveCursorForwardByWord;
/// The handler for [SemanticsAction.moveCursorBackwardByWord].
///
/// This handler is invoked when the user wants to move the cursor in a
/// text field backward by one word.
///
/// TalkBack users can trigger this by pressing the volume down key while the
/// input focus is in a text field.
final MoveCursorHandler? onMoveCursorBackwardByWord;
/// The handler for [SemanticsAction.setSelection].
///
/// This handler is invoked when the user either wants to change the currently
/// selected text in a text field or change the position of the cursor.
///
/// TalkBack users can trigger this handler by selecting "Move cursor to
/// beginning/end" or "Select all" from the local context menu.
final SetSelectionHandler? onSetSelection;
/// The handler for [SemanticsAction.setText].
///
/// This handler is invoked when the user wants to replace the current text in
/// the text field with a new text.
///
/// Voice access users can trigger this handler by speaking "type <text>" to
/// their Android devices.
final SetTextHandler? onSetText;
/// The handler for [SemanticsAction.didGainAccessibilityFocus].
///
/// This handler is invoked when the node annotated with this handler gains
/// the accessibility focus. The accessibility focus is the
/// green (on Android with TalkBack) or black (on iOS with VoiceOver)
/// rectangle shown on screen to indicate what element an accessibility
/// user is currently interacting with.
///
/// The accessibility focus is different from the input focus. The input focus
/// is usually held by the element that currently responds to keyboard inputs.
/// Accessibility focus and input focus can be held by two different nodes!
///
/// See also:
///
/// * [onDidLoseAccessibilityFocus], which is invoked when the accessibility
/// focus is removed from the node.
/// * [FocusNode], [FocusScope], [FocusManager], which manage the input focus.
final VoidCallback? onDidGainAccessibilityFocus;
/// The handler for [SemanticsAction.didLoseAccessibilityFocus].
///
/// This handler is invoked when the node annotated with this handler
/// loses the accessibility focus. The accessibility focus is
/// the green (on Android with TalkBack) or black (on iOS with VoiceOver)
/// rectangle shown on screen to indicate what element an accessibility
/// user is currently interacting with.
///
/// The accessibility focus is different from the input focus. The input focus
/// is usually held by the element that currently responds to keyboard inputs.
/// Accessibility focus and input focus can be held by two different nodes!
///
/// See also:
///
/// * [onDidGainAccessibilityFocus], which is invoked when the node gains
/// accessibility focus.
/// * [FocusNode], [FocusScope], [FocusManager], which manage the input focus.
final VoidCallback? onDidLoseAccessibilityFocus;
/// The handler for [SemanticsAction.dismiss].
///
/// This is a request to dismiss the currently focused node.
///
/// TalkBack users on Android can trigger this action in the local context
/// menu, and VoiceOver users on iOS can trigger this action with a standard
/// gesture or menu option.
final VoidCallback? onDismiss;
/// A map from each supported [CustomSemanticsAction] to a provided handler.
///
/// The handler associated with each custom action is called whenever a
/// semantics action of type [SemanticsAction.customAction] is received. The
/// provided argument will be an identifier used to retrieve an instance of
/// a custom action which can then retrieve the correct handler from this map.
///
/// See also:
///
/// * [CustomSemanticsAction], for an explanation of custom actions.
final Map<CustomSemanticsAction, VoidCallback>? customSemanticsActions;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<bool>('checked', checked, defaultValue: null));
properties.add(DiagnosticsProperty<bool>('mixed', mixed, defaultValue: null));
properties.add(DiagnosticsProperty<bool>('expanded', expanded, defaultValue: null));
properties.add(DiagnosticsProperty<bool>('selected', selected, defaultValue: null));
properties.add(StringProperty('identifier', identifier, defaultValue: null));
properties.add(StringProperty('label', label, defaultValue: null));
properties.add(AttributedStringProperty('attributedLabel', attributedLabel, defaultValue: null));
properties.add(StringProperty('value', value, defaultValue: null));
properties.add(AttributedStringProperty('attributedValue', attributedValue, defaultValue: null));
properties.add(StringProperty('increasedValue', value, defaultValue: null));
properties.add(AttributedStringProperty('attributedIncreasedValue', attributedIncreasedValue, defaultValue: null));
properties.add(StringProperty('decreasedValue', value, defaultValue: null));
properties.add(AttributedStringProperty('attributedDecreasedValue', attributedDecreasedValue, defaultValue: null));
properties.add(StringProperty('hint', hint, defaultValue: null));
properties.add(AttributedStringProperty('attributedHint', attributedHint, defaultValue: null));
properties.add(StringProperty('tooltip', tooltip, defaultValue: null));
properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
properties.add(DiagnosticsProperty<SemanticsSortKey>('sortKey', sortKey, defaultValue: null));
properties.add(DiagnosticsProperty<SemanticsHintOverrides>('hintOverrides', hintOverrides, defaultValue: null));
}
@override
String toStringShort() => objectRuntimeType(this, 'SemanticsProperties'); // the hashCode isn't important since we're immutable
}
/// In tests use this function to reset the counter used to generate
/// [SemanticsNode.id].
void debugResetSemanticsIdCounter() {
SemanticsNode._lastIdentifier = 0;
}
/// A node that represents some semantic data.
///
/// The semantics tree is maintained during the semantics phase of the pipeline
/// (i.e., during [PipelineOwner.flushSemantics]), which happens after
/// compositing. The semantics tree is then uploaded into the engine for use
/// by assistive technology.
class SemanticsNode with DiagnosticableTreeMixin {
/// Creates a semantic node.
///
/// Each semantic node has a unique identifier that is assigned when the node
/// is created.
SemanticsNode({
this.key,
VoidCallback? showOnScreen,
}) : _id = _generateNewId(),
_showOnScreen = showOnScreen;
/// Creates a semantic node to represent the root of the semantics tree.
///
/// The root node is assigned an identifier of zero.
SemanticsNode.root({
this.key,
VoidCallback? showOnScreen,
required SemanticsOwner owner,
}) : _id = 0,
_showOnScreen = showOnScreen {
attach(owner);
}
// The maximal semantic node identifier generated by the framework.
//
// The identifier range for semantic node IDs is split into 2, the least significant 16 bits are
// reserved for framework generated IDs(generated with _generateNewId), and most significant 32
// bits are reserved for engine generated IDs.
static const int _maxFrameworkAccessibilityIdentifier = (1<<16) - 1;
static int _lastIdentifier = 0;
static int _generateNewId() {
_lastIdentifier = (_lastIdentifier + 1) % _maxFrameworkAccessibilityIdentifier;
return _lastIdentifier;
}
/// Uniquely identifies this node in the list of sibling nodes.
///
/// Keys are used during the construction of the semantics tree. They are not
/// transferred to the engine.
final Key? key;
/// The unique identifier for this node.
///
/// The root node has an id of zero. Other nodes are given a unique id
/// when they are attached to a [SemanticsOwner]. If they are detached, their
/// ids are invalid and should not be used.
///
/// In rare circumstances, id may change if this node is detached and
/// re-attached to the [SemanticsOwner]. This should only happen when the
/// application has generated too many semantics nodes.
int get id => _id;
int _id;
final VoidCallback? _showOnScreen;
// GEOMETRY
/// The transform from this node's coordinate system to its parent's coordinate system.
///
/// By default, the transform is null, which represents the identity
/// transformation (i.e., that this node has the same coordinate system as its
/// parent).
Matrix4? get transform => _transform;
Matrix4? _transform;
set transform(Matrix4? value) {
if (!MatrixUtils.matrixEquals(_transform, value)) {
_transform = value == null || MatrixUtils.isIdentity(value) ? null : value;
_markDirty();
}
}
/// The bounding box for this node in its coordinate system.
Rect get rect => _rect;
Rect _rect = Rect.zero;
set rect(Rect value) {
assert(value.isFinite, '$this (with $owner) tried to set a non-finite rect.');
if (_rect != value) {
_rect = value;
_markDirty();
}
}
/// The semantic clip from an ancestor that was applied to this node.
///
/// Expressed in the coordinate system of the node. May be null if no clip has
/// been applied.
///
/// Descendant [SemanticsNode]s that are positioned outside of this rect will
/// be excluded from the semantics tree. Descendant [SemanticsNode]s that are
/// overlapping with this rect, but are outside of [parentPaintClipRect] will
/// be included in the tree, but they will be marked as hidden because they
/// are assumed to be not visible on screen.
///
/// If this rect is null, all descendant [SemanticsNode]s outside of
/// [parentPaintClipRect] will be excluded from the tree.
///
/// If this rect is non-null it has to completely enclose
/// [parentPaintClipRect]. If [parentPaintClipRect] is null this property is
/// also null.
Rect? parentSemanticsClipRect;
/// The paint clip from an ancestor that was applied to this node.
///
/// Expressed in the coordinate system of the node. May be null if no clip has
/// been applied.
///
/// Descendant [SemanticsNode]s that are positioned outside of this rect will
/// either be excluded from the semantics tree (if they have no overlap with
/// [parentSemanticsClipRect]) or they will be included and marked as hidden
/// (if they are overlapping with [parentSemanticsClipRect]).
///
/// This rect is completely enclosed by [parentSemanticsClipRect].
///
/// If this rect is null [parentSemanticsClipRect] also has to be null.
Rect? parentPaintClipRect;
/// The elevation adjustment that the parent imposes on this node.
///
/// The [elevation] property is relative to the elevation of the parent
/// [SemanticsNode]. However, as [SemanticsConfiguration]s from various
/// ascending [RenderObject]s are merged into each other to form that
/// [SemanticsNode] the parent’s elevation may change. This requires an
/// adjustment of the child’s relative elevation which is represented by this
/// value.
///
/// The value is rarely accessed directly. Instead, for most use cases the
/// [elevation] value should be used, which includes this adjustment.
///
/// See also:
///
/// * [elevation], the actual elevation of this [SemanticsNode].
double? elevationAdjustment;
/// The index of this node within the parent's list of semantic children.
///
/// This includes all semantic nodes, not just those currently in the
/// child list. For example, if a scrollable has five children but the first
/// two are not visible (and thus not included in the list of children), then
/// the index of the last node will still be 4.
int? indexInParent;
/// Whether the node is invisible.
///
/// A node whose [rect] is outside of the bounds of the screen and hence not
/// reachable for users is considered invisible if its semantic information
/// is not merged into a (partially) visible parent as indicated by
/// [isMergedIntoParent].
///
/// An invisible node can be safely dropped from the semantic tree without
/// loosing semantic information that is relevant for describing the content
/// currently shown on screen.
bool get isInvisible => !isMergedIntoParent && rect.isEmpty;
// MERGING
/// Whether this node merges its semantic information into an ancestor node.
///
/// This value indicates whether this node has any ancestors with
/// [mergeAllDescendantsIntoThisNode] set to true.
bool get isMergedIntoParent => parent != null && _isMergedIntoParent;
bool _isMergedIntoParent = false;
/// Whether the user can interact with this node in assistive technologies.
///
/// This node can still receive accessibility focus even if this is true.
/// Setting this to true prevents the user from activating pointer related
/// [SemanticsAction]s, such as [SemanticsAction.tap] or
/// [SemanticsAction.longPress].
bool get areUserActionsBlocked => _areUserActionsBlocked;
bool _areUserActionsBlocked = false;
set areUserActionsBlocked(bool value) {
if (_areUserActionsBlocked == value) {
return;
}
_areUserActionsBlocked = value;
_markDirty();
}
/// Whether this node is taking part in a merge of semantic information.
///
/// This returns true if the node is either merged into an ancestor node or if
/// decedent nodes are merged into this node.
///
/// See also:
///
/// * [isMergedIntoParent]
/// * [mergeAllDescendantsIntoThisNode]
bool get isPartOfNodeMerging => mergeAllDescendantsIntoThisNode || isMergedIntoParent;
/// Whether this node and all of its descendants should be treated as one logical entity.
bool get mergeAllDescendantsIntoThisNode => _mergeAllDescendantsIntoThisNode;
bool _mergeAllDescendantsIntoThisNode = _kEmptyConfig.isMergingSemanticsOfDescendants;
// CHILDREN
/// Contains the children in inverse hit test order (i.e. paint order).
List<SemanticsNode>? _children;
/// A snapshot of `newChildren` passed to [_replaceChildren] that we keep in
/// debug mode. It supports the assertion that user does not mutate the list
/// of children.
late List<SemanticsNode> _debugPreviousSnapshot;
void _replaceChildren(List<SemanticsNode> newChildren) {
assert(!newChildren.any((SemanticsNode child) => child == this));
assert(() {
final Set<SemanticsNode> seenChildren = <SemanticsNode>{};
for (final SemanticsNode child in newChildren) {
assert(seenChildren.add(child));
} // check for duplicate adds
return true;
}());
// The goal of this function is updating sawChange.
if (_children != null) {
for (final SemanticsNode child in _children!) {
child._dead = true;
}
}
for (final SemanticsNode child in newChildren) {
child._dead = false;
}
bool sawChange = false;
if (_children != null) {
for (final SemanticsNode child in _children!) {
if (child._dead) {
if (child.parent == this) {
// we might have already had our child stolen from us by
// another node that is deeper in the tree.
_dropChild(child);
}
sawChange = true;
}
}
}
for (final SemanticsNode child in newChildren) {
if (child.parent != this) {
if (child.parent != null) {
// we're rebuilding the tree from the bottom up, so it's possible
// that our child was, in the last pass, a child of one of our
// ancestors. In that case, we drop the child eagerly here.
// TODO(ianh): Find a way to assert that the same node didn't
// actually appear in the tree in two places.
child.parent?._dropChild(child);
}
assert(!child.attached);
_adoptChild(child);
sawChange = true;
}
}
// Wait until the new children are adopted so isMergedIntoParent becomes
// up-to-date.
assert(() {
if (identical(newChildren, _children)) {
final List<DiagnosticsNode> mutationErrors = <DiagnosticsNode>[];
if (newChildren.length != _debugPreviousSnapshot.length) {
mutationErrors.add(ErrorDescription(
"The list's length has changed from ${_debugPreviousSnapshot.length} "
'to ${newChildren.length}.',
));
} else {
for (int i = 0; i < newChildren.length; i++) {
if (!identical(newChildren[i], _debugPreviousSnapshot[i])) {
if (mutationErrors.isNotEmpty) {
mutationErrors.add(ErrorSpacer());
}
mutationErrors.add(ErrorDescription('Child node at position $i was replaced:'));
mutationErrors.add(_debugPreviousSnapshot[i].toDiagnosticsNode(name: 'Previous child', style: DiagnosticsTreeStyle.singleLine));
mutationErrors.add(newChildren[i].toDiagnosticsNode(name: 'New child', style: DiagnosticsTreeStyle.singleLine));
}
}
}
if (mutationErrors.isNotEmpty) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Failed to replace child semantics nodes because the list of `SemanticsNode`s was mutated.'),
ErrorHint('Instead of mutating the existing list, create a new list containing the desired `SemanticsNode`s.'),
ErrorDescription('Error details:'),
...mutationErrors,
]);
}
}
_debugPreviousSnapshot = List<SemanticsNode>.of(newChildren);
SemanticsNode ancestor = this;
while (ancestor.parent is SemanticsNode) {
ancestor = ancestor.parent!;
}
assert(!newChildren.any((SemanticsNode child) => child == ancestor));
return true;
}());
if (!sawChange && _children != null) {
assert(newChildren.length == _children!.length);
// Did the order change?
for (int i = 0; i < _children!.length; i++) {
if (_children![i].id != newChildren[i].id) {
sawChange = true;
break;
}
}
}
_children = newChildren;
if (sawChange) {
_markDirty();
}
}
/// Whether this node has a non-zero number of children.
bool get hasChildren => _children?.isNotEmpty ?? false;
bool _dead = false;
/// The number of children this node has.
int get childrenCount => hasChildren ? _children!.length : 0;
/// Visits the immediate children of this node.
///
/// This function calls visitor for each immediate child until visitor returns
/// false. Returns true if all the visitor calls returned true, otherwise
/// returns false.
void visitChildren(SemanticsNodeVisitor visitor) {
if (_children != null) {
for (final SemanticsNode child in _children!) {
if (!visitor(child)) {
return;
}
}
}
}
/// Visit all the descendants of this node.
///
/// This function calls visitor for each descendant in a pre-order traversal
/// until visitor returns false. Returns true if all the visitor calls
/// returned true, otherwise returns false.
bool _visitDescendants(SemanticsNodeVisitor visitor) {
if (_children != null) {
for (final SemanticsNode child in _children!) {
if (!visitor(child) || !child._visitDescendants(visitor)) {
return false;
}
}
}
return true;
}
/// The owner for this node (null if unattached).
///
/// The entire semantics tree that this node belongs to will have the same owner.
SemanticsOwner? get owner => _owner;
SemanticsOwner? _owner;
/// Whether the semantics tree this node belongs to is attached to a [SemanticsOwner].
///
/// This becomes true during the call to [attach].
///
/// This becomes false during the call to [detach].
bool get attached => _owner != null;
/// The parent of this node in the semantics tree.
///
/// The [parent] of the root node in the semantics tree is null.
SemanticsNode? get parent => _parent;
SemanticsNode? _parent;
/// The depth of this node in the semantics tree.
///
/// The depth of nodes in a tree monotonically increases as you traverse down
/// the tree. There's no guarantee regarding depth between siblings.
///
/// The depth is used to ensure that nodes are processed in depth order.
int get depth => _depth;
int _depth = 0;
void _redepthChild(SemanticsNode child) {
assert(child.owner == owner);
if (child._depth <= _depth) {
child._depth = _depth + 1;
child._redepthChildren();
}
}
void _redepthChildren() {
_children?.forEach(_redepthChild);
}
void _updateChildMergeFlagRecursively(SemanticsNode child) {
assert(child.owner == owner);
final bool childShouldMergeToParent = isPartOfNodeMerging;
if (childShouldMergeToParent == child._isMergedIntoParent) {
return;
}
child._isMergedIntoParent = childShouldMergeToParent;
_markDirty();
if (child.mergeAllDescendantsIntoThisNode) {
// No need to update the descendants since `child` has the merge flag set.
} else {
child._updateChildrenMergeFlags();
}
}
void _updateChildrenMergeFlags() {
_children?.forEach(_updateChildMergeFlagRecursively);
}
void _adoptChild(SemanticsNode child) {
assert(child._parent == null);
assert(() {
SemanticsNode node = this;
while (node.parent != null) {
node = node.parent!;
}
assert(node != child); // indicates we are about to create a cycle
return true;
}());
child._parent = this;
if (attached) {
child.attach(_owner!);
}
_redepthChild(child);
_updateChildMergeFlagRecursively(child);
}
void _dropChild(SemanticsNode child) {
assert(child._parent == this);
assert(child.attached == attached);
child._parent = null;
if (attached) {
child.detach();
}
}
/// Mark this node as attached to the given owner.
@visibleForTesting
void attach(SemanticsOwner owner) {
assert(_owner == null);
_owner = owner;
while (owner._nodes.containsKey(id)) {
// Ids may repeat if the Flutter has generated > 2^16 ids. We need to keep
// regenerating the id until we found an id that is not used.
_id = _generateNewId();
}
owner._nodes[id] = this;
owner._detachedNodes.remove(this);
if (_dirty) {
_dirty = false;
_markDirty();
}
if (_children != null) {
for (final SemanticsNode child in _children!) {
child.attach(owner);
}
}
}
/// Mark this node as detached from its owner.
@visibleForTesting
void detach() {
assert(_owner != null);
assert(owner!._nodes.containsKey(id));
assert(!owner!._detachedNodes.contains(this));
owner!._nodes.remove(id);
owner!._detachedNodes.add(this);
_owner = null;
assert(parent == null || attached == parent!.attached);
if (_children != null) {
for (final SemanticsNode child in _children!) {
// The list of children may be stale and may contain nodes that have
// been assigned to a different parent.
if (child.parent == this) {
child.detach();
}
}
}
// The other side will have forgotten this node if we ever send
// it again, so make sure to mark it dirty so that it'll get
// sent if it is resurrected.
_markDirty();
}
// DIRTY MANAGEMENT
bool _dirty = false;
void _markDirty() {
if (_dirty) {
return;
}
_dirty = true;
if (attached) {
assert(!owner!._detachedNodes.contains(this));
owner!._dirtyNodes.add(this);
}
}
bool _isDifferentFromCurrentSemanticAnnotation(SemanticsConfiguration config) {
return _attributedLabel != config.attributedLabel
|| _attributedHint != config.attributedHint
|| _elevation != config.elevation
|| _thickness != config.thickness
|| _attributedValue != config.attributedValue
|| _attributedIncreasedValue != config.attributedIncreasedValue
|| _attributedDecreasedValue != config.attributedDecreasedValue
|| _tooltip != config.tooltip
|| _flags != config._flags
|| _textDirection != config.textDirection
|| _sortKey != config._sortKey
|| _textSelection != config._textSelection
|| _scrollPosition != config._scrollPosition
|| _scrollExtentMax != config._scrollExtentMax
|| _scrollExtentMin != config._scrollExtentMin
|| _actionsAsBits != config._actionsAsBits
|| indexInParent != config.indexInParent
|| platformViewId != config.platformViewId
|| _maxValueLength != config._maxValueLength
|| _currentValueLength != config._currentValueLength
|| _mergeAllDescendantsIntoThisNode != config.isMergingSemanticsOfDescendants
|| _areUserActionsBlocked != config.isBlockingUserActions;
}
// TAGS, LABELS, ACTIONS
Map<SemanticsAction, SemanticsActionHandler> _actions = _kEmptyConfig._actions;
Map<CustomSemanticsAction, VoidCallback> _customSemanticsActions = _kEmptyConfig._customSemanticsActions;
int get _effectiveActionsAsBits => _areUserActionsBlocked ? _actionsAsBits & _kUnblockedUserActions : _actionsAsBits;
int _actionsAsBits = _kEmptyConfig._actionsAsBits;
/// The [SemanticsTag]s this node is tagged with.
///
/// Tags are used during the construction of the semantics tree. They are not
/// transferred to the engine.
Set<SemanticsTag>? tags;
/// Whether this node is tagged with `tag`.
bool isTagged(SemanticsTag tag) => tags != null && tags!.contains(tag);
int _flags = _kEmptyConfig._flags;
/// Whether this node currently has a given [SemanticsFlag].
bool hasFlag(SemanticsFlag flag) => _flags & flag.index != 0;
/// {@macro flutter.semantics.SemanticsProperties.identifier}
String get identifier => _identifier;
String _identifier = _kEmptyConfig.identifier;
/// A textual description of this node.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedLabel].
String get label => _attributedLabel.string;
/// A textual description of this node in [AttributedString] format.
///
/// The reading direction is given by [textDirection].
///
/// See also [label], which exposes just the raw text.
AttributedString get attributedLabel => _attributedLabel;
AttributedString _attributedLabel = _kEmptyConfig.attributedLabel;
/// A textual description for the current value of the node.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedValue].
String get value => _attributedValue.string;
/// A textual description for the current value of the node in
/// [AttributedString] format.
///
/// The reading direction is given by [textDirection].
///
/// See also [value], which exposes just the raw text.
AttributedString get attributedValue => _attributedValue;
AttributedString _attributedValue = _kEmptyConfig.attributedValue;
/// The value that [value] will have after a [SemanticsAction.increase] action
/// has been performed.
///
/// This property is only valid if the [SemanticsAction.increase] action is
/// available on this node.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedIncreasedValue].
String get increasedValue => _attributedIncreasedValue.string;
/// The value in [AttributedString] format that [value] or [attributedValue]
/// will have after a [SemanticsAction.increase] action has been performed.
///
/// This property is only valid if the [SemanticsAction.increase] action is
/// available on this node.
///
/// The reading direction is given by [textDirection].
///
/// See also [increasedValue], which exposes just the raw text.
AttributedString get attributedIncreasedValue => _attributedIncreasedValue;
AttributedString _attributedIncreasedValue = _kEmptyConfig.attributedIncreasedValue;
/// The value that [value] will have after a [SemanticsAction.decrease] action
/// has been performed.
///
/// This property is only valid if the [SemanticsAction.decrease] action is
/// available on this node.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedDecreasedValue].
String get decreasedValue => _attributedDecreasedValue.string;
/// The value in [AttributedString] format that [value] or [attributedValue]
/// will have after a [SemanticsAction.decrease] action has been performed.
///
/// This property is only valid if the [SemanticsAction.decrease] action is
/// available on this node.
///
/// The reading direction is given by [textDirection].
///
/// See also [decreasedValue], which exposes just the raw text.
AttributedString get attributedDecreasedValue => _attributedDecreasedValue;
AttributedString _attributedDecreasedValue = _kEmptyConfig.attributedDecreasedValue;
/// A brief description of the result of performing an action on this node.
///
/// The reading direction is given by [textDirection].
///
/// This exposes the raw text of the [attributedHint].
String get hint => _attributedHint.string;
/// A brief description of the result of performing an action on this node
/// in [AttributedString] format.
///
/// The reading direction is given by [textDirection].
///
/// See also [hint], which exposes just the raw text.
AttributedString get attributedHint => _attributedHint;
AttributedString _attributedHint = _kEmptyConfig.attributedHint;
/// A textual description of the widget's tooltip.
///
/// The reading direction is given by [textDirection].
String get tooltip => _tooltip;
String _tooltip = _kEmptyConfig.tooltip;
/// The elevation along the z-axis at which the [rect] of this [SemanticsNode]
/// is located above its parent.
///
/// The value is relative to the parent's [elevation]. The sum of the
/// [elevation]s of all ancestor node plus this value determines the absolute
/// elevation of this [SemanticsNode].
///
/// See also:
///
/// * [thickness], which describes how much space in z-direction this
/// [SemanticsNode] occupies starting at this [elevation].
/// * [elevationAdjustment], which has been used to calculate this value.
double get elevation => _elevation;
double _elevation = _kEmptyConfig.elevation;
/// Describes how much space the [SemanticsNode] takes up along the z-axis.
///
/// A [SemanticsNode] represents multiple [RenderObject]s, which can be
/// located at various elevations in 3D. The [thickness] is the difference
/// between the absolute elevations of the lowest and highest [RenderObject]
/// represented by this [SemanticsNode]. In other words, the thickness
/// describes how high the box is that this [SemanticsNode] occupies in three
/// dimensional space. The two other dimensions are defined by [rect].
///
/// {@tool snippet}
/// The following code stacks three [PhysicalModel]s on top of each other
/// separated by non-zero elevations.
///
/// [PhysicalModel] C is elevated 10.0 above [PhysicalModel] B, which in turn
/// is elevated 5.0 above [PhysicalModel] A. The side view of this
/// constellation looks as follows:
///
/// 
///
/// In this example the [RenderObject]s for [PhysicalModel] C and B share one
/// [SemanticsNode] Y. Given the elevations of those [RenderObject]s, this
/// [SemanticsNode] has a [thickness] of 10.0 and an elevation of 5.0 over
/// its parent [SemanticsNode] X.
/// ```dart
/// PhysicalModel( // A
/// color: Colors.amber,
/// child: Semantics(
/// explicitChildNodes: true,
/// child: const PhysicalModel( // B
/// color: Colors.brown,
/// elevation: 5.0,
/// child: PhysicalModel( // C
/// color: Colors.cyan,
/// elevation: 10.0,
/// child: Placeholder(),
/// ),
/// ),
/// ),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [elevation], which describes the elevation of the box defined by
/// [thickness] and [rect] relative to the parent of this [SemanticsNode].
double get thickness => _thickness;
double _thickness = _kEmptyConfig.thickness;
/// Provides hint values which override the default hints on supported
/// platforms.
SemanticsHintOverrides? get hintOverrides => _hintOverrides;
SemanticsHintOverrides? _hintOverrides;
/// The reading direction for [label], [value], [hint], [increasedValue], and
/// [decreasedValue].
TextDirection? get textDirection => _textDirection;
TextDirection? _textDirection = _kEmptyConfig.textDirection;
/// Determines the position of this node among its siblings in the traversal
/// sort order.
///
/// This is used to describe the order in which the semantic node should be
/// traversed by the accessibility services on the platform (e.g. VoiceOver
/// on iOS and TalkBack on Android).
SemanticsSortKey? get sortKey => _sortKey;
SemanticsSortKey? _sortKey;
/// The currently selected text (or the position of the cursor) within [value]
/// if this node represents a text field.
TextSelection? get textSelection => _textSelection;
TextSelection? _textSelection;
/// If this node represents a text field, this indicates whether or not it's
/// a multiline text field.
bool? get isMultiline => _isMultiline;
bool? _isMultiline;
/// The total number of scrollable children that contribute to semantics.
///
/// If the number of children are unknown or unbounded, this value will be
/// null.
int? get scrollChildCount => _scrollChildCount;
int? _scrollChildCount;
/// The index of the first visible semantic child of a scroll node.
int? get scrollIndex => _scrollIndex;
int? _scrollIndex;
/// Indicates the current scrolling position in logical pixels if the node is
/// scrollable.
///
/// The properties [scrollExtentMin] and [scrollExtentMax] indicate the valid
/// in-range values for this property. The value for [scrollPosition] may
/// (temporarily) be outside that range, e.g. during an overscroll.
///
/// See also:
///
/// * [ScrollPosition.pixels], from where this value is usually taken.
double? get scrollPosition => _scrollPosition;
double? _scrollPosition;
/// Indicates the maximum in-range value for [scrollPosition] if the node is
/// scrollable.
///
/// This value may be infinity if the scroll is unbound.
///
/// See also:
///
/// * [ScrollPosition.maxScrollExtent], from where this value is usually taken.
double? get scrollExtentMax => _scrollExtentMax;
double? _scrollExtentMax;
/// Indicates the minimum in-range value for [scrollPosition] if the node is
/// scrollable.
///
/// This value may be infinity if the scroll is unbound.
///
/// See also:
///
/// * [ScrollPosition.minScrollExtent] from where this value is usually taken.
double? get scrollExtentMin => _scrollExtentMin;
double? _scrollExtentMin;
/// The id of the platform view, whose semantics nodes will be added as
/// children to this node.
///
/// If this value is non-null, the SemanticsNode must not have any children
/// as those would be replaced by the semantics nodes of the referenced
/// platform view.
///
/// See also:
///
/// * [AndroidView], which is the platform view for Android.
/// * [UiKitView], which is the platform view for iOS.
int? get platformViewId => _platformViewId;
int? _platformViewId;
/// The maximum number of characters that can be entered into an editable
/// text field.
///
/// For the purpose of this function a character is defined as one Unicode
/// scalar value.
///
/// This should only be set when [SemanticsFlag.isTextField] is set. Defaults
/// to null, which means no limit is imposed on the text field.
int? get maxValueLength => _maxValueLength;
int? _maxValueLength;
/// The current number of characters that have been entered into an editable
/// text field.
///
/// For the purpose of this function a character is defined as one Unicode
/// scalar value.
///
/// This should only be set when [SemanticsFlag.isTextField] is set. Must be
/// set when [maxValueLength] is set.
int? get currentValueLength => _currentValueLength;
int? _currentValueLength;
bool _canPerformAction(SemanticsAction action) => _actions.containsKey(action);
static final SemanticsConfiguration _kEmptyConfig = SemanticsConfiguration();
/// Reconfigures the properties of this object to describe the configuration
/// provided in the `config` argument and the children listed in the
/// `childrenInInversePaintOrder` argument.
///
/// The arguments may be null; this represents an empty configuration (all
/// values at their defaults, no children).
///
/// No reference is kept to the [SemanticsConfiguration] object, but the child
/// list is used as-is and should therefore not be changed after this call.
void updateWith({
required SemanticsConfiguration? config,
List<SemanticsNode>? childrenInInversePaintOrder,
}) {
config ??= _kEmptyConfig;
if (_isDifferentFromCurrentSemanticAnnotation(config)) {
_markDirty();
}
assert(
config.platformViewId == null || childrenInInversePaintOrder == null || childrenInInversePaintOrder.isEmpty,
'SemanticsNodes with children must not specify a platformViewId.',
);
final bool mergeAllDescendantsIntoThisNodeValueChanged = _mergeAllDescendantsIntoThisNode != config.isMergingSemanticsOfDescendants;
_identifier = config.identifier;
_attributedLabel = config.attributedLabel;
_attributedValue = config.attributedValue;
_attributedIncreasedValue = config.attributedIncreasedValue;
_attributedDecreasedValue = config.attributedDecreasedValue;
_attributedHint = config.attributedHint;
_tooltip = config.tooltip;
_hintOverrides = config.hintOverrides;
_elevation = config.elevation;
_thickness = config.thickness;
_flags = config._flags;
_textDirection = config.textDirection;
_sortKey = config.sortKey;
_actions = Map<SemanticsAction, SemanticsActionHandler>.of(config._actions);
_customSemanticsActions = Map<CustomSemanticsAction, VoidCallback>.of(config._customSemanticsActions);
_actionsAsBits = config._actionsAsBits;
_textSelection = config._textSelection;
_isMultiline = config.isMultiline;
_scrollPosition = config._scrollPosition;
_scrollExtentMax = config._scrollExtentMax;
_scrollExtentMin = config._scrollExtentMin;
_mergeAllDescendantsIntoThisNode = config.isMergingSemanticsOfDescendants;
_scrollChildCount = config.scrollChildCount;
_scrollIndex = config.scrollIndex;
indexInParent = config.indexInParent;
_platformViewId = config._platformViewId;
_maxValueLength = config._maxValueLength;
_currentValueLength = config._currentValueLength;
_areUserActionsBlocked = config.isBlockingUserActions;
_replaceChildren(childrenInInversePaintOrder ?? const <SemanticsNode>[]);
if (mergeAllDescendantsIntoThisNodeValueChanged) {
_updateChildrenMergeFlags();
}
assert(
!_canPerformAction(SemanticsAction.increase) || (value == '') == (increasedValue == ''),
'A SemanticsNode with action "increase" needs to be annotated with either both "value" and "increasedValue" or neither',
);
assert(
!_canPerformAction(SemanticsAction.decrease) || (value == '') == (decreasedValue == ''),
'A SemanticsNode with action "decrease" needs to be annotated with either both "value" and "decreasedValue" or neither',
);
}
/// Returns a summary of the semantics for this node.
///
/// If this node has [mergeAllDescendantsIntoThisNode], then the returned data
/// includes the information from this node's descendants. Otherwise, the
/// returned data matches the data on this node.
SemanticsData getSemanticsData() {
int flags = _flags;
// Can't use _effectiveActionsAsBits here. The filtering of action bits
// must be done after the merging the its descendants.
int actions = _actionsAsBits;
String identifier = _identifier;
AttributedString attributedLabel = _attributedLabel;
AttributedString attributedValue = _attributedValue;
AttributedString attributedIncreasedValue = _attributedIncreasedValue;
AttributedString attributedDecreasedValue = _attributedDecreasedValue;
AttributedString attributedHint = _attributedHint;
String tooltip = _tooltip;
TextDirection? textDirection = _textDirection;
Set<SemanticsTag>? mergedTags = tags == null ? null : Set<SemanticsTag>.of(tags!);
TextSelection? textSelection = _textSelection;
int? scrollChildCount = _scrollChildCount;
int? scrollIndex = _scrollIndex;
double? scrollPosition = _scrollPosition;
double? scrollExtentMax = _scrollExtentMax;
double? scrollExtentMin = _scrollExtentMin;
int? platformViewId = _platformViewId;
int? maxValueLength = _maxValueLength;
int? currentValueLength = _currentValueLength;
final double elevation = _elevation;
double thickness = _thickness;
final Set<int> customSemanticsActionIds = <int>{};
for (final CustomSemanticsAction action in _customSemanticsActions.keys) {
customSemanticsActionIds.add(CustomSemanticsAction.getIdentifier(action));
}
if (hintOverrides != null) {
if (hintOverrides!.onTapHint != null) {
final CustomSemanticsAction action = CustomSemanticsAction.overridingAction(
hint: hintOverrides!.onTapHint!,
action: SemanticsAction.tap,
);
customSemanticsActionIds.add(CustomSemanticsAction.getIdentifier(action));
}
if (hintOverrides!.onLongPressHint != null) {
final CustomSemanticsAction action = CustomSemanticsAction.overridingAction(
hint: hintOverrides!.onLongPressHint!,
action: SemanticsAction.longPress,
);
customSemanticsActionIds.add(CustomSemanticsAction.getIdentifier(action));
}
}
if (mergeAllDescendantsIntoThisNode) {
_visitDescendants((SemanticsNode node) {
assert(node.isMergedIntoParent);
flags |= node._flags;
actions |= node._effectiveActionsAsBits;
textDirection ??= node._textDirection;
textSelection ??= node._textSelection;
scrollChildCount ??= node._scrollChildCount;
scrollIndex ??= node._scrollIndex;
scrollPosition ??= node._scrollPosition;
scrollExtentMax ??= node._scrollExtentMax;
scrollExtentMin ??= node._scrollExtentMin;
platformViewId ??= node._platformViewId;
maxValueLength ??= node._maxValueLength;
currentValueLength ??= node._currentValueLength;
if (identifier == '') {
identifier = node._identifier;
}
if (attributedValue.string == '') {
attributedValue = node._attributedValue;
}
if (attributedIncreasedValue.string == '') {
attributedIncreasedValue = node._attributedIncreasedValue;
}
if (attributedDecreasedValue.string == '') {
attributedDecreasedValue = node._attributedDecreasedValue;
}
if (tooltip == '') {
tooltip = node._tooltip;
}
if (node.tags != null) {
mergedTags ??= <SemanticsTag>{};
mergedTags!.addAll(node.tags!);
}
for (final CustomSemanticsAction action in _customSemanticsActions.keys) {
customSemanticsActionIds.add(CustomSemanticsAction.getIdentifier(action));
}
if (node.hintOverrides != null) {
if (node.hintOverrides!.onTapHint != null) {
final CustomSemanticsAction action = CustomSemanticsAction.overridingAction(
hint: node.hintOverrides!.onTapHint!,
action: SemanticsAction.tap,
);
customSemanticsActionIds.add(CustomSemanticsAction.getIdentifier(action));
}
if (node.hintOverrides!.onLongPressHint != null) {
final CustomSemanticsAction action = CustomSemanticsAction.overridingAction(
hint: node.hintOverrides!.onLongPressHint!,
action: SemanticsAction.longPress,
);
customSemanticsActionIds.add(CustomSemanticsAction.getIdentifier(action));
}
}
attributedLabel = _concatAttributedString(
thisAttributedString: attributedLabel,
thisTextDirection: textDirection,
otherAttributedString: node._attributedLabel,
otherTextDirection: node._textDirection,
);
attributedHint = _concatAttributedString(
thisAttributedString: attributedHint,
thisTextDirection: textDirection,
otherAttributedString: node._attributedHint,
otherTextDirection: node._textDirection,
);
thickness = math.max(thickness, node._thickness + node._elevation);
return true;
});
}
return SemanticsData(
flags: flags,
actions: _areUserActionsBlocked ? actions & _kUnblockedUserActions : actions,
identifier: identifier,
attributedLabel: attributedLabel,
attributedValue: attributedValue,
attributedIncreasedValue: attributedIncreasedValue,
attributedDecreasedValue: attributedDecreasedValue,
attributedHint: attributedHint,
tooltip: tooltip,
textDirection: textDirection,
rect: rect,
transform: transform,
elevation: elevation,
thickness: thickness,
tags: mergedTags,
textSelection: textSelection,
scrollChildCount: scrollChildCount,
scrollIndex: scrollIndex,
scrollPosition: scrollPosition,
scrollExtentMax: scrollExtentMax,
scrollExtentMin: scrollExtentMin,
platformViewId: platformViewId,
maxValueLength: maxValueLength,
currentValueLength: currentValueLength,
customSemanticsActionIds: customSemanticsActionIds.toList()..sort(),
);
}
static Float64List _initIdentityTransform() {
return Matrix4.identity().storage;
}
static final Int32List _kEmptyChildList = Int32List(0);
static final Int32List _kEmptyCustomSemanticsActionsList = Int32List(0);
static final Float64List _kIdentityTransform = _initIdentityTransform();
void _addToUpdate(SemanticsUpdateBuilder builder, Set<int> customSemanticsActionIdsUpdate) {
assert(_dirty);
final SemanticsData data = getSemanticsData();
final Int32List childrenInTraversalOrder;
final Int32List childrenInHitTestOrder;
if (!hasChildren || mergeAllDescendantsIntoThisNode) {
childrenInTraversalOrder = _kEmptyChildList;
childrenInHitTestOrder = _kEmptyChildList;
} else {
final int childCount = _children!.length;
final List<SemanticsNode> sortedChildren = _childrenInTraversalOrder();
childrenInTraversalOrder = Int32List(childCount);
for (int i = 0; i < childCount; i += 1) {
childrenInTraversalOrder[i] = sortedChildren[i].id;
}
// _children is sorted in paint order, so we invert it to get the hit test
// order.
childrenInHitTestOrder = Int32List(childCount);
for (int i = childCount - 1; i >= 0; i -= 1) {
childrenInHitTestOrder[i] = _children![childCount - i - 1].id;
}
}
Int32List? customSemanticsActionIds;
if (data.customSemanticsActionIds?.isNotEmpty ?? false) {
customSemanticsActionIds = Int32List(data.customSemanticsActionIds!.length);
for (int i = 0; i < data.customSemanticsActionIds!.length; i++) {
customSemanticsActionIds[i] = data.customSemanticsActionIds![i];
customSemanticsActionIdsUpdate.add(data.customSemanticsActionIds![i]);
}
}
builder.updateNode(
id: id,
flags: data.flags,
actions: data.actions,
rect: data.rect,
identifier: data.identifier,
label: data.attributedLabel.string,
labelAttributes: data.attributedLabel.attributes,
value: data.attributedValue.string,
valueAttributes: data.attributedValue.attributes,
increasedValue: data.attributedIncreasedValue.string,
increasedValueAttributes: data.attributedIncreasedValue.attributes,
decreasedValue: data.attributedDecreasedValue.string,
decreasedValueAttributes: data.attributedDecreasedValue.attributes,
hint: data.attributedHint.string,
hintAttributes: data.attributedHint.attributes,
tooltip: data.tooltip,
textDirection: data.textDirection,
textSelectionBase: data.textSelection != null ? data.textSelection!.baseOffset : -1,
textSelectionExtent: data.textSelection != null ? data.textSelection!.extentOffset : -1,
platformViewId: data.platformViewId ?? -1,
maxValueLength: data.maxValueLength ?? -1,
currentValueLength: data.currentValueLength ?? -1,
scrollChildren: data.scrollChildCount ?? 0,
scrollIndex: data.scrollIndex ?? 0 ,
scrollPosition: data.scrollPosition ?? double.nan,
scrollExtentMax: data.scrollExtentMax ?? double.nan,
scrollExtentMin: data.scrollExtentMin ?? double.nan,
transform: data.transform?.storage ?? _kIdentityTransform,
elevation: data.elevation,
thickness: data.thickness,
childrenInTraversalOrder: childrenInTraversalOrder,
childrenInHitTestOrder: childrenInHitTestOrder,
additionalActions: customSemanticsActionIds ?? _kEmptyCustomSemanticsActionsList,
);
_dirty = false;
}
/// Builds a new list made of [_children] sorted in semantic traversal order.
List<SemanticsNode> _childrenInTraversalOrder() {
TextDirection? inheritedTextDirection = textDirection;
SemanticsNode? ancestor = parent;
while (inheritedTextDirection == null && ancestor != null) {
inheritedTextDirection = ancestor.textDirection;
ancestor = ancestor.parent;
}
List<SemanticsNode>? childrenInDefaultOrder;
if (inheritedTextDirection != null) {
childrenInDefaultOrder = _childrenInDefaultOrder(_children!, inheritedTextDirection);
} else {
// In the absence of text direction default to paint order.
childrenInDefaultOrder = _children;
}
// List.sort does not guarantee stable sort order. Therefore, children are
// first partitioned into groups that have compatible sort keys, i.e. keys
// in the same group can be compared to each other. These groups stay in
// the same place. Only children within the same group are sorted.
final List<_TraversalSortNode> everythingSorted = <_TraversalSortNode>[];
final List<_TraversalSortNode> sortNodes = <_TraversalSortNode>[];
SemanticsSortKey? lastSortKey;
for (int position = 0; position < childrenInDefaultOrder!.length; position += 1) {
final SemanticsNode child = childrenInDefaultOrder[position];
final SemanticsSortKey? sortKey = child.sortKey;
lastSortKey = position > 0
? childrenInDefaultOrder[position - 1].sortKey
: null;
final bool isCompatibleWithPreviousSortKey = position == 0 ||
sortKey.runtimeType == lastSortKey.runtimeType &&
(sortKey == null || sortKey.name == lastSortKey!.name);
if (!isCompatibleWithPreviousSortKey && sortNodes.isNotEmpty) {
// Do not sort groups with null sort keys. List.sort does not guarantee
// a stable sort order.
if (lastSortKey != null) {
sortNodes.sort();
}
everythingSorted.addAll(sortNodes);
sortNodes.clear();
}
sortNodes.add(_TraversalSortNode(
node: child,
sortKey: sortKey,
position: position,
));
}
// Do not sort groups with null sort keys. List.sort does not guarantee
// a stable sort order.
if (lastSortKey != null) {
sortNodes.sort();
}
everythingSorted.addAll(sortNodes);
return everythingSorted
.map<SemanticsNode>((_TraversalSortNode sortNode) => sortNode.node)
.toList();
}
/// Sends a [SemanticsEvent] associated with this [SemanticsNode].
///
/// Semantics events should be sent to inform interested parties (like
/// the accessibility system of the operating system) about changes to the UI.
void sendEvent(SemanticsEvent event) {
if (!attached) {
return;
}
SystemChannels.accessibility.send(event.toMap(nodeId: id));
}
bool _debugIsActionBlocked(SemanticsAction action) {
bool result = false;
assert((){
result = (_effectiveActionsAsBits & action.index) == 0;
return true;
}());
return result;
}
@override
String toStringShort() => '${objectRuntimeType(this, 'SemanticsNode')}#$id';
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
bool hideOwner = true;
if (_dirty) {
final bool inDirtyNodes = owner != null && owner!._dirtyNodes.contains(this);
properties.add(FlagProperty('inDirtyNodes', value: inDirtyNodes, ifTrue: 'dirty', ifFalse: 'STALE'));
hideOwner = inDirtyNodes;
}
properties.add(DiagnosticsProperty<SemanticsOwner>('owner', owner, level: hideOwner ? DiagnosticLevel.hidden : DiagnosticLevel.info));
properties.add(FlagProperty('isMergedIntoParent', value: isMergedIntoParent, ifTrue: 'merged up ⬆️'));
properties.add(FlagProperty('mergeAllDescendantsIntoThisNode', value: mergeAllDescendantsIntoThisNode, ifTrue: 'merge boundary ⛔️'));
final Offset? offset = transform != null ? MatrixUtils.getAsTranslation(transform!) : null;
if (offset != null) {
properties.add(DiagnosticsProperty<Rect>('rect', rect.shift(offset), showName: false));
} else {
final double? scale = transform != null ? MatrixUtils.getAsScale(transform!) : null;
String? description;
if (scale != null) {
description = '$rect scaled by ${scale.toStringAsFixed(1)}x';
} else if (transform != null && !MatrixUtils.isIdentity(transform!)) {
final String matrix = transform.toString().split('\n').take(4).map<String>((String line) => line.substring(4)).join('; ');
description = '$rect with transform [$matrix]';
}
properties.add(DiagnosticsProperty<Rect>('rect', rect, description: description, showName: false));
}
properties.add(IterableProperty<String>('tags', tags?.map((SemanticsTag tag) => tag.name), defaultValue: null));
final List<String> actions = _actions.keys.map<String>((SemanticsAction action) => '${action.name}${_debugIsActionBlocked(action) ? '🚫️' : ''}').toList()..sort();
final List<String?> customSemanticsActions = _customSemanticsActions.keys
.map<String?>((CustomSemanticsAction action) => action.label)
.toList();
properties.add(IterableProperty<String>('actions', actions, ifEmpty: null));
properties.add(IterableProperty<String?>('customActions', customSemanticsActions, ifEmpty: null));
final List<String> flags = SemanticsFlag.values.where((SemanticsFlag flag) => hasFlag(flag)).map((SemanticsFlag flag) => flag.name).toList();
properties.add(IterableProperty<String>('flags', flags, ifEmpty: null));
properties.add(FlagProperty('isInvisible', value: isInvisible, ifTrue: 'invisible'));
properties.add(FlagProperty('isHidden', value: hasFlag(SemanticsFlag.isHidden), ifTrue: 'HIDDEN'));
properties.add(StringProperty('identifier', _identifier, defaultValue: ''));
properties.add(AttributedStringProperty('label', _attributedLabel));
properties.add(AttributedStringProperty('value', _attributedValue));
properties.add(AttributedStringProperty('increasedValue', _attributedIncreasedValue));
properties.add(AttributedStringProperty('decreasedValue', _attributedDecreasedValue));
properties.add(AttributedStringProperty('hint', _attributedHint));
properties.add(StringProperty('tooltip', _tooltip, defaultValue: ''));
properties.add(EnumProperty<TextDirection>('textDirection', _textDirection, defaultValue: null));
properties.add(DiagnosticsProperty<SemanticsSortKey>('sortKey', sortKey, defaultValue: null));
if (_textSelection?.isValid ?? false) {
properties.add(MessageProperty('text selection', '[${_textSelection!.start}, ${_textSelection!.end}]'));
}
properties.add(IntProperty('platformViewId', platformViewId, defaultValue: null));
properties.add(IntProperty('maxValueLength', maxValueLength, defaultValue: null));
properties.add(IntProperty('currentValueLength', currentValueLength, defaultValue: null));
properties.add(IntProperty('scrollChildren', scrollChildCount, defaultValue: null));
properties.add(IntProperty('scrollIndex', scrollIndex, defaultValue: null));
properties.add(DoubleProperty('scrollExtentMin', scrollExtentMin, defaultValue: null));
properties.add(DoubleProperty('scrollPosition', scrollPosition, defaultValue: null));
properties.add(DoubleProperty('scrollExtentMax', scrollExtentMax, defaultValue: null));
properties.add(IntProperty('indexInParent', indexInParent, defaultValue: null));
properties.add(DoubleProperty('elevation', elevation, defaultValue: 0.0));
properties.add(DoubleProperty('thickness', thickness, defaultValue: 0.0));
}
/// Returns a string representation of this node and its descendants.
///
/// The order in which the children of the [SemanticsNode] will be printed is
/// controlled by the [childOrder] parameter.
@override
String toStringDeep({
String prefixLineOne = '',
String? prefixOtherLines,
DiagnosticLevel minLevel = DiagnosticLevel.debug,
DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.traversalOrder,
}) {
return toDiagnosticsNode(childOrder: childOrder).toStringDeep(prefixLineOne: prefixLineOne, prefixOtherLines: prefixOtherLines, minLevel: minLevel);
}
@override
DiagnosticsNode toDiagnosticsNode({
String? name,
DiagnosticsTreeStyle? style = DiagnosticsTreeStyle.sparse,
DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.traversalOrder,
}) {
return _SemanticsDiagnosticableNode(
name: name,
value: this,
style: style,
childOrder: childOrder,
);
}
@override
List<DiagnosticsNode> debugDescribeChildren({ DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.inverseHitTest }) {
return debugListChildrenInOrder(childOrder)
.map<DiagnosticsNode>((SemanticsNode node) => node.toDiagnosticsNode(childOrder: childOrder))
.toList();
}
/// Returns the list of direct children of this node in the specified order.
List<SemanticsNode> debugListChildrenInOrder(DebugSemanticsDumpOrder childOrder) {
if (_children == null) {
return const <SemanticsNode>[];
}
return switch (childOrder) {
DebugSemanticsDumpOrder.inverseHitTest => _children!,
DebugSemanticsDumpOrder.traversalOrder => _childrenInTraversalOrder(),
};
}
}
/// An edge of a box, such as top, bottom, left or right, used to compute
/// [SemanticsNode]s that overlap vertically or horizontally.
///
/// For computing horizontal overlap in an LTR setting we create two [_BoxEdge]
/// objects for each [SemanticsNode]: one representing the left edge (marked
/// with [isLeadingEdge] equal to true) and one for the right edge (with [isLeadingEdge]
/// equal to false). Similarly, for vertical overlap we also create two objects
/// for each [SemanticsNode], one for the top and one for the bottom edge.
class _BoxEdge implements Comparable<_BoxEdge> {
_BoxEdge({
required this.isLeadingEdge,
required this.offset,
required this.node,
}) : assert(offset.isFinite);
/// True if the edge comes before the seconds edge along the traversal
/// direction, and false otherwise.
///
/// This field is never null.
///
/// For example, in LTR traversal the left edge's [isLeadingEdge] is set to true,
/// the right edge's [isLeadingEdge] is set to false. When considering vertical
/// ordering of boxes, the top edge is the start edge, and the bottom edge is
/// the end edge.
final bool isLeadingEdge;
/// The offset from the start edge of the parent [SemanticsNode] in the
/// direction of the traversal.
final double offset;
/// The node whom this edge belongs.
final SemanticsNode node;
@override
int compareTo(_BoxEdge other) {
return offset.compareTo(other.offset);
}
}
/// A group of [nodes] that are disjoint vertically or horizontally from other
/// nodes that share the same [SemanticsNode] parent.
///
/// The [nodes] are sorted among each other separately from other nodes.
class _SemanticsSortGroup implements Comparable<_SemanticsSortGroup> {
_SemanticsSortGroup({
required this.startOffset,
required this.textDirection,
});
/// The offset from the start edge of the parent [SemanticsNode] in the
/// direction of the traversal.
///
/// This value is equal to the [_BoxEdge.offset] of the first node in the
/// [nodes] list being considered.
final double startOffset;
final TextDirection textDirection;
/// The nodes that are sorted among each other.
final List<SemanticsNode> nodes = <SemanticsNode>[];
@override
int compareTo(_SemanticsSortGroup other) {
return startOffset.compareTo(other.startOffset);
}
/// Sorts this group assuming that [nodes] belong to the same vertical group.
///
/// This method breaks up this group into horizontal [_SemanticsSortGroup]s
/// then sorts them using [sortedWithinKnot].
List<SemanticsNode> sortedWithinVerticalGroup() {
final List<_BoxEdge> edges = <_BoxEdge>[];
for (final SemanticsNode child in nodes) {
// Using a small delta to shrink child rects removes overlapping cases.
final Rect childRect = child.rect.deflate(0.1);
edges.add(_BoxEdge(
isLeadingEdge: true,
offset: _pointInParentCoordinates(child, childRect.topLeft).dx,
node: child,
));
edges.add(_BoxEdge(
isLeadingEdge: false,
offset: _pointInParentCoordinates(child, childRect.bottomRight).dx,
node: child,
));
}
edges.sort();
List<_SemanticsSortGroup> horizontalGroups = <_SemanticsSortGroup>[];
_SemanticsSortGroup? group;
int depth = 0;
for (final _BoxEdge edge in edges) {
if (edge.isLeadingEdge) {
depth += 1;
group ??= _SemanticsSortGroup(
startOffset: edge.offset,
textDirection: textDirection,
);
group.nodes.add(edge.node);
} else {
depth -= 1;
}
if (depth == 0) {
horizontalGroups.add(group!);
group = null;
}
}
horizontalGroups.sort();
if (textDirection == TextDirection.rtl) {
horizontalGroups = horizontalGroups.reversed.toList();
}
return horizontalGroups
.expand((_SemanticsSortGroup group) => group.sortedWithinKnot())
.toList();
}
/// Sorts [nodes] where nodes intersect both vertically and horizontally.
///
/// In the special case when [nodes] contains one or less nodes, this method
/// returns [nodes] unchanged.
///
/// This method constructs a graph, where vertices are [SemanticsNode]s and
/// edges are "traversed before" relation between pairs of nodes. The sort
/// order is the topological sorting of the graph, with the original order of
/// [nodes] used as the tie breaker.
///
/// Whether a node is traversed before another node is determined by the
/// vector that connects the two nodes' centers. If the vector "points to the
/// right or down", defined as the [Offset.direction] being between `-pi/4`
/// and `3*pi/4`), then the semantics node whose center is at the end of the
/// vector is said to be traversed after.
List<SemanticsNode> sortedWithinKnot() {
if (nodes.length <= 1) {
// Trivial knot. Nothing to do.
return nodes;
}
final Map<int, SemanticsNode> nodeMap = <int, SemanticsNode>{};
final Map<int, int> edges = <int, int>{};
for (final SemanticsNode node in nodes) {
nodeMap[node.id] = node;
final Offset center = _pointInParentCoordinates(node, node.rect.center);
for (final SemanticsNode nextNode in nodes) {
if (identical(node, nextNode) || edges[nextNode.id] == node.id) {
// Skip self or when we've already established that the next node
// points to current node.
continue;
}
final Offset nextCenter = _pointInParentCoordinates(nextNode, nextNode.rect.center);
final Offset centerDelta = nextCenter - center;
// When centers coincide, direction is 0.0.
final double direction = centerDelta.direction;
final bool isLtrAndForward = textDirection == TextDirection.ltr &&
-math.pi / 4 < direction && direction < 3 * math.pi / 4;
final bool isRtlAndForward = textDirection == TextDirection.rtl &&
(direction < -3 * math.pi / 4 || direction > 3 * math.pi / 4);
if (isLtrAndForward || isRtlAndForward) {
edges[node.id] = nextNode.id;
}
}
}
final List<int> sortedIds = <int>[];
final Set<int> visitedIds = <int>{};
final List<SemanticsNode> startNodes = nodes.toList()..sort((SemanticsNode a, SemanticsNode b) {
final Offset aTopLeft = _pointInParentCoordinates(a, a.rect.topLeft);
final Offset bTopLeft = _pointInParentCoordinates(b, b.rect.topLeft);
final int verticalDiff = aTopLeft.dy.compareTo(bTopLeft.dy);
if (verticalDiff != 0) {
return -verticalDiff;
}
return -aTopLeft.dx.compareTo(bTopLeft.dx);
});
void search(int id) {
if (visitedIds.contains(id)) {
return;
}
visitedIds.add(id);
if (edges.containsKey(id)) {
search(edges[id]!);
}
sortedIds.add(id);
}
startNodes.map<int>((SemanticsNode node) => node.id).forEach(search);
return sortedIds.map<SemanticsNode>((int id) => nodeMap[id]!).toList().reversed.toList();
}
}
/// Converts `point` to the `node`'s parent's coordinate system.
Offset _pointInParentCoordinates(SemanticsNode node, Offset point) {
if (node.transform == null) {
return point;
}
final Vector3 vector = Vector3(point.dx, point.dy, 0.0);
node.transform!.transform3(vector);
return Offset(vector.x, vector.y);
}
/// Sorts `children` using the default sorting algorithm, and returns them as a
/// new list.
///
/// The algorithm first breaks up children into groups such that no two nodes
/// from different groups overlap vertically. These groups are sorted vertically
/// according to their [_SemanticsSortGroup.startOffset].
///
/// Within each group, the nodes are sorted using
/// [_SemanticsSortGroup.sortedWithinVerticalGroup].
///
/// For an illustration of the algorithm see http://bit.ly/flutter-default-traversal.
List<SemanticsNode> _childrenInDefaultOrder(List<SemanticsNode> children, TextDirection textDirection) {
final List<_BoxEdge> edges = <_BoxEdge>[];
for (final SemanticsNode child in children) {
assert(child.rect.isFinite);
// Using a small delta to shrink child rects removes overlapping cases.
final Rect childRect = child.rect.deflate(0.1);
edges.add(_BoxEdge(
isLeadingEdge: true,
offset: _pointInParentCoordinates(child, childRect.topLeft).dy,
node: child,
));
edges.add(_BoxEdge(
isLeadingEdge: false,
offset: _pointInParentCoordinates(child, childRect.bottomRight).dy,
node: child,
));
}
edges.sort();
final List<_SemanticsSortGroup> verticalGroups = <_SemanticsSortGroup>[];
_SemanticsSortGroup? group;
int depth = 0;
for (final _BoxEdge edge in edges) {
if (edge.isLeadingEdge) {
depth += 1;
group ??= _SemanticsSortGroup(
startOffset: edge.offset,
textDirection: textDirection,
);
group.nodes.add(edge.node);
} else {
depth -= 1;
}
if (depth == 0) {
verticalGroups.add(group!);
group = null;
}
}
verticalGroups.sort();
return verticalGroups
.expand((_SemanticsSortGroup group) => group.sortedWithinVerticalGroup())
.toList();
}
/// The implementation of [Comparable] that implements the ordering of
/// [SemanticsNode]s in the accessibility traversal.
///
/// [SemanticsNode]s are sorted prior to sending them to the engine side.
///
/// This implementation considers a [node]'s [sortKey] and its position within
/// the list of its siblings. [sortKey] takes precedence over position.
class _TraversalSortNode implements Comparable<_TraversalSortNode> {
_TraversalSortNode({
required this.node,
this.sortKey,
required this.position,
});
/// The node whose position this sort node determines.
final SemanticsNode node;
/// Determines the position of this node among its siblings.
///
/// Sort keys take precedence over other attributes, such as
/// [position].
final SemanticsSortKey? sortKey;
/// Position within the list of siblings as determined by the default sort
/// order.
final int position;
@override
int compareTo(_TraversalSortNode other) {
if (sortKey == null || other.sortKey == null) {
return position - other.position;
}
return sortKey!.compareTo(other.sortKey!);
}
}
/// Owns [SemanticsNode] objects and notifies listeners of changes to the
/// render tree semantics.
///
/// To listen for semantic updates, call [SemanticsBinding.ensureSemantics] or
/// [PipelineOwner.ensureSemantics] to obtain a [SemanticsHandle]. This will
/// create a [SemanticsOwner] if necessary.
class SemanticsOwner extends ChangeNotifier {
/// Creates a [SemanticsOwner] that manages zero or more [SemanticsNode] objects.
SemanticsOwner({
required this.onSemanticsUpdate,
}){
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectCreated(
library: 'package:flutter/semantics.dart',
className: '$SemanticsOwner',
object: this,
);
}
}
/// The [onSemanticsUpdate] callback is expected to dispatch [SemanticsUpdate]s
/// to the [FlutterView] that is associated with this [PipelineOwner] and/or
/// [SemanticsOwner].
///
/// A [SemanticsOwner] calls [onSemanticsUpdate] during [sendSemanticsUpdate]
/// after the [SemanticsUpdate] has been build, but before the [SemanticsOwner]'s
/// listeners have been notified.
final SemanticsUpdateCallback onSemanticsUpdate;
final Set<SemanticsNode> _dirtyNodes = <SemanticsNode>{};
final Map<int, SemanticsNode> _nodes = <int, SemanticsNode>{};
final Set<SemanticsNode> _detachedNodes = <SemanticsNode>{};
/// The root node of the semantics tree, if any.
///
/// If the semantics tree is empty, returns null.
SemanticsNode? get rootSemanticsNode => _nodes[0];
@override
void dispose() {
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
_dirtyNodes.clear();
_nodes.clear();
_detachedNodes.clear();
super.dispose();
}
/// Update the semantics using [onSemanticsUpdate].
void sendSemanticsUpdate() {
// Once the tree is up-to-date, verify that every node is visible.
assert(() {
final List<SemanticsNode> invisibleNodes = <SemanticsNode>[];
// Finds the invisible nodes in the tree rooted at `node` and adds them to
// the invisibleNodes list. If a node is itself invisible, all its
// descendants will be skipped.
bool findInvisibleNodes(SemanticsNode node) {
if (node.rect.isEmpty) {
invisibleNodes.add(node);
} else if (!node.mergeAllDescendantsIntoThisNode) {
node.visitChildren(findInvisibleNodes);
}
return true;
}
final SemanticsNode? rootSemanticsNode = this.rootSemanticsNode;
if (rootSemanticsNode != null) {
// The root node is allowed to be invisible when it has no children.
if (rootSemanticsNode.childrenCount > 0 && rootSemanticsNode.rect.isEmpty) {
invisibleNodes.add(rootSemanticsNode);
} else if (!rootSemanticsNode.mergeAllDescendantsIntoThisNode) {
rootSemanticsNode.visitChildren(findInvisibleNodes);
}
}
if (invisibleNodes.isEmpty) {
return true;
}
List<DiagnosticsNode> nodeToMessage(SemanticsNode invisibleNode) {
final SemanticsNode? parent = invisibleNode.parent;
return<DiagnosticsNode>[
invisibleNode.toDiagnosticsNode(style: DiagnosticsTreeStyle.errorProperty),
parent?.toDiagnosticsNode(name: 'which was added as a child of', style: DiagnosticsTreeStyle.errorProperty) ?? ErrorDescription('which was added as the root SemanticsNode'),
];
}
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Invisible SemanticsNodes should not be added to the tree.'),
ErrorDescription('The following invisible SemanticsNodes were added to the tree:'),
...invisibleNodes.expand(nodeToMessage),
ErrorHint(
'An invisible SemanticsNode is one whose rect is not on screen hence not reachable for users, '
'and its semantic information is not merged into a visible parent.'
),
ErrorHint(
'An invisible SemanticsNode makes the accessibility experience confusing, '
'as it does not provide any visual indication when the user selects it '
'via accessibility technologies.'
),
ErrorHint(
'Consider removing the above invisible SemanticsNodes if they were added by your '
'RenderObject.assembleSemanticsNode implementation, or filing a bug on GitHub:\n'
' https://github.com/flutter/flutter/issues/new?template=2_bug.yml',
),
]);
}());
if (_dirtyNodes.isEmpty) {
return;
}
final Set<int> customSemanticsActionIds = <int>{};
final List<SemanticsNode> visitedNodes = <SemanticsNode>[];
while (_dirtyNodes.isNotEmpty) {
final List<SemanticsNode> localDirtyNodes = _dirtyNodes.where((SemanticsNode node) => !_detachedNodes.contains(node)).toList();
_dirtyNodes.clear();
_detachedNodes.clear();
localDirtyNodes.sort((SemanticsNode a, SemanticsNode b) => a.depth - b.depth);
visitedNodes.addAll(localDirtyNodes);
for (final SemanticsNode node in localDirtyNodes) {
assert(node._dirty);
assert(node.parent == null || !node.parent!.isPartOfNodeMerging || node.isMergedIntoParent);
if (node.isPartOfNodeMerging) {
assert(node.mergeAllDescendantsIntoThisNode || node.parent != null);
// if we're merged into our parent, make sure our parent is added to the dirty list
if (node.parent != null && node.parent!.isPartOfNodeMerging) {
node.parent!._markDirty(); // this can add the node to the dirty list
node._dirty = false; // We don't want to send update for this node.
}
}
}
}
visitedNodes.sort((SemanticsNode a, SemanticsNode b) => a.depth - b.depth);
final SemanticsUpdateBuilder builder = SemanticsBinding.instance.createSemanticsUpdateBuilder();
for (final SemanticsNode node in visitedNodes) {
assert(node.parent?._dirty != true); // could be null (no parent) or false (not dirty)
// The _serialize() method marks the node as not dirty, and
// recurses through the tree to do a deep serialization of all
// contiguous dirty nodes. This means that when we return here,
// it's quite possible that subsequent nodes are no longer
// dirty. We skip these here.
// We also skip any nodes that were reset and subsequently
// dropped entirely (RenderObject.markNeedsSemanticsUpdate()
// calls reset() on its SemanticsNode if onlyChanges isn't set,
// which happens e.g. when the node is no longer contributing
// semantics).
if (node._dirty && node.attached) {
node._addToUpdate(builder, customSemanticsActionIds);
}
}
_dirtyNodes.clear();
for (final int actionId in customSemanticsActionIds) {
final CustomSemanticsAction action = CustomSemanticsAction.getAction(actionId)!;
builder.updateCustomAction(id: actionId, label: action.label, hint: action.hint, overrideId: action.action?.index ?? -1);
}
onSemanticsUpdate(builder.build());
notifyListeners();
}
SemanticsActionHandler? _getSemanticsActionHandlerForId(int id, SemanticsAction action) {
SemanticsNode? result = _nodes[id];
if (result != null && result.isPartOfNodeMerging && !result._canPerformAction(action)) {
result._visitDescendants((SemanticsNode node) {
if (node._canPerformAction(action)) {
result = node;
return false; // found node, abort walk
}
return true; // continue walk
});
}
if (result == null || !result!._canPerformAction(action)) {
return null;
}
return result!._actions[action];
}
/// Asks the [SemanticsNode] with the given id to perform the given action.
///
/// If the [SemanticsNode] has not indicated that it can perform the action,
/// this function does nothing.
///
/// If the given `action` requires arguments they need to be passed in via
/// the `args` parameter.
void performAction(int id, SemanticsAction action, [ Object? args ]) {
final SemanticsActionHandler? handler = _getSemanticsActionHandlerForId(id, action);
if (handler != null) {
handler(args);
return;
}
// Default actions if no [handler] was provided.
if (action == SemanticsAction.showOnScreen && _nodes[id]?._showOnScreen != null) {
_nodes[id]!._showOnScreen!();
}
}
SemanticsActionHandler? _getSemanticsActionHandlerForPosition(SemanticsNode node, Offset position, SemanticsAction action) {
if (node.transform != null) {
final Matrix4 inverse = Matrix4.identity();
if (inverse.copyInverse(node.transform!) == 0.0) {
return null;
}
position = MatrixUtils.transformPoint(inverse, position);
}
if (!node.rect.contains(position)) {
return null;
}
if (node.mergeAllDescendantsIntoThisNode) {
SemanticsNode? result;
node._visitDescendants((SemanticsNode child) {
if (child._canPerformAction(action)) {
result = child;
return false;
}
return true;
});
return result?._actions[action];
}
if (node.hasChildren) {
for (final SemanticsNode child in node._children!.reversed) {
final SemanticsActionHandler? handler = _getSemanticsActionHandlerForPosition(child, position, action);
if (handler != null) {
return handler;
}
}
}
return node._actions[action];
}
/// Asks the [SemanticsNode] at the given position to perform the given action.
///
/// If the [SemanticsNode] has not indicated that it can perform the action,
/// this function does nothing.
///
/// If the given `action` requires arguments they need to be passed in via
/// the `args` parameter.
void performActionAt(Offset position, SemanticsAction action, [ Object? args ]) {
final SemanticsNode? node = rootSemanticsNode;
if (node == null) {
return;
}
final SemanticsActionHandler? handler = _getSemanticsActionHandlerForPosition(node, position, action);
if (handler != null) {
handler(args);
}
}
@override
String toString() => describeIdentity(this);
}
/// Describes the semantic information associated with the owning
/// [RenderObject].
///
/// The information provided in the configuration is used to generate the
/// semantics tree.
class SemanticsConfiguration {
// SEMANTIC BOUNDARY BEHAVIOR
/// Whether the [RenderObject] owner of this configuration wants to own its
/// own [SemanticsNode].
///
/// When set to true semantic information associated with the [RenderObject]
/// owner of this configuration or any of its descendants will not leak into
/// parents. The [SemanticsNode] generated out of this configuration will
/// act as a boundary.
///
/// Whether descendants of the owning [RenderObject] can add their semantic
/// information to the [SemanticsNode] introduced by this configuration
/// is controlled by [explicitChildNodes].
///
/// This has to be true if [isMergingSemanticsOfDescendants] is also true.
bool get isSemanticBoundary => _isSemanticBoundary;
bool _isSemanticBoundary = false;
set isSemanticBoundary(bool value) {
assert(!isMergingSemanticsOfDescendants || value);
_isSemanticBoundary = value;
}
/// Whether to block pointer related user actions for the rendering subtree.
///
/// Setting this to true will prevent users from interacting with the
/// rendering object produces this semantics configuration and its subtree
/// through pointer-related [SemanticsAction]s in assistive technologies.
///
/// The [SemanticsNode] created from this semantics configuration is still
/// focusable by assistive technologies. Only pointer-related
/// [SemanticsAction]s, such as [SemanticsAction.tap] or its friends, are
/// blocked.
///
/// If this semantics configuration is merged into a parent semantics node,
/// only the [SemanticsAction]s from this rendering object and the rendering
/// objects in the subtree are blocked.
bool isBlockingUserActions = false;
/// Whether the configuration forces all children of the owning [RenderObject]
/// that want to contribute semantic information to the semantics tree to do
/// so in the form of explicit [SemanticsNode]s.
///
/// When set to false children of the owning [RenderObject] are allowed to
/// annotate [SemanticsNode]s of their parent with the semantic information
/// they want to contribute to the semantic tree.
/// When set to true the only way for children of the owning [RenderObject]
/// to contribute semantic information to the semantic tree is to introduce
/// new explicit [SemanticsNode]s to the tree.
///
/// This setting is often used in combination with [isSemanticBoundary] to
/// create semantic boundaries that are either writable or not for children.
bool explicitChildNodes = false;
/// Whether the owning [RenderObject] makes other [RenderObject]s previously
/// painted within the same semantic boundary unreachable for accessibility
/// purposes.
///
/// If set to true, the semantic information for all siblings and cousins of
/// this node, that are earlier in a depth-first pre-order traversal, are
/// dropped from the semantics tree up until a semantic boundary (as defined
/// by [isSemanticBoundary]) is reached.
///
/// If [isSemanticBoundary] and [isBlockingSemanticsOfPreviouslyPaintedNodes]
/// is set on the same node, all previously painted siblings and cousins up
/// until the next ancestor that is a semantic boundary are dropped.
///
/// Paint order as established by [RenderObject.visitChildrenForSemantics] is
/// used to determine if a node is previous to this one.
bool isBlockingSemanticsOfPreviouslyPaintedNodes = false;
// SEMANTIC ANNOTATIONS
// These will end up on [SemanticsNode]s generated from
// [SemanticsConfiguration]s.
/// Whether this configuration is empty.
///
/// An empty configuration doesn't contain any semantic information that it
/// wants to contribute to the semantics tree.
bool get hasBeenAnnotated => _hasBeenAnnotated;
bool _hasBeenAnnotated = false;
/// The actions (with associated action handlers) that this configuration
/// would like to contribute to the semantics tree.
///
/// See also:
///
/// * [addAction] to add an action.
final Map<SemanticsAction, SemanticsActionHandler> _actions = <SemanticsAction, SemanticsActionHandler>{};
int get _effectiveActionsAsBits => isBlockingUserActions ? _actionsAsBits & _kUnblockedUserActions : _actionsAsBits;
int _actionsAsBits = 0;
/// Adds an `action` to the semantics tree.
///
/// The provided `handler` is called to respond to the user triggered
/// `action`.
void _addAction(SemanticsAction action, SemanticsActionHandler handler) {
_actions[action] = handler;
_actionsAsBits |= action.index;
_hasBeenAnnotated = true;
}
/// Adds an `action` to the semantics tree, whose `handler` does not expect
/// any arguments.
///
/// The provided `handler` is called to respond to the user triggered
/// `action`.
void _addArgumentlessAction(SemanticsAction action, VoidCallback handler) {
_addAction(action, (Object? args) {
assert(args == null);
handler();
});
}
/// The handler for [SemanticsAction.tap].
///
/// This is the semantic equivalent of a user briefly tapping the screen with
/// the finger without moving it. For example, a button should implement this
/// action.
///
/// VoiceOver users on iOS and TalkBack users on Android can trigger this
/// action by double-tapping the screen while an element is focused.
///
/// On Android prior to Android Oreo a double-tap on the screen while an
/// element with an [onTap] handler is focused will not call the registered
/// handler. Instead, Android will simulate a pointer down and up event at the
/// center of the focused element. Those pointer events will get dispatched
/// just like a regular tap with TalkBack disabled would: The events will get
/// processed by any [GestureDetector] listening for gestures in the center of
/// the focused element. Therefore, to ensure that [onTap] handlers work
/// properly on Android versions prior to Oreo, a [GestureDetector] with an
/// onTap handler should always be wrapping an element that defines a
/// semantic [onTap] handler. By default a [GestureDetector] will register its
/// own semantic [onTap] handler that follows this principle.
VoidCallback? get onTap => _onTap;
VoidCallback? _onTap;
set onTap(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.tap, value!);
_onTap = value;
}
/// The handler for [SemanticsAction.longPress].
///
/// This is the semantic equivalent of a user pressing and holding the screen
/// with the finger for a few seconds without moving it.
///
/// VoiceOver users on iOS and TalkBack users on Android can trigger this
/// action by double-tapping the screen without lifting the finger after the
/// second tap.
VoidCallback? get onLongPress => _onLongPress;
VoidCallback? _onLongPress;
set onLongPress(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.longPress, value!);
_onLongPress = value;
}
/// The handler for [SemanticsAction.scrollLeft].
///
/// This is the semantic equivalent of a user moving their finger across the
/// screen from right to left. It should be recognized by controls that are
/// horizontally scrollable.
///
/// VoiceOver users on iOS can trigger this action by swiping left with three
/// fingers. TalkBack users on Android can trigger this action by swiping
/// right and then left in one motion path. On Android, [onScrollUp] and
/// [onScrollLeft] share the same gesture. Therefore, only on of them should
/// be provided.
VoidCallback? get onScrollLeft => _onScrollLeft;
VoidCallback? _onScrollLeft;
set onScrollLeft(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.scrollLeft, value!);
_onScrollLeft = value;
}
/// The handler for [SemanticsAction.dismiss].
///
/// This is a request to dismiss the currently focused node.
///
/// TalkBack users on Android can trigger this action in the local context
/// menu, and VoiceOver users on iOS can trigger this action with a standard
/// gesture or menu option.
VoidCallback? get onDismiss => _onDismiss;
VoidCallback? _onDismiss;
set onDismiss(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.dismiss, value!);
_onDismiss = value;
}
/// The handler for [SemanticsAction.scrollRight].
///
/// This is the semantic equivalent of a user moving their finger across the
/// screen from left to right. It should be recognized by controls that are
/// horizontally scrollable.
///
/// VoiceOver users on iOS can trigger this action by swiping right with three
/// fingers. TalkBack users on Android can trigger this action by swiping
/// left and then right in one motion path. On Android, [onScrollDown] and
/// [onScrollRight] share the same gesture. Therefore, only on of them should
/// be provided.
VoidCallback? get onScrollRight => _onScrollRight;
VoidCallback? _onScrollRight;
set onScrollRight(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.scrollRight, value!);
_onScrollRight = value;
}
/// The handler for [SemanticsAction.scrollUp].
///
/// This is the semantic equivalent of a user moving their finger across the
/// screen from bottom to top. It should be recognized by controls that are
/// vertically scrollable.
///
/// VoiceOver users on iOS can trigger this action by swiping up with three
/// fingers. TalkBack users on Android can trigger this action by swiping
/// right and then left in one motion path. On Android, [onScrollUp] and
/// [onScrollLeft] share the same gesture. Therefore, only on of them should
/// be provided.
VoidCallback? get onScrollUp => _onScrollUp;
VoidCallback? _onScrollUp;
set onScrollUp(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.scrollUp, value!);
_onScrollUp = value;
}
/// The handler for [SemanticsAction.scrollDown].
///
/// This is the semantic equivalent of a user moving their finger across the
/// screen from top to bottom. It should be recognized by controls that are
/// vertically scrollable.
///
/// VoiceOver users on iOS can trigger this action by swiping down with three
/// fingers. TalkBack users on Android can trigger this action by swiping
/// left and then right in one motion path. On Android, [onScrollDown] and
/// [onScrollRight] share the same gesture. Therefore, only on of them should
/// be provided.
VoidCallback? get onScrollDown => _onScrollDown;
VoidCallback? _onScrollDown;
set onScrollDown(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.scrollDown, value!);
_onScrollDown = value;
}
/// The handler for [SemanticsAction.increase].
///
/// This is a request to increase the value represented by the widget. For
/// example, this action might be recognized by a slider control.
///
/// If [this.value] is set, [increasedValue] must also be provided and
/// [onIncrease] must ensure that [this.value] will be set to
/// [increasedValue].
///
/// VoiceOver users on iOS can trigger this action by swiping up with one
/// finger. TalkBack users on Android can trigger this action by pressing the
/// volume up button.
VoidCallback? get onIncrease => _onIncrease;
VoidCallback? _onIncrease;
set onIncrease(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.increase, value!);
_onIncrease = value;
}
/// The handler for [SemanticsAction.decrease].
///
/// This is a request to decrease the value represented by the widget. For
/// example, this action might be recognized by a slider control.
///
/// If [this.value] is set, [decreasedValue] must also be provided and
/// [onDecrease] must ensure that [this.value] will be set to
/// [decreasedValue].
///
/// VoiceOver users on iOS can trigger this action by swiping down with one
/// finger. TalkBack users on Android can trigger this action by pressing the
/// volume down button.
VoidCallback? get onDecrease => _onDecrease;
VoidCallback? _onDecrease;
set onDecrease(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.decrease, value!);
_onDecrease = value;
}
/// The handler for [SemanticsAction.copy].
///
/// This is a request to copy the current selection to the clipboard.
///
/// TalkBack users on Android can trigger this action from the local context
/// menu of a text field, for example.
VoidCallback? get onCopy => _onCopy;
VoidCallback? _onCopy;
set onCopy(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.copy, value!);
_onCopy = value;
}
/// The handler for [SemanticsAction.cut].
///
/// This is a request to cut the current selection and place it in the
/// clipboard.
///
/// TalkBack users on Android can trigger this action from the local context
/// menu of a text field, for example.
VoidCallback? get onCut => _onCut;
VoidCallback? _onCut;
set onCut(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.cut, value!);
_onCut = value;
}
/// The handler for [SemanticsAction.paste].
///
/// This is a request to paste the current content of the clipboard.
///
/// TalkBack users on Android can trigger this action from the local context
/// menu of a text field, for example.
VoidCallback? get onPaste => _onPaste;
VoidCallback? _onPaste;
set onPaste(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.paste, value!);
_onPaste = value;
}
/// The handler for [SemanticsAction.showOnScreen].
///
/// A request to fully show the semantics node on screen. For example, this
/// action might be send to a node in a scrollable list that is partially off
/// screen to bring it on screen.
///
/// For elements in a scrollable list the framework provides a default
/// implementation for this action and it is not advised to provide a
/// custom one via this setter.
VoidCallback? get onShowOnScreen => _onShowOnScreen;
VoidCallback? _onShowOnScreen;
set onShowOnScreen(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.showOnScreen, value!);
_onShowOnScreen = value;
}
/// The handler for [SemanticsAction.moveCursorForwardByCharacter].
///
/// This handler is invoked when the user wants to move the cursor in a
/// text field forward by one character.
///
/// TalkBack users can trigger this by pressing the volume up key while the
/// input focus is in a text field.
MoveCursorHandler? get onMoveCursorForwardByCharacter => _onMoveCursorForwardByCharacter;
MoveCursorHandler? _onMoveCursorForwardByCharacter;
set onMoveCursorForwardByCharacter(MoveCursorHandler? value) {
assert(value != null);
_addAction(SemanticsAction.moveCursorForwardByCharacter, (Object? args) {
final bool extendSelection = args! as bool;
value!(extendSelection);
});
_onMoveCursorForwardByCharacter = value;
}
/// The handler for [SemanticsAction.moveCursorBackwardByCharacter].
///
/// This handler is invoked when the user wants to move the cursor in a
/// text field backward by one character.
///
/// TalkBack users can trigger this by pressing the volume down key while the
/// input focus is in a text field.
MoveCursorHandler? get onMoveCursorBackwardByCharacter => _onMoveCursorBackwardByCharacter;
MoveCursorHandler? _onMoveCursorBackwardByCharacter;
set onMoveCursorBackwardByCharacter(MoveCursorHandler? value) {
assert(value != null);
_addAction(SemanticsAction.moveCursorBackwardByCharacter, (Object? args) {
final bool extendSelection = args! as bool;
value!(extendSelection);
});
_onMoveCursorBackwardByCharacter = value;
}
/// The handler for [SemanticsAction.moveCursorForwardByWord].
///
/// This handler is invoked when the user wants to move the cursor in a
/// text field backward by one word.
///
/// TalkBack users can trigger this by pressing the volume down key while the
/// input focus is in a text field.
MoveCursorHandler? get onMoveCursorForwardByWord => _onMoveCursorForwardByWord;
MoveCursorHandler? _onMoveCursorForwardByWord;
set onMoveCursorForwardByWord(MoveCursorHandler? value) {
assert(value != null);
_addAction(SemanticsAction.moveCursorForwardByWord, (Object? args) {
final bool extendSelection = args! as bool;
value!(extendSelection);
});
_onMoveCursorForwardByCharacter = value;
}
/// The handler for [SemanticsAction.moveCursorBackwardByWord].
///
/// This handler is invoked when the user wants to move the cursor in a
/// text field backward by one word.
///
/// TalkBack users can trigger this by pressing the volume down key while the
/// input focus is in a text field.
MoveCursorHandler? get onMoveCursorBackwardByWord => _onMoveCursorBackwardByWord;
MoveCursorHandler? _onMoveCursorBackwardByWord;
set onMoveCursorBackwardByWord(MoveCursorHandler? value) {
assert(value != null);
_addAction(SemanticsAction.moveCursorBackwardByWord, (Object? args) {
final bool extendSelection = args! as bool;
value!(extendSelection);
});
_onMoveCursorBackwardByCharacter = value;
}
/// The handler for [SemanticsAction.setSelection].
///
/// This handler is invoked when the user either wants to change the currently
/// selected text in a text field or change the position of the cursor.
///
/// TalkBack users can trigger this handler by selecting "Move cursor to
/// beginning/end" or "Select all" from the local context menu.
SetSelectionHandler? get onSetSelection => _onSetSelection;
SetSelectionHandler? _onSetSelection;
set onSetSelection(SetSelectionHandler? value) {
assert(value != null);
_addAction(SemanticsAction.setSelection, (Object? args) {
assert(args != null && args is Map);
final Map<String, int> selection = (args! as Map<dynamic, dynamic>).cast<String, int>();
assert(selection['base'] != null && selection['extent'] != null);
value!(TextSelection(
baseOffset: selection['base']!,
extentOffset: selection['extent']!,
));
});
_onSetSelection = value;
}
/// The handler for [SemanticsAction.setText].
///
/// This handler is invoked when the user wants to replace the current text in
/// the text field with a new text.
///
/// Voice access users can trigger this handler by speaking "type <text>" to
/// their Android devices.
SetTextHandler? get onSetText => _onSetText;
SetTextHandler? _onSetText;
set onSetText(SetTextHandler? value) {
assert(value != null);
_addAction(SemanticsAction.setText, (Object? args) {
assert(args != null && args is String);
final String text = args! as String;
value!(text);
});
_onSetText = value;
}
/// The handler for [SemanticsAction.didGainAccessibilityFocus].
///
/// This handler is invoked when the node annotated with this handler gains
/// the accessibility focus. The accessibility focus is the
/// green (on Android with TalkBack) or black (on iOS with VoiceOver)
/// rectangle shown on screen to indicate what element an accessibility
/// user is currently interacting with.
///
/// The accessibility focus is different from the input focus. The input focus
/// is usually held by the element that currently responds to keyboard inputs.
/// Accessibility focus and input focus can be held by two different nodes!
///
/// See also:
///
/// * [onDidLoseAccessibilityFocus], which is invoked when the accessibility
/// focus is removed from the node.
/// * [FocusNode], [FocusScope], [FocusManager], which manage the input focus.
VoidCallback? get onDidGainAccessibilityFocus => _onDidGainAccessibilityFocus;
VoidCallback? _onDidGainAccessibilityFocus;
set onDidGainAccessibilityFocus(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.didGainAccessibilityFocus, value!);
_onDidGainAccessibilityFocus = value;
}
/// The handler for [SemanticsAction.didLoseAccessibilityFocus].
///
/// This handler is invoked when the node annotated with this handler
/// loses the accessibility focus. The accessibility focus is
/// the green (on Android with TalkBack) or black (on iOS with VoiceOver)
/// rectangle shown on screen to indicate what element an accessibility
/// user is currently interacting with.
///
/// The accessibility focus is different from the input focus. The input focus
/// is usually held by the element that currently responds to keyboard inputs.
/// Accessibility focus and input focus can be held by two different nodes!
///
/// See also:
///
/// * [onDidGainAccessibilityFocus], which is invoked when the node gains
/// accessibility focus.
/// * [FocusNode], [FocusScope], [FocusManager], which manage the input focus.
VoidCallback? get onDidLoseAccessibilityFocus => _onDidLoseAccessibilityFocus;
VoidCallback? _onDidLoseAccessibilityFocus;
set onDidLoseAccessibilityFocus(VoidCallback? value) {
_addArgumentlessAction(SemanticsAction.didLoseAccessibilityFocus, value!);
_onDidLoseAccessibilityFocus = value;
}
/// A delegate that decides how to handle [SemanticsConfiguration]s produced
/// in the widget subtree.
///
/// The [SemanticsConfiguration]s are produced by rendering objects in the
/// subtree and want to merge up to their parent. This delegate can decide
/// which of these should be merged together to form sibling SemanticsNodes and
/// which of them should be merged upwards into the parent SemanticsNode.
///
/// The input list of [SemanticsConfiguration]s can be empty if the rendering
/// object of this semantics configuration is a leaf node or child rendering
/// objects do not contribute to the semantics.
ChildSemanticsConfigurationsDelegate? get childConfigurationsDelegate => _childConfigurationsDelegate;
ChildSemanticsConfigurationsDelegate? _childConfigurationsDelegate;
set childConfigurationsDelegate(ChildSemanticsConfigurationsDelegate? value) {
assert(value != null);
_childConfigurationsDelegate = value;
// Setting the childConfigsDelegate does not annotate any meaningful
// semantics information of the config.
}
/// Returns the action handler registered for [action] or null if none was
/// registered.
SemanticsActionHandler? getActionHandler(SemanticsAction action) => _actions[action];
/// Determines the position of this node among its siblings in the traversal
/// sort order.
///
/// This is used to describe the order in which the semantic node should be
/// traversed by the accessibility services on the platform (e.g. VoiceOver
/// on iOS and TalkBack on Android).
///
/// Whether this sort key has an effect on the [SemanticsNode] sort order is
/// subject to how this configuration is used. For example, the [absorb]
/// method may decide to not use this key when it combines multiple
/// [SemanticsConfiguration] objects.
SemanticsSortKey? get sortKey => _sortKey;
SemanticsSortKey? _sortKey;
set sortKey(SemanticsSortKey? value) {
assert(value != null);
_sortKey = value;
_hasBeenAnnotated = true;
}
/// The index of this node within the parent's list of semantic children.
///
/// This includes all semantic nodes, not just those currently in the
/// child list. For example, if a scrollable has five children but the first
/// two are not visible (and thus not included in the list of children), then
/// the index of the last node will still be 4.
int? get indexInParent => _indexInParent;
int? _indexInParent;
set indexInParent(int? value) {
_indexInParent = value;
_hasBeenAnnotated = true;
}
/// The total number of scrollable children that contribute to semantics.
///
/// If the number of children are unknown or unbounded, this value will be
/// null.
int? get scrollChildCount => _scrollChildCount;
int? _scrollChildCount;
set scrollChildCount(int? value) {
if (value == scrollChildCount) {
return;
}
_scrollChildCount = value;
_hasBeenAnnotated = true;
}
/// The index of the first visible scrollable child that contributes to
/// semantics.
int? get scrollIndex => _scrollIndex;
int? _scrollIndex;
set scrollIndex(int? value) {
if (value == scrollIndex) {
return;
}
_scrollIndex = value;
_hasBeenAnnotated = true;
}
/// The id of the platform view, whose semantics nodes will be added as
/// children to this node.
int? get platformViewId => _platformViewId;
int? _platformViewId;
set platformViewId(int? value) {
if (value == platformViewId) {
return;
}
_platformViewId = value;
_hasBeenAnnotated = true;
}
/// The maximum number of characters that can be entered into an editable
/// text field.
///
/// For the purpose of this function a character is defined as one Unicode
/// scalar value.
///
/// This should only be set when [isTextField] is true. Defaults to null,
/// which means no limit is imposed on the text field.
int? get maxValueLength => _maxValueLength;
int? _maxValueLength;
set maxValueLength(int? value) {
if (value == maxValueLength) {
return;
}
_maxValueLength = value;
_hasBeenAnnotated = true;
}
/// The current number of characters that have been entered into an editable
/// text field.
///
/// For the purpose of this function a character is defined as one Unicode
/// scalar value.
///
/// This should only be set when [isTextField] is true. Must be set when
/// [maxValueLength] is set.
int? get currentValueLength => _currentValueLength;
int? _currentValueLength;
set currentValueLength(int? value) {
if (value == currentValueLength) {
return;
}
_currentValueLength = value;
_hasBeenAnnotated = true;
}
/// Whether the semantic information provided by the owning [RenderObject] and
/// all of its descendants should be treated as one logical entity.
///
/// If set to true, the descendants of the owning [RenderObject]'s
/// [SemanticsNode] will merge their semantic information into the
/// [SemanticsNode] representing the owning [RenderObject].
///
/// Setting this to true requires that [isSemanticBoundary] is also true.
bool get isMergingSemanticsOfDescendants => _isMergingSemanticsOfDescendants;
bool _isMergingSemanticsOfDescendants = false;
set isMergingSemanticsOfDescendants(bool value) {
assert(isSemanticBoundary);
_isMergingSemanticsOfDescendants = value;
_hasBeenAnnotated = true;
}
/// The handlers for each supported [CustomSemanticsAction].
///
/// Whenever a custom accessibility action is added to a node, the action
/// [SemanticsAction.customAction] is automatically added. A handler is
/// created which uses the passed argument to lookup the custom action
/// handler from this map and invoke it, if present.
Map<CustomSemanticsAction, VoidCallback> get customSemanticsActions => _customSemanticsActions;
Map<CustomSemanticsAction, VoidCallback> _customSemanticsActions = <CustomSemanticsAction, VoidCallback>{};
set customSemanticsActions(Map<CustomSemanticsAction, VoidCallback> value) {
_hasBeenAnnotated = true;
_actionsAsBits |= SemanticsAction.customAction.index;
_customSemanticsActions = value;
_actions[SemanticsAction.customAction] = _onCustomSemanticsAction;
}
void _onCustomSemanticsAction(Object? args) {
final CustomSemanticsAction? action = CustomSemanticsAction.getAction(args! as int);
if (action == null) {
return;
}
final VoidCallback? callback = _customSemanticsActions[action];
if (callback != null) {
callback();
}
}
/// {@macro flutter.semantics.SemanticsProperties.identifier}
String get identifier => _identifier;
String _identifier = '';
set identifier(String identifier) {
_identifier = identifier;
_hasBeenAnnotated = true;
}
/// A textual description of the owning [RenderObject].
///
/// Setting this attribute will override the [attributedLabel].
///
/// The reading direction is given by [textDirection].
///
/// See also:
///
/// * [attributedLabel], which is the [AttributedString] of this property.
String get label => _attributedLabel.string;
set label(String label) {
_attributedLabel = AttributedString(label);
_hasBeenAnnotated = true;
}
/// A textual description of the owning [RenderObject] in [AttributedString]
/// format.
///
/// On iOS this is used for the `accessibilityAttributedLabel` property
/// defined in the `UIAccessibility` Protocol. On Android it is concatenated
/// together with [attributedValue] and [attributedHint] in the following
/// order: [attributedValue], [attributedLabel], [attributedHint]. The
/// concatenated value is then used as the `Text` description.
///
/// The reading direction is given by [textDirection].
///
/// See also:
///
/// * [label], which is the raw text of this property.
AttributedString get attributedLabel => _attributedLabel;
AttributedString _attributedLabel = AttributedString('');
set attributedLabel(AttributedString attributedLabel) {
_attributedLabel = attributedLabel;
_hasBeenAnnotated = true;
}
/// A textual description for the current value of the owning [RenderObject].
///
/// Setting this attribute will override the [attributedValue].
///
/// The reading direction is given by [textDirection].
///
/// See also:
///
/// * [attributedValue], which is the [AttributedString] of this property.
/// * [increasedValue] and [attributedIncreasedValue], which describe what
/// [value] will be after performing [SemanticsAction.increase].
/// * [decreasedValue] and [attributedDecreasedValue], which describe what
/// [value] will be after performing [SemanticsAction.decrease].
String get value => _attributedValue.string;
set value(String value) {
_attributedValue = AttributedString(value);
_hasBeenAnnotated = true;
}
/// A textual description for the current value of the owning [RenderObject]
/// in [AttributedString] format.
///
/// On iOS this is used for the `accessibilityAttributedValue` property
/// defined in the `UIAccessibility` Protocol. On Android it is concatenated
/// together with [attributedLabel] and [attributedHint] in the following
/// order: [attributedValue], [attributedLabel], [attributedHint]. The
/// concatenated value is then used as the `Text` description.
///
/// The reading direction is given by [textDirection].
///
/// See also:
///
/// * [value], which is the raw text of this property.
/// * [attributedIncreasedValue], which describes what [value] will be after
/// performing [SemanticsAction.increase].
/// * [attributedDecreasedValue], which describes what [value] will be after
/// performing [SemanticsAction.decrease].
AttributedString get attributedValue => _attributedValue;
AttributedString _attributedValue = AttributedString('');
set attributedValue(AttributedString attributedValue) {
_attributedValue = attributedValue;
_hasBeenAnnotated = true;
}
/// The value that [value] will have after performing a
/// [SemanticsAction.increase] action.
///
/// Setting this attribute will override the [attributedIncreasedValue].
///
/// One of the [attributedIncreasedValue] or [increasedValue] must be set if
/// a handler for [SemanticsAction.increase] is provided and one of the
/// [value] or [attributedValue] is set.
///
/// The reading direction is given by [textDirection].
///
/// See also:
///
/// * [attributedIncreasedValue], which is the [AttributedString] of this property.
String get increasedValue => _attributedIncreasedValue.string;
set increasedValue(String increasedValue) {
_attributedIncreasedValue = AttributedString(increasedValue);
_hasBeenAnnotated = true;
}
/// The value that [value] will have after performing a
/// [SemanticsAction.increase] action in [AttributedString] format.
///
/// One of the [attributedIncreasedValue] or [increasedValue] must be set if
/// a handler for [SemanticsAction.increase] is provided and one of the
/// [value] or [attributedValue] is set.
///
/// The reading direction is given by [textDirection].
///
/// See also:
///
/// * [increasedValue], which is the raw text of this property.
AttributedString get attributedIncreasedValue => _attributedIncreasedValue;
AttributedString _attributedIncreasedValue = AttributedString('');
set attributedIncreasedValue(AttributedString attributedIncreasedValue) {
_attributedIncreasedValue = attributedIncreasedValue;
_hasBeenAnnotated = true;
}
/// The value that [value] will have after performing a
/// [SemanticsAction.decrease] action.
///
/// Setting this attribute will override the [attributedDecreasedValue].
///
/// One of the [attributedDecreasedValue] or [decreasedValue] must be set if
/// a handler for [SemanticsAction.decrease] is provided and one of the
/// [value] or [attributedValue] is set.
///
/// The reading direction is given by [textDirection].
///
/// * [attributedDecreasedValue], which is the [AttributedString] of this property.
String get decreasedValue => _attributedDecreasedValue.string;
set decreasedValue(String decreasedValue) {
_attributedDecreasedValue = AttributedString(decreasedValue);
_hasBeenAnnotated = true;
}
/// The value that [value] will have after performing a
/// [SemanticsAction.decrease] action in [AttributedString] format.
///
/// One of the [attributedDecreasedValue] or [decreasedValue] must be set if
/// a handler for [SemanticsAction.decrease] is provided and one of the
/// [value] or [attributedValue] is set.
///
/// The reading direction is given by [textDirection].
///
/// See also:
///
/// * [decreasedValue], which is the raw text of this property.
AttributedString get attributedDecreasedValue => _attributedDecreasedValue;
AttributedString _attributedDecreasedValue = AttributedString('');
set attributedDecreasedValue(AttributedString attributedDecreasedValue) {
_attributedDecreasedValue = attributedDecreasedValue;
_hasBeenAnnotated = true;
}
/// A brief description of the result of performing an action on this node.
///
/// Setting this attribute will override the [attributedHint].
///
/// The reading direction is given by [textDirection].
///
/// See also:
///
/// * [attributedHint], which is the [AttributedString] of this property.
String get hint => _attributedHint.string;
set hint(String hint) {
_attributedHint = AttributedString(hint);
_hasBeenAnnotated = true;
}
/// A brief description of the result of performing an action on this node in
/// [AttributedString] format.
///
/// On iOS this is used for the `accessibilityAttributedHint` property
/// defined in the `UIAccessibility` Protocol. On Android it is concatenated
/// together with [attributedLabel] and [attributedValue] in the following
/// order: [attributedValue], [attributedLabel], [attributedHint]. The
/// concatenated value is then used as the `Text` description.
///
/// The reading direction is given by [textDirection].
///
/// See also:
///
/// * [hint], which is the raw text of this property.
AttributedString get attributedHint => _attributedHint;
AttributedString _attributedHint = AttributedString('');
set attributedHint(AttributedString attributedHint) {
_attributedHint = attributedHint;
_hasBeenAnnotated = true;
}
/// A textual description of the widget's tooltip.
///
/// The reading direction is given by [textDirection].
String get tooltip => _tooltip;
String _tooltip = '';
set tooltip(String tooltip) {
_tooltip = tooltip;
_hasBeenAnnotated = true;
}
/// Provides hint values which override the default hints on supported
/// platforms.
SemanticsHintOverrides? get hintOverrides => _hintOverrides;
SemanticsHintOverrides? _hintOverrides;
set hintOverrides(SemanticsHintOverrides? value) {
if (value == null) {
return;
}
_hintOverrides = value;
_hasBeenAnnotated = true;
}
/// The elevation in z-direction at which the owning [RenderObject] is
/// located relative to its parent.
double get elevation => _elevation;
double _elevation = 0.0;
set elevation(double value) {
assert(value >= 0.0);
if (value == _elevation) {
return;
}
_elevation = value;
_hasBeenAnnotated = true;
}
/// The extend that the owning [RenderObject] occupies in z-direction starting
/// at [elevation].
///
/// It's extremely rare to set this value directly. Instead, it is calculated
/// implicitly when other [SemanticsConfiguration]s are merged into this one
/// via [absorb].
double get thickness => _thickness;
double _thickness = 0.0;
set thickness(double value) {
assert(value >= 0.0);
if (value == _thickness) {
return;
}
_thickness = value;
_hasBeenAnnotated = true;
}
/// Whether the semantics node is the root of a subtree for which values
/// should be announced.
///
/// See also:
///
/// * [SemanticsFlag.scopesRoute], for a full description of route scoping.
bool get scopesRoute => _hasFlag(SemanticsFlag.scopesRoute);
set scopesRoute(bool value) {
_setFlag(SemanticsFlag.scopesRoute, value);
}
/// Whether the semantics node contains the label of a route.
///
/// See also:
///
/// * [SemanticsFlag.namesRoute], for a full description of route naming.
bool get namesRoute => _hasFlag(SemanticsFlag.namesRoute);
set namesRoute(bool value) {
_setFlag(SemanticsFlag.namesRoute, value);
}
/// Whether the semantics node represents an image.
bool get isImage => _hasFlag(SemanticsFlag.isImage);
set isImage(bool value) {
_setFlag(SemanticsFlag.isImage, value);
}
/// Whether the semantics node is a live region.
///
/// A live region indicates that updates to semantics node are important.
/// Platforms may use this information to make polite announcements to the
/// user to inform them of updates to this node.
///
/// An example of a live region is a [SnackBar] widget. On Android and iOS,
/// live region causes a polite announcement to be generated automatically,
/// even if the widget does not have accessibility focus. This announcement
/// may not be spoken if the OS accessibility services are already
/// announcing something else, such as reading the label of a focused widget
/// or providing a system announcement.
///
/// See also:
///
/// * [SemanticsFlag.isLiveRegion], the semantics flag that this setting controls.
bool get liveRegion => _hasFlag(SemanticsFlag.isLiveRegion);
set liveRegion(bool value) {
_setFlag(SemanticsFlag.isLiveRegion, value);
}
/// The reading direction for the text in [label], [value], [hint],
/// [increasedValue], and [decreasedValue].
TextDirection? get textDirection => _textDirection;
TextDirection? _textDirection;
set textDirection(TextDirection? textDirection) {
_textDirection = textDirection;
_hasBeenAnnotated = true;
}
/// Whether the owning [RenderObject] is selected (true) or not (false).
///
/// This is different from having accessibility focus. The element that is
/// accessibility focused may or may not be selected; e.g. a [ListTile] can have
/// accessibility focus but have its [ListTile.selected] property set to false,
/// in which case it will not be flagged as selected.
bool get isSelected => _hasFlag(SemanticsFlag.isSelected);
set isSelected(bool value) {
_setFlag(SemanticsFlag.isSelected, value);
}
/// If this node has Boolean state that can be controlled by the user, whether
/// that state is expanded or collapsed, corresponding to true and false, respectively.
///
/// Do not call the setter for this field if the owning [RenderObject] doesn't
/// have expanded/collapsed state that can be controlled by the user.
///
/// The getter returns null if the owning [RenderObject] does not have
/// expanded/collapsed state.
bool? get isExpanded => _hasFlag(SemanticsFlag.hasExpandedState) ? _hasFlag(SemanticsFlag.isExpanded) : null;
set isExpanded(bool? value) {
_setFlag(SemanticsFlag.hasExpandedState, true);
_setFlag(SemanticsFlag.isExpanded, value!);
}
/// Whether the owning [RenderObject] is currently enabled.
///
/// A disabled object does not respond to user interactions. Only objects that
/// usually respond to user interactions, but which currently do not (like a
/// disabled button) should be marked as disabled.
///
/// The setter should not be called for objects (like static text) that never
/// respond to user interactions.
///
/// The getter will return null if the owning [RenderObject] doesn't support
/// the concept of being enabled/disabled.
///
/// This property does not control whether semantics are enabled. If you wish to
/// disable semantics for a particular widget, you should use an [ExcludeSemantics]
/// widget.
bool? get isEnabled => _hasFlag(SemanticsFlag.hasEnabledState) ? _hasFlag(SemanticsFlag.isEnabled) : null;
set isEnabled(bool? value) {
_setFlag(SemanticsFlag.hasEnabledState, true);
_setFlag(SemanticsFlag.isEnabled, value!);
}
/// If this node has Boolean state that can be controlled by the user, whether
/// that state is checked or unchecked, corresponding to true and false,
/// respectively.
///
/// Do not call the setter for this field if the owning [RenderObject] doesn't
/// have checked/unchecked state that can be controlled by the user.
///
/// The getter returns null if the owning [RenderObject] does not have
/// checked/unchecked state.
bool? get isChecked => _hasFlag(SemanticsFlag.hasCheckedState) ? _hasFlag(SemanticsFlag.isChecked) : null;
set isChecked(bool? value) {
assert(value != true || isCheckStateMixed != true);
_setFlag(SemanticsFlag.hasCheckedState, true);
_setFlag(SemanticsFlag.isChecked, value!);
}
/// If this node has tristate that can be controlled by the user, whether
/// that state is in its mixed state.
///
/// Do not call the setter for this field if the owning [RenderObject] doesn't
/// have checked/unchecked state that can be controlled by the user.
///
/// The getter returns null if the owning [RenderObject] does not have
/// mixed checked state.
bool? get isCheckStateMixed => _hasFlag(SemanticsFlag.hasCheckedState) ? _hasFlag(SemanticsFlag.isCheckStateMixed) : null;
set isCheckStateMixed(bool? value) {
assert(value != true || isChecked != true);
_setFlag(SemanticsFlag.hasCheckedState, true);
_setFlag(SemanticsFlag.isCheckStateMixed, value!);
}
/// If this node has Boolean state that can be controlled by the user, whether
/// that state is on or off, corresponding to true and false, respectively.
///
/// Do not call the setter for this field if the owning [RenderObject] doesn't
/// have on/off state that can be controlled by the user.
///
/// The getter returns null if the owning [RenderObject] does not have
/// on/off state.
bool? get isToggled => _hasFlag(SemanticsFlag.hasToggledState) ? _hasFlag(SemanticsFlag.isToggled) : null;
set isToggled(bool? value) {
_setFlag(SemanticsFlag.hasToggledState, true);
_setFlag(SemanticsFlag.isToggled, value!);
}
/// Whether the owning RenderObject corresponds to UI that allows the user to
/// pick one of several mutually exclusive options.
///
/// For example, a [Radio] button is in a mutually exclusive group because
/// only one radio button in that group can be marked as [isChecked].
bool get isInMutuallyExclusiveGroup => _hasFlag(SemanticsFlag.isInMutuallyExclusiveGroup);
set isInMutuallyExclusiveGroup(bool value) {
_setFlag(SemanticsFlag.isInMutuallyExclusiveGroup, value);
}
/// Whether the owning [RenderObject] can hold the input focus.
bool get isFocusable => _hasFlag(SemanticsFlag.isFocusable);
set isFocusable(bool value) {
_setFlag(SemanticsFlag.isFocusable, value);
}
/// Whether the owning [RenderObject] currently holds the input focus.
bool get isFocused => _hasFlag(SemanticsFlag.isFocused);
set isFocused(bool value) {
_setFlag(SemanticsFlag.isFocused, value);
}
/// Whether the owning [RenderObject] is a button (true) or not (false).
bool get isButton => _hasFlag(SemanticsFlag.isButton);
set isButton(bool value) {
_setFlag(SemanticsFlag.isButton, value);
}
/// Whether the owning [RenderObject] is a link (true) or not (false).
bool get isLink => _hasFlag(SemanticsFlag.isLink);
set isLink(bool value) {
_setFlag(SemanticsFlag.isLink, value);
}
/// Whether the owning [RenderObject] is a header (true) or not (false).
bool get isHeader => _hasFlag(SemanticsFlag.isHeader);
set isHeader(bool value) {
_setFlag(SemanticsFlag.isHeader, value);
}
/// Whether the owning [RenderObject] is a slider (true) or not (false).
bool get isSlider => _hasFlag(SemanticsFlag.isSlider);
set isSlider(bool value) {
_setFlag(SemanticsFlag.isSlider, value);
}
/// Whether the owning [RenderObject] is a keyboard key (true) or not
//(false).
bool get isKeyboardKey => _hasFlag(SemanticsFlag.isKeyboardKey);
set isKeyboardKey(bool value) {
_setFlag(SemanticsFlag.isKeyboardKey, value);
}
/// Whether the owning [RenderObject] is considered hidden.
///
/// Hidden elements are currently not visible on screen. They may be covered
/// by other elements or positioned outside of the visible area of a viewport.
///
/// Hidden elements cannot gain accessibility focus though regular touch. The
/// only way they can be focused is by moving the focus to them via linear
/// navigation.
///
/// Platforms are free to completely ignore hidden elements and new platforms
/// are encouraged to do so.
///
/// Instead of marking an element as hidden it should usually be excluded from
/// the semantics tree altogether. Hidden elements are only included in the
/// semantics tree to work around platform limitations and they are mainly
/// used to implement accessibility scrolling on iOS.
bool get isHidden => _hasFlag(SemanticsFlag.isHidden);
set isHidden(bool value) {
_setFlag(SemanticsFlag.isHidden, value);
}
/// Whether the owning [RenderObject] is a text field.
bool get isTextField => _hasFlag(SemanticsFlag.isTextField);
set isTextField(bool value) {
_setFlag(SemanticsFlag.isTextField, value);
}
/// Whether the owning [RenderObject] is read only.
///
/// Only applicable when [isTextField] is true.
bool get isReadOnly => _hasFlag(SemanticsFlag.isReadOnly);
set isReadOnly(bool value) {
_setFlag(SemanticsFlag.isReadOnly, value);
}
/// Whether [this.value] should be obscured.
///
/// This option is usually set in combination with [isTextField] to indicate
/// that the text field contains a password (or other sensitive information).
/// Doing so instructs screen readers to not read out [this.value].
bool get isObscured => _hasFlag(SemanticsFlag.isObscured);
set isObscured(bool value) {
_setFlag(SemanticsFlag.isObscured, value);
}
/// Whether the text field is multiline.
///
/// This option is usually set in combination with [isTextField] to indicate
/// that the text field is configured to be multiline.
bool get isMultiline => _hasFlag(SemanticsFlag.isMultiline);
set isMultiline(bool value) {
_setFlag(SemanticsFlag.isMultiline, value);
}
/// Whether the platform can scroll the semantics node when the user attempts
/// to move focus to an offscreen child.
///
/// For example, a [ListView] widget has implicit scrolling so that users can
/// easily move to the next visible set of children. A [TabBar] widget does
/// not have implicit scrolling, so that users can navigate into the tab
/// body when reaching the end of the tab bar.
bool get hasImplicitScrolling => _hasFlag(SemanticsFlag.hasImplicitScrolling);
set hasImplicitScrolling(bool value) {
_setFlag(SemanticsFlag.hasImplicitScrolling, value);
}
/// The currently selected text (or the position of the cursor) within
/// [this.value] if this node represents a text field.
TextSelection? get textSelection => _textSelection;
TextSelection? _textSelection;
set textSelection(TextSelection? value) {
assert(value != null);
_textSelection = value;
_hasBeenAnnotated = true;
}
/// Indicates the current scrolling position in logical pixels if the node is
/// scrollable.
///
/// The properties [scrollExtentMin] and [scrollExtentMax] indicate the valid
/// in-range values for this property. The value for [scrollPosition] may
/// (temporarily) be outside that range, e.g. during an overscroll.
///
/// See also:
///
/// * [ScrollPosition.pixels], from where this value is usually taken.
double? get scrollPosition => _scrollPosition;
double? _scrollPosition;
set scrollPosition(double? value) {
assert(value != null);
_scrollPosition = value;
_hasBeenAnnotated = true;
}
/// Indicates the maximum in-range value for [scrollPosition] if the node is
/// scrollable.
///
/// This value may be infinity if the scroll is unbound.
///
/// See also:
///
/// * [ScrollPosition.maxScrollExtent], from where this value is usually taken.
double? get scrollExtentMax => _scrollExtentMax;
double? _scrollExtentMax;
set scrollExtentMax(double? value) {
assert(value != null);
_scrollExtentMax = value;
_hasBeenAnnotated = true;
}
/// Indicates the minimum in-range value for [scrollPosition] if the node is
/// scrollable.
///
/// This value may be infinity if the scroll is unbound.
///
/// See also:
///
/// * [ScrollPosition.minScrollExtent], from where this value is usually taken.
double? get scrollExtentMin => _scrollExtentMin;
double? _scrollExtentMin;
set scrollExtentMin(double? value) {
assert(value != null);
_scrollExtentMin = value;
_hasBeenAnnotated = true;
}
// TAGS
/// The set of tags that this configuration wants to add to all child
/// [SemanticsNode]s.
///
/// See also:
///
/// * [addTagForChildren] to add a tag and for more information about their
/// usage.
Iterable<SemanticsTag>? get tagsForChildren => _tagsForChildren;
/// Whether this configuration will tag the child semantics nodes with a
/// given [SemanticsTag].
bool tagsChildrenWith(SemanticsTag tag) => _tagsForChildren?.contains(tag) ?? false;
Set<SemanticsTag>? _tagsForChildren;
/// Specifies a [SemanticsTag] that this configuration wants to apply to all
/// child [SemanticsNode]s.
///
/// The tag is added to all [SemanticsNode] that pass through the
/// [RenderObject] owning this configuration while looking to be attached to a
/// parent [SemanticsNode].
///
/// Tags are used to communicate to a parent [SemanticsNode] that a child
/// [SemanticsNode] was passed through a particular [RenderObject]. The parent
/// can use this information to determine the shape of the semantics tree.
///
/// See also:
///
/// * [RenderViewport.excludeFromScrolling] for an example of
/// how tags are used.
void addTagForChildren(SemanticsTag tag) {
_tagsForChildren ??= <SemanticsTag>{};
_tagsForChildren!.add(tag);
}
// INTERNAL FLAG MANAGEMENT
int _flags = 0;
void _setFlag(SemanticsFlag flag, bool value) {
if (value) {
_flags |= flag.index;
} else {
_flags &= ~flag.index;
}
_hasBeenAnnotated = true;
}
bool _hasFlag(SemanticsFlag flag) => (_flags & flag.index) != 0;
// CONFIGURATION COMBINATION LOGIC
/// Whether this configuration is compatible with the provided `other`
/// configuration.
///
/// Two configurations are said to be compatible if they can be added to the
/// same [SemanticsNode] without losing any semantics information.
bool isCompatibleWith(SemanticsConfiguration? other) {
if (other == null || !other.hasBeenAnnotated || !hasBeenAnnotated) {
return true;
}
if (_actionsAsBits & other._actionsAsBits != 0) {
return false;
}
if ((_flags & other._flags) != 0) {
return false;
}
if (_platformViewId != null && other._platformViewId != null) {
return false;
}
if (_maxValueLength != null && other._maxValueLength != null) {
return false;
}
if (_currentValueLength != null && other._currentValueLength != null) {
return false;
}
if (_attributedValue.string.isNotEmpty && other._attributedValue.string.isNotEmpty) {
return false;
}
return true;
}
/// Absorb the semantic information from `child` into this configuration.
///
/// This adds the semantic information of both configurations and saves the
/// result in this configuration.
///
/// The [RenderObject] owning the `child` configuration must be a descendant
/// of the [RenderObject] that owns this configuration.
///
/// Only configurations that have [explicitChildNodes] set to false can
/// absorb other configurations and it is recommended to only absorb compatible
/// configurations as determined by [isCompatibleWith].
void absorb(SemanticsConfiguration child) {
assert(!explicitChildNodes);
if (!child.hasBeenAnnotated) {
return;
}
if (child.isBlockingUserActions) {
child._actions.forEach((SemanticsAction key, SemanticsActionHandler value) {
if (_kUnblockedUserActions & key.index > 0) {
_actions[key] = value;
}
});
} else {
_actions.addAll(child._actions);
}
_actionsAsBits |= child._effectiveActionsAsBits;
_customSemanticsActions.addAll(child._customSemanticsActions);
_flags |= child._flags;
_textSelection ??= child._textSelection;
_scrollPosition ??= child._scrollPosition;
_scrollExtentMax ??= child._scrollExtentMax;
_scrollExtentMin ??= child._scrollExtentMin;
_hintOverrides ??= child._hintOverrides;
_indexInParent ??= child.indexInParent;
_scrollIndex ??= child._scrollIndex;
_scrollChildCount ??= child._scrollChildCount;
_platformViewId ??= child._platformViewId;
_maxValueLength ??= child._maxValueLength;
_currentValueLength ??= child._currentValueLength;
textDirection ??= child.textDirection;
_sortKey ??= child._sortKey;
if (_identifier == '') {
_identifier = child._identifier;
}
_attributedLabel = _concatAttributedString(
thisAttributedString: _attributedLabel,
thisTextDirection: textDirection,
otherAttributedString: child._attributedLabel,
otherTextDirection: child.textDirection,
);
if (_attributedValue.string == '') {
_attributedValue = child._attributedValue;
}
if (_attributedIncreasedValue.string == '') {
_attributedIncreasedValue = child._attributedIncreasedValue;
}
if (_attributedDecreasedValue.string == '') {
_attributedDecreasedValue = child._attributedDecreasedValue;
}
_attributedHint = _concatAttributedString(
thisAttributedString: _attributedHint,
thisTextDirection: textDirection,
otherAttributedString: child._attributedHint,
otherTextDirection: child.textDirection,
);
if (_tooltip == '') {
_tooltip = child._tooltip;
}
_thickness = math.max(_thickness, child._thickness + child._elevation);
_hasBeenAnnotated = _hasBeenAnnotated || child._hasBeenAnnotated;
}
/// Returns an exact copy of this configuration.
SemanticsConfiguration copy() {
return SemanticsConfiguration()
.._isSemanticBoundary = _isSemanticBoundary
..explicitChildNodes = explicitChildNodes
..isBlockingSemanticsOfPreviouslyPaintedNodes = isBlockingSemanticsOfPreviouslyPaintedNodes
.._hasBeenAnnotated = _hasBeenAnnotated
.._isMergingSemanticsOfDescendants = _isMergingSemanticsOfDescendants
.._textDirection = _textDirection
.._sortKey = _sortKey
.._identifier = _identifier
.._attributedLabel = _attributedLabel
.._attributedIncreasedValue = _attributedIncreasedValue
.._attributedValue = _attributedValue
.._attributedDecreasedValue = _attributedDecreasedValue
.._attributedHint = _attributedHint
.._hintOverrides = _hintOverrides
.._tooltip = _tooltip
.._elevation = _elevation
.._thickness = _thickness
.._flags = _flags
.._tagsForChildren = _tagsForChildren
.._textSelection = _textSelection
.._scrollPosition = _scrollPosition
.._scrollExtentMax = _scrollExtentMax
.._scrollExtentMin = _scrollExtentMin
.._actionsAsBits = _actionsAsBits
.._indexInParent = indexInParent
.._scrollIndex = _scrollIndex
.._scrollChildCount = _scrollChildCount
.._platformViewId = _platformViewId
.._maxValueLength = _maxValueLength
.._currentValueLength = _currentValueLength
.._actions.addAll(_actions)
.._customSemanticsActions.addAll(_customSemanticsActions)
..isBlockingUserActions = isBlockingUserActions;
}
}
/// Used by [debugDumpSemanticsTree] to specify the order in which child nodes
/// are printed.
enum DebugSemanticsDumpOrder {
/// Print nodes in inverse hit test order.
///
/// In inverse hit test order, the last child of a [SemanticsNode] will be
/// asked first if it wants to respond to a user's interaction, followed by
/// the second last, etc. until a taker is found.
inverseHitTest,
/// Print nodes in semantic traversal order.
///
/// This is the order in which a user would navigate the UI using the "next"
/// and "previous" gestures.
traversalOrder,
}
AttributedString _concatAttributedString({
required AttributedString thisAttributedString,
required AttributedString otherAttributedString,
required TextDirection? thisTextDirection,
required TextDirection? otherTextDirection,
}) {
if (otherAttributedString.string.isEmpty) {
return thisAttributedString;
}
if (thisTextDirection != otherTextDirection && otherTextDirection != null) {
final AttributedString directionEmbedding = switch (otherTextDirection) {
TextDirection.rtl => AttributedString(Unicode.RLE),
TextDirection.ltr => AttributedString(Unicode.LRE),
};
otherAttributedString = directionEmbedding + otherAttributedString + AttributedString(Unicode.PDF);
}
if (thisAttributedString.string.isEmpty) {
return otherAttributedString;
}
return thisAttributedString + AttributedString('\n') + otherAttributedString;
}
/// Base class for all sort keys for [SemanticsProperties.sortKey] accessibility
/// traversal order sorting.
///
/// Sort keys are sorted by [name], then by the comparison that the subclass
/// implements. If [SemanticsProperties.sortKey] is specified, sort keys within
/// the same semantic group must all be of the same type.
///
/// Keys with no [name] are compared to other keys with no [name], and will
/// be traversed before those with a [name].
///
/// If no sort key is applied to a semantics node, then it will be ordered using
/// a platform dependent default algorithm.
///
/// See also:
///
/// * [OrdinalSortKey] for a sort key that sorts using an ordinal.
abstract class SemanticsSortKey with Diagnosticable implements Comparable<SemanticsSortKey> {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const SemanticsSortKey({this.name});
/// An optional name that will group this sort key with other sort keys of the
/// same [name].
///
/// Sort keys must have the same `runtimeType` when compared.
///
/// Keys with no [name] are compared to other keys with no [name], and will
/// be traversed before those with a [name].
final String? name;
@override
int compareTo(SemanticsSortKey other) {
// Sort by name first and then subclass ordering.
assert(runtimeType == other.runtimeType, 'Semantics sort keys can only be compared to other sort keys of the same type.');
// Defer to the subclass implementation for ordering only if the names are
// identical (or both null).
if (name == other.name) {
return doCompare(other);
}
// Keys that don't have a name are sorted together and come before those with
// a name.
if (name == null && other.name != null) {
return -1;
} else if (name != null && other.name == null) {
return 1;
}
return name!.compareTo(other.name!);
}
/// The implementation of [compareTo].
///
/// The argument is guaranteed to be of the same type as this object and have
/// the same [name].
///
/// The method should return a negative number if this object comes earlier in
/// the sort order than the argument; and a positive number if it comes later
/// in the sort order. Returning zero causes the system to use default sort
/// order.
@protected
int doCompare(covariant SemanticsSortKey other);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(StringProperty('name', name, defaultValue: null));
}
}
/// A [SemanticsSortKey] that sorts based on the `double` value it is
/// given.
///
/// The [OrdinalSortKey] compares itself with other [OrdinalSortKey]s
/// to sort based on the order it is given.
///
/// [OrdinalSortKey]s are sorted by the optional [name], then by their [order].
/// If [SemanticsProperties.sortKey] is a [OrdinalSortKey], then all the other
/// specified sort keys in the same semantics group must also be
/// [OrdinalSortKey]s.
///
/// Keys with no [name] are compared to other keys with no [name], and will
/// be traversed before those with a [name].
///
/// The ordinal value [order] is typically a whole number, though it can be
/// fractional, e.g. in order to fit between two other consecutive whole
/// numbers. The value must be finite (it cannot be [double.nan],
/// [double.infinity], or [double.negativeInfinity]).
class OrdinalSortKey extends SemanticsSortKey {
/// Creates a const semantics sort key that uses a [double] as its key value.
///
/// The [order] must be a finite number.
const OrdinalSortKey(
this.order, {
super.name,
}) : assert(order > double.negativeInfinity),
assert(order < double.infinity);
/// Determines the placement of this key in a sequence of keys that defines
/// the order in which this node is traversed by the platform's accessibility
/// services.
///
/// Lower values will be traversed first. Keys with the same [name] will be
/// grouped together and sorted by name first, and then sorted by [order].
final double order;
@override
int doCompare(OrdinalSortKey other) {
if (other.order == order) {
return 0;
}
return order.compareTo(other.order);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty('order', order, defaultValue: null));
}
}
| flutter/packages/flutter/lib/src/semantics/semantics.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/semantics/semantics.dart",
"repo_id": "flutter",
"token_count": 62262
} | 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 'system_channels.dart';
/// Allows access to the haptic feedback interface on the device.
///
/// This API is intentionally terse since it calls default platform behavior. It
/// is not suitable for precise control of the system's haptic feedback module.
abstract final class HapticFeedback {
/// Provides vibration haptic feedback to the user for a short duration.
///
/// On iOS devices that support haptic feedback, this uses the default system
/// vibration value (`kSystemSoundID_Vibrate`).
///
/// On Android, this uses the platform haptic feedback API to simulate a
/// response to a long press (`HapticFeedbackConstants.LONG_PRESS`).
static Future<void> vibrate() async {
await SystemChannels.platform.invokeMethod<void>('HapticFeedback.vibrate');
}
/// Provides a haptic feedback corresponding a collision impact with a light mass.
///
/// On iOS versions 10 and above, this uses a `UIImpactFeedbackGenerator` with
/// `UIImpactFeedbackStyleLight`. This call has no effects on iOS versions
/// below 10.
///
/// On Android, this uses `HapticFeedbackConstants.VIRTUAL_KEY`.
static Future<void> lightImpact() async {
await SystemChannels.platform.invokeMethod<void>(
'HapticFeedback.vibrate',
'HapticFeedbackType.lightImpact',
);
}
/// Provides a haptic feedback corresponding a collision impact with a medium mass.
///
/// On iOS versions 10 and above, this uses a `UIImpactFeedbackGenerator` with
/// `UIImpactFeedbackStyleMedium`. This call has no effects on iOS versions
/// below 10.
///
/// On Android, this uses `HapticFeedbackConstants.KEYBOARD_TAP`.
static Future<void> mediumImpact() async {
await SystemChannels.platform.invokeMethod<void>(
'HapticFeedback.vibrate',
'HapticFeedbackType.mediumImpact',
);
}
/// Provides a haptic feedback corresponding a collision impact with a heavy mass.
///
/// On iOS versions 10 and above, this uses a `UIImpactFeedbackGenerator` with
/// `UIImpactFeedbackStyleHeavy`. This call has no effects on iOS versions
/// below 10.
///
/// On Android, this uses `HapticFeedbackConstants.CONTEXT_CLICK` on API levels
/// 23 and above. This call has no effects on Android API levels below 23.
static Future<void> heavyImpact() async {
await SystemChannels.platform.invokeMethod<void>(
'HapticFeedback.vibrate',
'HapticFeedbackType.heavyImpact',
);
}
/// Provides a haptic feedback indication selection changing through discrete values.
///
/// On iOS versions 10 and above, this uses a `UISelectionFeedbackGenerator`.
/// This call has no effects on iOS versions below 10.
///
/// On Android, this uses `HapticFeedbackConstants.CLOCK_TICK`.
static Future<void> selectionClick() async {
await SystemChannels.platform.invokeMethod<void>(
'HapticFeedback.vibrate',
'HapticFeedbackType.selectionClick',
);
}
}
| flutter/packages/flutter/lib/src/services/haptic_feedback.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/haptic_feedback.dart",
"repo_id": "flutter",
"token_count": 920
} | 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 'package:flutter/foundation.dart';
import 'keyboard_maps.g.dart';
import 'raw_keyboard.dart';
export 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder;
export 'keyboard_key.g.dart' show LogicalKeyboardKey, PhysicalKeyboardKey;
/// Platform-specific key event data for iOS.
///
/// This class is deprecated and will be removed. Platform specific key event
/// data will no longer be available. See [KeyEvent] for what is available.
///
/// This object contains information about key events obtained from iOS'
/// `UIKey` interface.
///
/// See also:
///
/// * [RawKeyboard], which uses this interface to expose key data.
@Deprecated(
'Platform specific key event data is no longer available. See KeyEvent for what is available. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
class RawKeyEventDataIos extends RawKeyEventData {
/// Creates a key event data structure specific for iOS.
@Deprecated(
'Platform specific key event data is no longer available. See KeyEvent for what is available. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
const RawKeyEventDataIos({
this.characters = '',
this.charactersIgnoringModifiers = '',
this.keyCode = 0,
this.modifiers = 0,
});
/// The Unicode characters associated with a key-up or key-down event.
///
/// See also:
///
/// * [Apple's UIKey documentation](https://developer.apple.com/documentation/uikit/uikey/3526130-characters?language=objc)
final String characters;
/// The characters generated by a key event as if no modifier key (except for
/// Shift) applies.
///
/// See also:
///
/// * [Apple's UIKey documentation](https://developer.apple.com/documentation/uikit/uikey/3526131-charactersignoringmodifiers?language=objc)
final String charactersIgnoringModifiers;
/// The virtual key code for the keyboard key associated with a key event.
///
/// See also:
///
/// * [Apple's UIKey documentation](https://developer.apple.com/documentation/uikit/uikey/3526132-keycode?language=objc)
final int keyCode;
/// A mask of the current modifiers using the values in Modifier Flags.
///
/// See also:
///
/// * [Apple's UIKey documentation](https://developer.apple.com/documentation/uikit/uikey/3526133-modifierflags?language=objc)
final int modifiers;
@override
String get keyLabel => charactersIgnoringModifiers;
@override
PhysicalKeyboardKey get physicalKey => kIosToPhysicalKey[keyCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.iosPlane + keyCode);
@override
LogicalKeyboardKey get logicalKey {
// Look to see if the keyCode is a printable number pad key, so that a
// difference between regular keys (e.g. "=") and the number pad version
// (e.g. the "=" on the number pad) can be determined.
final LogicalKeyboardKey? numPadKey = kIosNumPadMap[keyCode];
if (numPadKey != null) {
return numPadKey;
}
// Look to see if the [keyLabel] is one we know about and have a mapping for.
final LogicalKeyboardKey? specialKey = kIosSpecialLogicalMap[keyLabel];
if (specialKey != null) {
return specialKey;
}
// Keys that can't be derived with characterIgnoringModifiers will be
// derived from their key codes using this map.
final LogicalKeyboardKey? knownKey = kIosToLogicalKey[keyCode];
if (knownKey != null) {
return knownKey;
}
// If this key is printable, generate the LogicalKeyboardKey from its
// Unicode value. Control keys such as ESC, CTRL, and SHIFT are not
// printable. HOME, DEL, arrow keys, and function keys are considered
// modifier function keys, which generate invalid Unicode scalar values.
if (keyLabel.isNotEmpty &&
!LogicalKeyboardKey.isControlCharacter(keyLabel) &&
!_isUnprintableKey(keyLabel)) {
// Given that charactersIgnoringModifiers can contain a String of
// arbitrary length, limit to a maximum of two Unicode scalar values. It
// is unlikely that a keyboard would produce a code point bigger than 32
// bits, but it is still worth defending against this case.
assert(charactersIgnoringModifiers.length <= 2);
int codeUnit = charactersIgnoringModifiers.codeUnitAt(0);
if (charactersIgnoringModifiers.length == 2) {
final int secondCode = charactersIgnoringModifiers.codeUnitAt(1);
codeUnit = (codeUnit << 16) | secondCode;
}
final int keyId = LogicalKeyboardKey.unicodePlane | (codeUnit & LogicalKeyboardKey.valueMask);
return LogicalKeyboardKey.findKeyByKeyId(keyId) ?? LogicalKeyboardKey(keyId);
}
// This is a non-printable key that we don't know about, so we mint a new
// code.
return LogicalKeyboardKey(keyCode | LogicalKeyboardKey.iosPlane);
}
/// Returns true if the given label represents an unprintable key.
///
/// Examples of unprintable keys are "NSUpArrowFunctionKey = 0xF700"
/// or "NSHomeFunctionKey = 0xF729".
///
/// See <https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?language=objc> for more
/// information.
///
/// Used by [RawKeyEvent] subclasses to help construct IDs.
static bool _isUnprintableKey(String label) {
if (label.length != 1) {
return false;
}
final int codeUnit = label.codeUnitAt(0);
return codeUnit >= 0xF700 && codeUnit <= 0xF8FF;
}
bool _isLeftRightModifierPressed(KeyboardSide side, int anyMask, int leftMask, int rightMask) {
if (modifiers & anyMask == 0) {
return false;
}
if (modifiers & (leftMask | rightMask | anyMask) == anyMask) {
// If only the "anyMask" bit is set, then we respond true for requests of
// whether either left or right is pressed. Handles the case where iOS
// supplies just the "either" modifier flag, but not the left/right flag.
// (e.g. modifierShift but not modifierLeftShift).
return true;
}
return switch (side) {
KeyboardSide.any => true,
KeyboardSide.all => modifiers & leftMask != 0 && modifiers & rightMask != 0,
KeyboardSide.left => modifiers & leftMask != 0,
KeyboardSide.right => modifiers & rightMask != 0,
};
}
@override
bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}) {
final int independentModifier = modifiers & deviceIndependentMask;
bool result;
switch (key) {
case ModifierKey.controlModifier:
result = _isLeftRightModifierPressed(side, independentModifier & modifierControl, modifierLeftControl, modifierRightControl);
case ModifierKey.shiftModifier:
result = _isLeftRightModifierPressed(side, independentModifier & modifierShift, modifierLeftShift, modifierRightShift);
case ModifierKey.altModifier:
result = _isLeftRightModifierPressed(side, independentModifier & modifierOption, modifierLeftOption, modifierRightOption);
case ModifierKey.metaModifier:
result = _isLeftRightModifierPressed(side, independentModifier & modifierCommand, modifierLeftCommand, modifierRightCommand);
case ModifierKey.capsLockModifier:
result = independentModifier & modifierCapsLock != 0;
// On iOS, the function modifier bit is set for any function key, like F1,
// F2, etc., but the meaning of ModifierKey.modifierFunction in Flutter is
// that of the Fn modifier key, so there's no good way to emulate that on
// iOS.
case ModifierKey.functionModifier:
case ModifierKey.numLockModifier:
case ModifierKey.symbolModifier:
case ModifierKey.scrollLockModifier:
// These modifier masks are not used in iOS keyboards.
result = false;
}
assert(!result || getModifierSide(key) != null, "$runtimeType thinks that a modifier is pressed, but can't figure out what side it's on.");
return result;
}
@override
KeyboardSide? getModifierSide(ModifierKey key) {
KeyboardSide? findSide(int anyMask, int leftMask, int rightMask) {
final int combinedMask = leftMask | rightMask;
final int combined = modifiers & combinedMask;
if (combined == leftMask) {
return KeyboardSide.left;
} else if (combined == rightMask) {
return KeyboardSide.right;
} else if (combined == combinedMask || modifiers & (combinedMask | anyMask) == anyMask) {
// Handles the case where iOS supplies just the "either" modifier
// flag, but not the left/right flag. (e.g. modifierShift but not
// modifierLeftShift), or if left and right flags are provided, but not
// the "either" modifier flag.
return KeyboardSide.all;
}
return null;
}
switch (key) {
case ModifierKey.controlModifier:
return findSide(modifierControl, modifierLeftControl, modifierRightControl);
case ModifierKey.shiftModifier:
return findSide(modifierShift, modifierLeftShift, modifierRightShift);
case ModifierKey.altModifier:
return findSide(modifierOption, modifierLeftOption, modifierRightOption);
case ModifierKey.metaModifier:
return findSide(modifierCommand, modifierLeftCommand, modifierRightCommand);
case ModifierKey.capsLockModifier:
case ModifierKey.numLockModifier:
case ModifierKey.scrollLockModifier:
case ModifierKey.functionModifier:
case ModifierKey.symbolModifier:
return KeyboardSide.all;
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<String>('characters', characters));
properties.add(DiagnosticsProperty<String>('charactersIgnoringModifiers', charactersIgnoringModifiers));
properties.add(DiagnosticsProperty<int>('keyCode', keyCode));
properties.add(DiagnosticsProperty<int>('modifiers', modifiers));
}
@override
bool operator==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is RawKeyEventDataIos
&& other.characters == characters
&& other.charactersIgnoringModifiers == charactersIgnoringModifiers
&& other.keyCode == keyCode
&& other.modifiers == modifiers;
}
@override
int get hashCode => Object.hash(
characters,
charactersIgnoringModifiers,
keyCode,
modifiers,
);
// Modifier key masks. See Apple's UIKey documentation
// https://developer.apple.com/documentation/uikit/uikeymodifierflags?language=objc
// https://opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h.auto.html
/// This mask is used to check the [modifiers] field to test whether the CAPS
/// LOCK modifier key is on.
///
/// {@template flutter.services.RawKeyEventDataIos.modifierCapsLock}
/// Use this value if you need to decode the [modifiers] field yourself, but
/// it's much easier to use [isModifierPressed] if you just want to know if
/// a modifier is pressed.
/// {@endtemplate}
static const int modifierCapsLock = 0x10000;
/// This mask is used to check the [modifiers] field to test whether one of the
/// SHIFT modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierShift = 0x20000;
/// This mask is used to check the [modifiers] field to test whether the left
/// SHIFT modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierLeftShift = 0x02;
/// This mask is used to check the [modifiers] field to test whether the right
/// SHIFT modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierRightShift = 0x04;
/// This mask is used to check the [modifiers] field to test whether one of the
/// CTRL modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierControl = 0x40000;
/// This mask is used to check the [modifiers] field to test whether the left
/// CTRL modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierLeftControl = 0x01;
/// This mask is used to check the [modifiers] field to test whether the right
/// CTRL modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierRightControl = 0x2000;
/// This mask is used to check the [modifiers] field to test whether one of the
/// ALT modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierOption = 0x80000;
/// This mask is used to check the [modifiers] field to test whether the left
/// ALT modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierLeftOption = 0x20;
/// This mask is used to check the [modifiers] field to test whether the right
/// ALT modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierRightOption = 0x40;
/// This mask is used to check the [modifiers] field to test whether one of the
/// CMD modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierCommand = 0x100000;
/// This mask is used to check the [modifiers] field to test whether the left
/// CMD modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierLeftCommand = 0x08;
/// This mask is used to check the [modifiers] field to test whether the right
/// CMD modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierRightCommand = 0x10;
/// This mask is used to check the [modifiers] field to test whether any key in
/// the numeric keypad is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierNumericPad = 0x200000;
/// This mask is used to check the [modifiers] field to test whether the
/// HELP modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierHelp = 0x400000;
/// This mask is used to check the [modifiers] field to test whether one of the
/// FUNCTION modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataIos.modifierCapsLock}
static const int modifierFunction = 0x800000;
/// Used to retrieve only the device-independent modifier flags, allowing
/// applications to mask off the device-dependent modifier flags, including
/// event coalescing information.
static const int deviceIndependentMask = 0xffff0000;
}
| flutter/packages/flutter/lib/src/services/raw_keyboard_ios.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/raw_keyboard_ios.dart",
"repo_id": "flutter",
"token_count": 4855
} | 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:io' show Platform;
import 'dart:ui' show
FontWeight,
Offset,
Rect,
Size,
TextAlign,
TextDirection;
import 'package:flutter/foundation.dart';
import 'package:vector_math/vector_math_64.dart' show Matrix4;
import 'autofill.dart';
import 'clipboard.dart' show Clipboard;
import 'keyboard_inserted_content.dart';
import 'message_codec.dart';
import 'platform_channel.dart';
import 'system_channels.dart';
import 'text_editing.dart';
import 'text_editing_delta.dart';
export 'dart:ui' show Brightness, FontWeight, Offset, Rect, Size, TextAlign, TextDirection, TextPosition, TextRange;
export 'package:vector_math/vector_math_64.dart' show Matrix4;
export 'autofill.dart' show AutofillConfiguration, AutofillScope;
export 'text_editing.dart' show TextSelection;
// TODO(a14n): the following export leads to Segmentation fault, see https://github.com/flutter/flutter/issues/106332
// export 'text_editing_delta.dart' show TextEditingDelta;
/// Indicates how to handle the intelligent replacement of dashes in text input.
///
/// See also:
///
/// * [TextField.smartDashesType]
/// * [CupertinoTextField.smartDashesType]
/// * [EditableText.smartDashesType]
/// * [SmartQuotesType]
/// * <https://developer.apple.com/documentation/uikit/uitextinputtraits>
enum SmartDashesType {
/// Smart dashes is disabled.
///
/// This corresponds to the
/// ["no" value of UITextSmartDashesType](https://developer.apple.com/documentation/uikit/uitextsmartdashestype/no).
disabled,
/// Smart dashes is enabled.
///
/// This corresponds to the
/// ["yes" value of UITextSmartDashesType](https://developer.apple.com/documentation/uikit/uitextsmartdashestype/yes).
enabled,
}
/// Indicates how to handle the intelligent replacement of quotes in text input.
///
/// See also:
///
/// * [TextField.smartQuotesType]
/// * [CupertinoTextField.smartQuotesType]
/// * [EditableText.smartQuotesType]
/// * <https://developer.apple.com/documentation/uikit/uitextinputtraits>
enum SmartQuotesType {
/// Smart quotes is disabled.
///
/// This corresponds to the
/// ["no" value of UITextSmartQuotesType](https://developer.apple.com/documentation/uikit/uitextsmartquotestype/no).
disabled,
/// Smart quotes is enabled.
///
/// This corresponds to the
/// ["yes" value of UITextSmartQuotesType](https://developer.apple.com/documentation/uikit/uitextsmartquotestype/yes).
enabled,
}
/// The type of information for which to optimize the text input control.
///
/// On Android, behavior may vary across device and keyboard provider.
///
/// This class stays as close to `Enum` interface as possible, and allows
/// for additional flags for some input types. For example, numeric input
/// can specify whether it supports decimal numbers and/or signed numbers.
@immutable
class TextInputType {
const TextInputType._(this.index)
: signed = null,
decimal = null;
/// Optimize for numerical information.
///
/// Requests a numeric keyboard with additional settings.
/// The [signed] and [decimal] parameters are optional.
const TextInputType.numberWithOptions({
this.signed = false,
this.decimal = false,
}) : index = 2;
/// Enum value index, corresponds to one of the [values].
final int index;
/// The number is signed, allowing a positive or negative sign at the start.
///
/// This flag is only used for the [number] input type, otherwise `null`.
/// Use `const TextInputType.numberWithOptions(signed: true)` to set this.
final bool? signed;
/// The number is decimal, allowing a decimal point to provide fractional.
///
/// This flag is only used for the [number] input type, otherwise `null`.
/// Use `const TextInputType.numberWithOptions(decimal: true)` to set this.
final bool? decimal;
/// Optimize for textual information.
///
/// Requests the default platform keyboard.
static const TextInputType text = TextInputType._(0);
/// Optimize for multiline textual information.
///
/// Requests the default platform keyboard, but accepts newlines when the
/// enter key is pressed. This is the input type used for all multiline text
/// fields.
static const TextInputType multiline = TextInputType._(1);
/// Optimize for unsigned numerical information without a decimal point.
///
/// Requests a default keyboard with ready access to the number keys.
/// Additional options, such as decimal point and/or positive/negative
/// signs, can be requested using [TextInputType.numberWithOptions].
static const TextInputType number = TextInputType.numberWithOptions();
/// Optimize for telephone numbers.
///
/// Requests a keyboard with ready access to the number keys, "*", and "#".
static const TextInputType phone = TextInputType._(3);
/// Optimize for date and time information.
///
/// On iOS, requests the default keyboard.
///
/// On Android, requests a keyboard with ready access to the number keys,
/// ":", and "-".
static const TextInputType datetime = TextInputType._(4);
/// Optimize for email addresses.
///
/// Requests a keyboard with ready access to the "@" and "." keys.
static const TextInputType emailAddress = TextInputType._(5);
/// Optimize for URLs.
///
/// Requests a keyboard with ready access to the "/" and "." keys.
static const TextInputType url = TextInputType._(6);
/// Optimize for passwords that are visible to the user.
///
/// Requests a keyboard with ready access to both letters and numbers.
static const TextInputType visiblePassword = TextInputType._(7);
/// Optimized for a person's name.
///
/// On iOS, requests the
/// [UIKeyboardType.namePhonePad](https://developer.apple.com/documentation/uikit/uikeyboardtype/namephonepad)
/// keyboard, a keyboard optimized for entering a person’s name or phone number.
/// Does not support auto-capitalization.
///
/// On Android, requests a keyboard optimized for
/// [TYPE_TEXT_VARIATION_PERSON_NAME](https://developer.android.com/reference/android/text/InputType#TYPE_TEXT_VARIATION_PERSON_NAME).
static const TextInputType name = TextInputType._(8);
/// Optimized for postal mailing addresses.
///
/// On iOS, requests the default keyboard.
///
/// On Android, requests a keyboard optimized for
/// [TYPE_TEXT_VARIATION_POSTAL_ADDRESS](https://developer.android.com/reference/android/text/InputType#TYPE_TEXT_VARIATION_POSTAL_ADDRESS).
static const TextInputType streetAddress = TextInputType._(9);
/// Prevent the OS from showing the on-screen virtual keyboard.
static const TextInputType none = TextInputType._(10);
/// All possible enum values.
static const List<TextInputType> values = <TextInputType>[
text, multiline, number, phone, datetime, emailAddress, url, visiblePassword, name, streetAddress, none,
];
// Corresponding string name for each of the [values].
static const List<String> _names = <String>[
'text', 'multiline', 'number', 'phone', 'datetime', 'emailAddress', 'url', 'visiblePassword', 'name', 'address', 'none',
];
// Enum value name, this is what enum.toString() would normally return.
String get _name => 'TextInputType.${_names[index]}';
/// Returns a representation of this object as a JSON object.
Map<String, dynamic> toJson() {
return <String, dynamic>{
'name': _name,
'signed': signed,
'decimal': decimal,
};
}
@override
String toString() {
return '${objectRuntimeType(this, 'TextInputType')}('
'name: $_name, '
'signed: $signed, '
'decimal: $decimal)';
}
@override
bool operator ==(Object other) {
return other is TextInputType
&& other.index == index
&& other.signed == signed
&& other.decimal == decimal;
}
@override
int get hashCode => Object.hash(index, signed, decimal);
}
/// An action the user has requested the text input control to perform.
///
/// Each action represents a logical meaning, and also configures the soft
/// keyboard to display a certain kind of action button. The visual appearance
/// of the action button might differ between versions of the same OS.
///
/// Despite the logical meaning of each action, choosing a particular
/// [TextInputAction] does not necessarily cause any specific behavior to
/// happen, other than changing the focus when appropriate. It is up to the
/// developer to ensure that the behavior that occurs when an action button is
/// pressed is appropriate for the action button chosen.
///
/// For example: If the user presses the keyboard action button on iOS when it
/// reads "Emergency Call", the result should not be a focus change to the next
/// TextField. This behavior is not logically appropriate for a button that says
/// "Emergency Call".
///
/// See [EditableText] for more information about customizing action button
/// behavior.
///
/// Most [TextInputAction]s are supported equally by both Android and iOS.
/// However, there is not a complete, direct mapping between Android's IME input
/// types and iOS's keyboard return types. Therefore, some [TextInputAction]s
/// are inappropriate for one of the platforms. If a developer chooses an
/// inappropriate [TextInputAction] when running in debug mode, an error will be
/// thrown. If the same thing is done in release mode, then instead of sending
/// the inappropriate value, Android will use "unspecified" on the platform
/// side and iOS will use "default" on the platform side.
///
/// See also:
///
/// * [TextInput], which configures the platform's keyboard setup.
/// * [EditableText], which invokes callbacks when the action button is pressed.
//
// This class has been cloned to `flutter_driver/lib/src/common/action.dart` as `TextInputAction`,
// and must be kept in sync.
enum TextInputAction {
/// Logical meaning: There is no relevant input action for the current input
/// source, e.g., [TextField].
///
/// Android: Corresponds to Android's "IME_ACTION_NONE". The keyboard setup
/// is decided by the OS. The keyboard will likely show a return key.
///
/// iOS: iOS does not have a keyboard return type of "none." It is
/// inappropriate to choose this [TextInputAction] when running on iOS.
none,
/// Logical meaning: Let the OS decide which action is most appropriate.
///
/// Android: Corresponds to Android's "IME_ACTION_UNSPECIFIED". The OS chooses
/// which keyboard action to display. The decision will likely be a done
/// button or a return key.
///
/// iOS: Corresponds to iOS's "UIReturnKeyDefault". The title displayed in
/// the action button is "return".
unspecified,
/// Logical meaning: The user is done providing input to a group of inputs
/// (like a form). Some kind of finalization behavior should now take place.
///
/// Android: Corresponds to Android's "IME_ACTION_DONE". The OS displays a
/// button that represents completion, e.g., a checkmark button.
///
/// iOS: Corresponds to iOS's "UIReturnKeyDone". The title displayed in the
/// action button is "Done".
done,
/// Logical meaning: The user has entered some text that represents a
/// destination, e.g., a restaurant name. The "go" button is intended to take
/// the user to a part of the app that corresponds to this destination.
///
/// Android: Corresponds to Android's "IME_ACTION_GO". The OS displays a
/// button that represents taking "the user to the target of the text they
/// typed", e.g., a right-facing arrow button.
///
/// iOS: Corresponds to iOS's "UIReturnKeyGo". The title displayed in the
/// action button is "Go".
go,
/// Logical meaning: Execute a search query.
///
/// Android: Corresponds to Android's "IME_ACTION_SEARCH". The OS displays a
/// button that represents a search, e.g., a magnifying glass button.
///
/// iOS: Corresponds to iOS's "UIReturnKeySearch". The title displayed in the
/// action button is "Search".
search,
/// Logical meaning: Sends something that the user has composed, e.g., an
/// email or a text message.
///
/// Android: Corresponds to Android's "IME_ACTION_SEND". The OS displays a
/// button that represents sending something, e.g., a paper plane button.
///
/// iOS: Corresponds to iOS's "UIReturnKeySend". The title displayed in the
/// action button is "Send".
send,
/// Logical meaning: The user is done with the current input source and wants
/// to move to the next one.
///
/// Moves the focus to the next focusable item in the same [FocusScope].
///
/// Android: Corresponds to Android's "IME_ACTION_NEXT". The OS displays a
/// button that represents moving forward, e.g., a right-facing arrow button.
///
/// iOS: Corresponds to iOS's "UIReturnKeyNext". The title displayed in the
/// action button is "Next".
next,
/// Logical meaning: The user wishes to return to the previous input source
/// in the group, e.g., a form with multiple [TextField]s.
///
/// Moves the focus to the previous focusable item in the same [FocusScope].
///
/// Android: Corresponds to Android's "IME_ACTION_PREVIOUS". The OS displays a
/// button that represents moving backward, e.g., a left-facing arrow button.
///
/// iOS: iOS does not have a keyboard return type of "previous." It is
/// inappropriate to choose this [TextInputAction] when running on iOS.
previous,
/// Logical meaning: In iOS apps, it is common for a "Back" button and
/// "Continue" button to appear at the top of the screen. However, when the
/// keyboard is open, these buttons are often hidden off-screen. Therefore,
/// the purpose of the "Continue" return key on iOS is to make the "Continue"
/// button available when the user is entering text.
///
/// Historical context aside, [TextInputAction.continueAction] can be used any
/// time that the term "Continue" seems most appropriate for the given action.
///
/// Android: Android does not have an IME input type of "continue." It is
/// inappropriate to choose this [TextInputAction] when running on Android.
///
/// iOS: Corresponds to iOS's "UIReturnKeyContinue". The title displayed in the
/// action button is "Continue". This action is only available on iOS 9.0+.
///
/// The reason that this value has "Action" post-fixed to it is because
/// "continue" is a reserved word in Dart, as well as many other languages.
continueAction,
/// Logical meaning: The user wants to join something, e.g., a wireless
/// network.
///
/// Android: Android does not have an IME input type of "join." It is
/// inappropriate to choose this [TextInputAction] when running on Android.
///
/// iOS: Corresponds to iOS's "UIReturnKeyJoin". The title displayed in the
/// action button is "Join".
join,
/// Logical meaning: The user wants routing options, e.g., driving directions.
///
/// Android: Android does not have an IME input type of "route." It is
/// inappropriate to choose this [TextInputAction] when running on Android.
///
/// iOS: Corresponds to iOS's "UIReturnKeyRoute". The title displayed in the
/// action button is "Route".
route,
/// Logical meaning: Initiate a call to emergency services.
///
/// Android: Android does not have an IME input type of "emergencyCall." It is
/// inappropriate to choose this [TextInputAction] when running on Android.
///
/// iOS: Corresponds to iOS's "UIReturnKeyEmergencyCall". The title displayed
/// in the action button is "Emergency Call".
emergencyCall,
/// Logical meaning: Insert a newline character in the focused text input,
/// e.g., [TextField].
///
/// Android: Corresponds to Android's "IME_ACTION_NONE". The OS displays a
/// button that represents a new line, e.g., a carriage return button.
///
/// iOS: Corresponds to iOS's "UIReturnKeyDefault". The title displayed in the
/// action button is "return".
///
/// The term [TextInputAction.newline] exists in Flutter but not in Android
/// or iOS. The reason for introducing this term is so that developers can
/// achieve the common result of inserting new lines without needing to
/// understand the various IME actions on Android and return keys on iOS.
/// Thus, [TextInputAction.newline] is a convenience term that alleviates the
/// need to understand the underlying platforms to achieve this common behavior.
newline,
}
/// Configures how the platform keyboard will select an uppercase or
/// lowercase keyboard.
///
/// Only supports text keyboards, other keyboard types will ignore this
/// configuration. Capitalization is locale-aware.
enum TextCapitalization {
/// Defaults to an uppercase keyboard for the first letter of each word.
///
/// Corresponds to `InputType.TYPE_TEXT_FLAG_CAP_WORDS` on Android, and
/// `UITextAutocapitalizationTypeWords` on iOS.
words,
/// Defaults to an uppercase keyboard for the first letter of each sentence.
///
/// Corresponds to `InputType.TYPE_TEXT_FLAG_CAP_SENTENCES` on Android, and
/// `UITextAutocapitalizationTypeSentences` on iOS.
sentences,
/// Defaults to an uppercase keyboard for each character.
///
/// Corresponds to `InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS` on Android, and
/// `UITextAutocapitalizationTypeAllCharacters` on iOS.
characters,
/// Defaults to a lowercase keyboard.
none,
}
/// Controls the visual appearance of the text input control.
///
/// Many [TextInputAction]s are common between Android and iOS. However, if an
/// [inputAction] is provided that is not supported by the current
/// platform in debug mode, an error will be thrown when the corresponding
/// text input is attached. For example, providing iOS's "emergencyCall"
/// action when running on an Android device will result in an error when in
/// debug mode. In release mode, incompatible [TextInputAction]s are replaced
/// either with "unspecified" on Android, or "default" on iOS. Appropriate
/// [inputAction]s can be chosen by checking the current platform and then
/// selecting the appropriate action.
///
/// See also:
///
/// * [TextInput.attach]
/// * [TextInputAction]
@immutable
class TextInputConfiguration {
/// Creates configuration information for a text input control.
///
/// All arguments have default values, except [actionLabel]. Only
/// [actionLabel] may be null.
const TextInputConfiguration({
this.inputType = TextInputType.text,
this.readOnly = false,
this.obscureText = false,
this.autocorrect = true,
SmartDashesType? smartDashesType,
SmartQuotesType? smartQuotesType,
this.enableSuggestions = true,
this.enableInteractiveSelection = true,
this.actionLabel,
this.inputAction = TextInputAction.done,
this.keyboardAppearance = Brightness.light,
this.textCapitalization = TextCapitalization.none,
this.autofillConfiguration = AutofillConfiguration.disabled,
this.enableIMEPersonalizedLearning = true,
this.allowedMimeTypes = const <String>[],
this.enableDeltaModel = false,
}) : smartDashesType = smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled),
smartQuotesType = smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled);
/// The type of information for which to optimize the text input control.
final TextInputType inputType;
/// Whether the text field can be edited or not.
///
/// Defaults to false.
final bool readOnly;
/// Whether to hide the text being edited (e.g., for passwords).
///
/// Defaults to false.
final bool obscureText;
/// Whether to enable autocorrection.
///
/// Defaults to true.
final bool autocorrect;
/// The configuration to use for autofill.
///
/// Defaults to null, in which case no autofill information will be provided
/// to the platform. This will prevent the corresponding input field from
/// participating in autofills triggered by other fields. Additionally, on
/// Android and web, setting [autofillConfiguration] to null disables autofill.
final AutofillConfiguration autofillConfiguration;
/// {@template flutter.services.TextInputConfiguration.smartDashesType}
/// Whether to allow the platform to automatically format dashes.
///
/// This flag only affects iOS versions 11 and above. It sets
/// [`UITextSmartDashesType`](https://developer.apple.com/documentation/uikit/uitextsmartdashestype?language=objc)
/// in the engine. When true, it passes
/// [`UITextSmartDashesTypeYes`](https://developer.apple.com/documentation/uikit/uitextsmartdashestype/uitextsmartdashestypeyes?language=objc),
/// and when false, it passes
/// [`UITextSmartDashesTypeNo`](https://developer.apple.com/documentation/uikit/uitextsmartdashestype/uitextsmartdashestypeno?language=objc).
///
/// As an example of what this does, two consecutive hyphen characters will be
/// automatically replaced with one en dash, and three consecutive hyphens
/// will become one em dash.
///
/// Defaults to true, unless [obscureText] is true, when it defaults to false.
/// This is to avoid the problem where password fields receive autoformatted
/// characters.
///
/// See also:
///
/// * [smartQuotesType]
/// * <https://developer.apple.com/documentation/uikit/uitextinputtraits>
/// {@endtemplate}
final SmartDashesType smartDashesType;
/// {@template flutter.services.TextInputConfiguration.smartQuotesType}
/// Whether to allow the platform to automatically format quotes.
///
/// This flag only affects iOS. It sets
/// [`UITextSmartQuotesType`](https://developer.apple.com/documentation/uikit/uitextsmartquotestype?language=objc)
/// in the engine. When true, it passes
/// [`UITextSmartQuotesTypeYes`](https://developer.apple.com/documentation/uikit/uitextsmartquotestype/uitextsmartquotestypeyes?language=objc),
/// and when false, it passes
/// [`UITextSmartQuotesTypeNo`](https://developer.apple.com/documentation/uikit/uitextsmartquotestype/uitextsmartquotestypeno?language=objc).
///
/// As an example of what this does, a standard vertical double quote
/// character will be automatically replaced by a left or right double quote
/// depending on its position in a word.
///
/// Defaults to true, unless [obscureText] is true, when it defaults to false.
/// This is to avoid the problem where password fields receive autoformatted
/// characters.
///
/// See also:
///
/// * [smartDashesType]
/// * <https://developer.apple.com/documentation/uikit/uitextinputtraits>
/// {@endtemplate}
final SmartQuotesType smartQuotesType;
/// {@template flutter.services.TextInputConfiguration.enableSuggestions}
/// Whether to show input suggestions as the user types.
///
/// This flag only affects Android. On iOS, suggestions are tied directly to
/// [autocorrect], so that suggestions are only shown when [autocorrect] is
/// true. On Android autocorrection and suggestion are controlled separately.
///
/// Defaults to true.
///
/// See also:
///
/// * <https://developer.android.com/reference/android/text/InputType.html#TYPE_TEXT_FLAG_NO_SUGGESTIONS>
/// {@endtemplate}
final bool enableSuggestions;
/// Whether a user can change its selection.
///
/// This flag only affects iOS VoiceOver. On Android Talkback, the selection
/// change is sent through semantics actions and is directly disabled from
/// the widget side.
///
/// Defaults to true.
final bool enableInteractiveSelection;
/// What text to display in the text input control's action button.
final String? actionLabel;
/// What kind of action to request for the action button on the IME.
final TextInputAction inputAction;
/// Specifies how platforms may automatically capitalize text entered by the
/// user.
///
/// Defaults to [TextCapitalization.none].
///
/// See also:
///
/// * [TextCapitalization], for a description of each capitalization behavior.
final TextCapitalization textCapitalization;
/// The appearance of the keyboard.
///
/// This setting is only honored on iOS devices.
///
/// Defaults to [Brightness.light].
final Brightness keyboardAppearance;
/// {@template flutter.services.TextInputConfiguration.enableIMEPersonalizedLearning}
/// Whether to enable that the IME update personalized data such as typing
/// history and user dictionary data.
///
/// This flag only affects Android. On iOS, there is no equivalent flag.
///
/// Defaults to true.
///
/// See also:
///
/// * <https://developer.android.com/reference/android/view/inputmethod/EditorInfo#IME_FLAG_NO_PERSONALIZED_LEARNING>
/// {@endtemplate}
final bool enableIMEPersonalizedLearning;
/// {@macro flutter.widgets.contentInsertionConfiguration.allowedMimeTypes}
final List<String> allowedMimeTypes;
/// Creates a copy of this [TextInputConfiguration] with the given fields
/// replaced with new values.
TextInputConfiguration copyWith({
TextInputType? inputType,
bool? readOnly,
bool? obscureText,
bool? autocorrect,
SmartDashesType? smartDashesType,
SmartQuotesType? smartQuotesType,
bool? enableSuggestions,
bool? enableInteractiveSelection,
String? actionLabel,
TextInputAction? inputAction,
Brightness? keyboardAppearance,
TextCapitalization? textCapitalization,
bool? enableIMEPersonalizedLearning,
List<String>? allowedMimeTypes,
AutofillConfiguration? autofillConfiguration,
bool? enableDeltaModel,
}) {
return TextInputConfiguration(
inputType: inputType ?? this.inputType,
readOnly: readOnly ?? this.readOnly,
obscureText: obscureText ?? this.obscureText,
autocorrect: autocorrect ?? this.autocorrect,
smartDashesType: smartDashesType ?? this.smartDashesType,
smartQuotesType: smartQuotesType ?? this.smartQuotesType,
enableSuggestions: enableSuggestions ?? this.enableSuggestions,
enableInteractiveSelection: enableInteractiveSelection ?? this.enableInteractiveSelection,
inputAction: inputAction ?? this.inputAction,
textCapitalization: textCapitalization ?? this.textCapitalization,
keyboardAppearance: keyboardAppearance ?? this.keyboardAppearance,
enableIMEPersonalizedLearning: enableIMEPersonalizedLearning?? this.enableIMEPersonalizedLearning,
allowedMimeTypes: allowedMimeTypes ?? this.allowedMimeTypes,
autofillConfiguration: autofillConfiguration ?? this.autofillConfiguration,
enableDeltaModel: enableDeltaModel ?? this.enableDeltaModel,
);
}
/// Whether to enable that the engine sends text input updates to the
/// framework as [TextEditingDelta]'s or as one [TextEditingValue].
///
/// Enabling this flag results in granular text updates being received from the
/// platform's text input control.
///
/// When this is enabled:
/// * You must implement [DeltaTextInputClient] and not [TextInputClient] to
/// receive granular updates from the platform's text input.
/// * Platform text input updates will come through
/// [DeltaTextInputClient.updateEditingValueWithDeltas].
/// * If [TextInputClient] is implemented with this property enabled then
/// you will experience unexpected behavior as [TextInputClient] does not implement
/// a delta channel.
///
/// When this is disabled:
/// * If [DeltaTextInputClient] is implemented then updates for the
/// editing state will continue to come through the
/// [DeltaTextInputClient.updateEditingValue] channel.
/// * If [TextInputClient] is implemented then updates for the editing
/// state will come through [TextInputClient.updateEditingValue].
///
/// Defaults to false.
final bool enableDeltaModel;
/// Returns a representation of this object as a JSON object.
Map<String, dynamic> toJson() {
final Map<String, dynamic>? autofill = autofillConfiguration.toJson();
return <String, dynamic>{
'inputType': inputType.toJson(),
'readOnly': readOnly,
'obscureText': obscureText,
'autocorrect': autocorrect,
'smartDashesType': smartDashesType.index.toString(),
'smartQuotesType': smartQuotesType.index.toString(),
'enableSuggestions': enableSuggestions,
'enableInteractiveSelection': enableInteractiveSelection,
'actionLabel': actionLabel,
'inputAction': inputAction.toString(),
'textCapitalization': textCapitalization.toString(),
'keyboardAppearance': keyboardAppearance.toString(),
'enableIMEPersonalizedLearning': enableIMEPersonalizedLearning,
'contentCommitMimeTypes': allowedMimeTypes,
if (autofill != null) 'autofill': autofill,
'enableDeltaModel' : enableDeltaModel,
};
}
}
TextAffinity? _toTextAffinity(String? affinity) {
return switch (affinity) {
'TextAffinity.downstream' => TextAffinity.downstream,
'TextAffinity.upstream' => TextAffinity.upstream,
_ => null,
};
}
/// The state of a "floating cursor" drag on an iOS soft keyboard.
///
/// The "floating cursor" cursor-positioning mode is an iOS feature used to
/// precisely position the caret in some editable text using certain touch
/// gestures. As an example, when the user long-presses the spacebar on the iOS
/// virtual keyboard, iOS enters floating cursor mode where the whole keyboard
/// becomes a trackpad. In this mode, there are two visible cursors. One, the
/// floating cursor, hovers over the text, following the user's horizontal
/// movements exactly and snapping to lines vertically. The other, the
/// placeholder cursor, is a "shadow" that also snaps to the actual location
/// where the cursor will go horizontally when the user releases the trackpad.
///
/// The floating cursor renders over the text field, while the placeholder
/// cursor is a faint shadow of the cursor rendered in the text field in the
/// location between characters where the cursor will drop into when released.
/// The placeholder cursor is a faint vertical bar, while the floating cursor
/// has the same appearance as a normal cursor (a blue vertical bar).
///
/// This feature works out-of-the-box with Flutter. Support is built into
/// [EditableText].
///
/// See also:
///
/// * [EditableText.backgroundCursorColor], which configures the color of the
/// placeholder cursor while the floating cursor is being dragged.
enum FloatingCursorDragState {
/// A user has just activated a floating cursor by long pressing on the
/// spacebar.
Start,
/// A user is dragging a floating cursor.
Update,
/// A user has lifted their finger off the screen after using a floating
/// cursor.
End,
}
/// The current state and position of the floating cursor.
///
/// See also:
///
/// * [FloatingCursorDragState], which explains the floating cursor feature in
/// detail.
class RawFloatingCursorPoint {
/// Creates information for setting the position and state of a floating
/// cursor.
///
/// [state] must not be null and [offset] must not be null if the state is
/// [FloatingCursorDragState.Update].
RawFloatingCursorPoint({
this.offset,
this.startLocation,
required this.state,
}) : assert(state != FloatingCursorDragState.Update || offset != null);
/// The raw position of the floating cursor as determined by the iOS sdk.
final Offset? offset;
/// Represents the starting location when initiating a floating cursor via long press.
/// This is a tuple where the first item is the local offset and the second item is the new caret position.
/// This is only non-null when a floating cursor is started.
final (Offset, TextPosition)? startLocation;
/// The state of the floating cursor.
final FloatingCursorDragState state;
}
/// The current text, selection, and composing state for editing a run of text.
@immutable
class TextEditingValue {
/// Creates information for editing a run of text.
///
/// The selection and composing range must be within the text. This is not
/// checked during construction, and must be guaranteed by the caller.
///
/// The default value of [selection] is `TextSelection.collapsed(offset: -1)`.
/// This indicates that there is no selection at all.
const TextEditingValue({
this.text = '',
this.selection = const TextSelection.collapsed(offset: -1),
this.composing = TextRange.empty,
});
/// Creates an instance of this class from a JSON object.
factory TextEditingValue.fromJSON(Map<String, dynamic> encoded) {
final String text = encoded['text'] as String;
final TextSelection selection = TextSelection(
baseOffset: encoded['selectionBase'] as int? ?? -1,
extentOffset: encoded['selectionExtent'] as int? ?? -1,
affinity: _toTextAffinity(encoded['selectionAffinity'] as String?) ?? TextAffinity.downstream,
isDirectional: encoded['selectionIsDirectional'] as bool? ?? false,
);
final TextRange composing = TextRange(
start: encoded['composingBase'] as int? ?? -1,
end: encoded['composingExtent'] as int? ?? -1,
);
assert(_textRangeIsValid(selection, text));
assert(_textRangeIsValid(composing, text));
return TextEditingValue(
text: text,
selection: selection,
composing: composing,
);
}
/// The current text being edited.
final String text;
/// The range of text that is currently selected.
///
/// When [selection] is a [TextSelection] that has the same non-negative
/// `baseOffset` and `extentOffset`, the [selection] property represents the
/// caret position.
///
/// If the current [selection] has a negative `baseOffset` or `extentOffset`,
/// then the text currently does not have a selection or a caret location, and
/// most text editing operations that rely on the current selection (for
/// instance, insert a character at the caret location) will do nothing.
final TextSelection selection;
/// The range of text that is still being composed.
///
/// Composing regions are created by input methods (IMEs) to indicate the text
/// within a certain range is provisional. For instance, the Android Gboard
/// app's English keyboard puts the current word under the caret into a
/// composing region to indicate the word is subject to autocorrect or
/// prediction changes.
///
/// Composing regions can also be used for performing multistage input, which
/// is typically used by IMEs designed for phonetic keyboard to enter
/// ideographic symbols. As an example, many CJK keyboards require the user to
/// enter a Latin alphabet sequence and then convert it to CJK characters. On
/// iOS, the default software keyboards do not have a dedicated view to show
/// the unfinished Latin sequence, so it's displayed directly in the text
/// field, inside of a composing region.
///
/// The composing region should typically only be changed by the IME, or the
/// user via interacting with the IME.
///
/// If the range represented by this property is [TextRange.empty], then the
/// text is not currently being composed.
final TextRange composing;
/// A value that corresponds to the empty string with no selection and no composing range.
static const TextEditingValue empty = TextEditingValue();
/// Creates a copy of this value but with the given fields replaced with the new values.
TextEditingValue copyWith({
String? text,
TextSelection? selection,
TextRange? composing,
}) {
return TextEditingValue(
text: text ?? this.text,
selection: selection ?? this.selection,
composing: composing ?? this.composing,
);
}
/// Whether the [composing] range is a valid range within [text].
///
/// Returns true if and only if the [composing] range is normalized, its start
/// is greater than or equal to 0, and its end is less than or equal to
/// [text]'s length.
///
/// If this property is false while the [composing] range's `isValid` is true,
/// it usually indicates the current [composing] range is invalid because of a
/// programming error.
bool get isComposingRangeValid => composing.isValid && composing.isNormalized && composing.end <= text.length;
/// Returns a new [TextEditingValue], which is this [TextEditingValue] with
/// its [text] partially replaced by the `replacementString`.
///
/// The `replacementRange` parameter specifies the range of the
/// [TextEditingValue.text] that needs to be replaced.
///
/// The `replacementString` parameter specifies the string to replace the
/// given range of text with.
///
/// This method also adjusts the selection range and the composing range of the
/// resulting [TextEditingValue], such that they point to the same substrings
/// as the corresponding ranges in the original [TextEditingValue]. For
/// example, if the original [TextEditingValue] is "Hello world" with the word
/// "world" selected, replacing "Hello" with a different string using this
/// method will not change the selected word.
///
/// This method does nothing if the given `replacementRange` is not
/// [TextRange.isValid].
TextEditingValue replaced(TextRange replacementRange, String replacementString) {
if (!replacementRange.isValid) {
return this;
}
final String newText = text.replaceRange(replacementRange.start, replacementRange.end, replacementString);
if (replacementRange.end - replacementRange.start == replacementString.length) {
return copyWith(text: newText);
}
int adjustIndex(int originalIndex) {
// The length added by adding the replacementString.
final int replacedLength = originalIndex <= replacementRange.start && originalIndex < replacementRange.end ? 0 : replacementString.length;
// The length removed by removing the replacementRange.
final int removedLength = originalIndex.clamp(replacementRange.start, replacementRange.end) - replacementRange.start;
return originalIndex + replacedLength - removedLength;
}
final TextSelection adjustedSelection = TextSelection(
baseOffset: adjustIndex(selection.baseOffset),
extentOffset: adjustIndex(selection.extentOffset),
);
final TextRange adjustedComposing = TextRange(
start: adjustIndex(composing.start),
end: adjustIndex(composing.end),
);
assert(_textRangeIsValid(adjustedSelection, newText));
assert(_textRangeIsValid(adjustedComposing, newText));
return TextEditingValue(
text: newText,
selection: adjustedSelection,
composing: adjustedComposing,
);
}
/// Returns a representation of this object as a JSON object.
Map<String, dynamic> toJSON() {
assert(_textRangeIsValid(selection, text));
assert(_textRangeIsValid(composing, text));
return <String, dynamic>{
'text': text,
'selectionBase': selection.baseOffset,
'selectionExtent': selection.extentOffset,
'selectionAffinity': selection.affinity.toString(),
'selectionIsDirectional': selection.isDirectional,
'composingBase': composing.start,
'composingExtent': composing.end,
};
}
@override
String toString() => '${objectRuntimeType(this, 'TextEditingValue')}(text: \u2524$text\u251C, selection: $selection, composing: $composing)';
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is TextEditingValue
&& other.text == text
&& other.selection == selection
&& other.composing == composing;
}
@override
int get hashCode => Object.hash(
text.hashCode,
selection.hashCode,
composing.hashCode,
);
// Verify that the given range is within the text.
//
// The verification can't be perform during the constructor of
// [TextEditingValue], which are `const` and are allowed to retrieve
// properties of [TextRange]s. [TextEditingValue] should perform this
// wherever it is building other values (such as toJson) or is built in a
// non-const way (such as fromJson).
static bool _textRangeIsValid(TextRange range, String text) {
if (range.start == -1 && range.end == -1) {
return true;
}
assert(range.start >= 0 && range.start <= text.length,
'Range start ${range.start} is out of text of length ${text.length}');
assert(range.end >= 0 && range.end <= text.length,
'Range end ${range.end} is out of text of length ${text.length}');
return true;
}
}
/// Indicates what triggered the change in selected text (including changes to
/// the cursor location).
enum SelectionChangedCause {
/// The user tapped on the text and that caused the selection (or the location
/// of the cursor) to change.
tap,
/// The user tapped twice in quick succession on the text and that caused
/// the selection (or the location of the cursor) to change.
doubleTap,
/// The user long-pressed the text and that caused the selection (or the
/// location of the cursor) to change.
longPress,
/// The user force-pressed the text and that caused the selection (or the
/// location of the cursor) to change.
forcePress,
/// The user used the keyboard to change the selection or the location of the
/// cursor.
///
/// Keyboard-triggered selection changes may be caused by the IME as well as
/// by accessibility tools (e.g. TalkBack on Android).
keyboard,
/// The user used the selection toolbar to change the selection or the
/// location of the cursor.
///
/// An example is when the user taps on select all in the tool bar.
toolbar,
/// The user used the mouse to change the selection by dragging over a piece
/// of text.
drag,
/// The user used iPadOS 14+ Scribble to change the selection.
scribble,
}
/// A mixin for manipulating the selection, provided for toolbar or shortcut
/// keys.
mixin TextSelectionDelegate {
/// Gets the current text input.
TextEditingValue get textEditingValue;
/// Indicates that the user has requested the delegate to replace its current
/// text editing state with [value].
///
/// The new [value] is treated as user input and thus may subject to input
/// formatting.
///
/// See also:
///
/// * [EditableTextState.userUpdateTextEditingValue]: an implementation that
/// applies additional pre-processing to the specified [value], before
/// updating the text editing state.
void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause cause);
/// Hides the text selection toolbar.
///
/// By default, hideHandles is true, and the toolbar is hidden along with its
/// handles. If hideHandles is set to false, then the toolbar will be hidden
/// but the handles will remain.
void hideToolbar([bool hideHandles = true]);
/// Brings the provided [TextPosition] into the visible area of the text
/// input.
void bringIntoView(TextPosition position);
/// Whether cut is enabled.
bool get cutEnabled => true;
/// Whether copy is enabled.
bool get copyEnabled => true;
/// Whether paste is enabled.
bool get pasteEnabled => true;
/// Whether select all is enabled.
bool get selectAllEnabled => true;
/// Whether look up is enabled.
bool get lookUpEnabled => true;
/// Whether search web is enabled.
bool get searchWebEnabled => true;
/// Whether share is enabled.
bool get shareEnabled => true;
/// Whether Live Text input is enabled.
///
/// See also:
/// * [LiveText], where the availability of Live Text input can be obtained.
/// * [LiveTextInputStatusNotifier], where the status of Live Text can be listened to.
bool get liveTextInputEnabled => false;
/// Cut current selection to [Clipboard].
///
/// If and only if [cause] is [SelectionChangedCause.toolbar], the toolbar
/// will be hidden and the current selection will be scrolled into view.
void cutSelection(SelectionChangedCause cause);
/// Paste text from [Clipboard].
///
/// If there is currently a selection, it will be replaced.
///
/// If and only if [cause] is [SelectionChangedCause.toolbar], the toolbar
/// will be hidden and the current selection will be scrolled into view.
Future<void> pasteText(SelectionChangedCause cause);
/// Set the current selection to contain the entire text value.
///
/// If and only if [cause] is [SelectionChangedCause.toolbar], the selection
/// will be scrolled into view.
void selectAll(SelectionChangedCause cause);
/// Copy current selection to [Clipboard].
///
/// If [cause] is [SelectionChangedCause.toolbar], the position of
/// [bringIntoView] to selection will be called and hide toolbar.
void copySelection(SelectionChangedCause cause);
}
/// An interface to receive information from [TextInput].
///
/// If [TextInputConfiguration.enableDeltaModel] is set to true,
/// [DeltaTextInputClient] must be implemented instead of this class.
///
/// See also:
///
/// * [TextInput.attach]
/// * [EditableText], a [TextInputClient] implementation.
/// * [DeltaTextInputClient], a [TextInputClient] extension that receives
/// granular information from the platform's text input.
mixin TextInputClient {
/// The current state of the [TextEditingValue] held by this client.
TextEditingValue? get currentTextEditingValue;
/// The [AutofillScope] this [TextInputClient] belongs to, if any.
///
/// It should return null if this [TextInputClient] does not need autofill
/// support. For a [TextInputClient] that supports autofill, returning null
/// causes it to participate in autofill alone.
///
/// See also:
///
/// * [AutofillGroup], a widget that creates an [AutofillScope] for its
/// descendent autofillable [TextInputClient]s.
AutofillScope? get currentAutofillScope;
/// Requests that this client update its editing state to the given value.
///
/// The new [value] is treated as user input and thus may subject to input
/// formatting.
void updateEditingValue(TextEditingValue value);
/// Requests that this client perform the given action.
void performAction(TextInputAction action);
/// Notify client about new content insertion from Android keyboard.
void insertContent(KeyboardInsertedContent content) {}
/// Request from the input method that this client perform the given private
/// command.
///
/// This can be used to provide domain-specific features that are only known
/// between certain input methods and their clients.
///
/// See also:
/// * [performPrivateCommand](https://developer.android.com/reference/android/view/inputmethod/InputConnection#performPrivateCommand\(java.lang.String,%20android.os.Bundle\)),
/// which is the Android documentation for performPrivateCommand, used to
/// send a command from the input method.
/// * [sendAppPrivateCommand](https://developer.android.com/reference/android/view/inputmethod/InputMethodManager#sendAppPrivateCommand),
/// which is the Android documentation for sendAppPrivateCommand, used to
/// send a command to the input method.
void performPrivateCommand(String action, Map<String, dynamic> data);
/// Updates the floating cursor position and state.
///
/// See also:
///
/// * [FloatingCursorDragState], which explains the floating cursor feature
/// in detail.
void updateFloatingCursor(RawFloatingCursorPoint point);
/// Requests that this client display a prompt rectangle for the given text range,
/// to indicate the range of text that will be changed by a pending autocorrection.
///
/// This method will only be called on iOS.
void showAutocorrectionPromptRect(int start, int end);
/// Platform notified framework of closed connection.
///
/// [TextInputClient] should cleanup its connection and finalize editing.
void connectionClosed();
/// The framework calls this method to notify that the text input control has
/// been changed.
///
/// The [TextInputClient] may switch to the new text input control by hiding
/// the old and showing the new input control.
///
/// See also:
///
/// * [TextInputControl.hide], a method to hide the old input control.
/// * [TextInputControl.show], a method to show the new input control.
void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {}
/// Requests that the client show the editing toolbar, for example when the
/// platform changes the selection through a non-flutter method such as
/// scribble.
void showToolbar() {}
/// Requests that the client add a text placeholder to reserve visual space
/// in the text.
///
/// For example, this is called when responding to UIKit requesting
/// a text placeholder be added at the current selection, such as when
/// requesting additional writing space with iPadOS14 Scribble.
void insertTextPlaceholder(Size size) {}
/// Requests that the client remove the text placeholder.
void removeTextPlaceholder() {}
/// Performs the specified MacOS-specific selector from the
/// `NSStandardKeyBindingResponding` protocol or user-specified selector
/// from `DefaultKeyBinding.Dict`.
void performSelector(String selectorName) {}
}
/// An interface to receive focus from the engine.
///
/// This is currently only used to handle UIIndirectScribbleInteraction.
abstract class ScribbleClient {
/// A unique identifier for this element.
String get elementIdentifier;
/// Called by the engine when the [ScribbleClient] should receive focus.
///
/// For example, this method is called during a UIIndirectScribbleInteraction.
void onScribbleFocus(Offset offset);
/// Tests whether the [ScribbleClient] overlaps the given rectangle bounds.
bool isInScribbleRect(Rect rect);
/// The current bounds of the [ScribbleClient].
Rect get bounds;
}
/// Represents a selection rect for a character and it's position in the text.
///
/// This is used to report the current text selection rect and position data
/// to the engine for Scribble support on iPadOS 14.
@immutable
class SelectionRect {
/// Constructor for creating a [SelectionRect] from a text [position] and
/// [bounds].
const SelectionRect({
required this.position,
required this.bounds,
this.direction = TextDirection.ltr,
});
/// The position of this selection rect within the text String.
final int position;
/// The rectangle representing the bounds of this selection rect within the
/// currently focused [RenderEditable]'s coordinate space.
final Rect bounds;
/// The direction text flows within this selection rect.
final TextDirection direction;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (runtimeType != other.runtimeType) {
return false;
}
return other is SelectionRect
&& other.position == position
&& other.bounds == bounds
&& other.direction == direction;
}
@override
int get hashCode => Object.hash(position, bounds);
@override
String toString() => 'SelectionRect($position, $bounds)';
}
/// An interface to receive granular information from [TextInput].
///
/// See also:
///
/// * [TextInput.attach]
/// * [TextInputConfiguration], to opt-in to receive [TextEditingDelta]'s from
/// the platforms [TextInput] you must set [TextInputConfiguration.enableDeltaModel]
/// to true.
mixin DeltaTextInputClient implements TextInputClient {
/// Requests that this client update its editing state by applying the deltas
/// received from the engine.
///
/// The list of [TextEditingDelta]'s are treated as changes that will be applied
/// to the client's editing state. A change is any mutation to the raw text
/// value, or any updates to the selection and/or composing region.
///
/// {@tool snippet}
/// This example shows what an implementation of this method could look like.
///
/// ```dart
/// class MyClient with DeltaTextInputClient {
/// TextEditingValue? _localValue;
///
/// @override
/// void updateEditingValueWithDeltas(List<TextEditingDelta> textEditingDeltas) {
/// if (_localValue == null) {
/// return;
/// }
/// TextEditingValue newValue = _localValue!;
/// for (final TextEditingDelta delta in textEditingDeltas) {
/// newValue = delta.apply(newValue);
/// }
/// _localValue = newValue;
/// }
///
/// // ...
/// }
/// ```
/// {@end-tool}
void updateEditingValueWithDeltas(List<TextEditingDelta> textEditingDeltas);
}
/// An interface for interacting with a text input control.
///
/// See also:
///
/// * [TextInput.attach], a method used to establish a [TextInputConnection]
/// between the system's text input and a [TextInputClient].
/// * [EditableText], a [TextInputClient] that connects to and interacts with
/// the system's text input using a [TextInputConnection].
class TextInputConnection {
TextInputConnection._(this._client)
: _id = _nextId++;
Size? _cachedSize;
Matrix4? _cachedTransform;
Rect? _cachedRect;
Rect? _cachedCaretRect;
List<SelectionRect> _cachedSelectionRects = <SelectionRect>[];
static int _nextId = 1;
final int _id;
/// Resets the internal ID counter for testing purposes.
///
/// This call has no effect when asserts are disabled. Calling it from
/// application code will likely break text input for the application.
@visibleForTesting
static void debugResetId({int to = 1}) {
assert(() {
_nextId = to;
return true;
}());
}
final TextInputClient _client;
/// Whether this connection is currently interacting with the text input control.
bool get attached => TextInput._instance._currentConnection == this;
/// Whether there is currently a Scribble interaction in progress.
///
/// This is used to make sure selection handles are shown when UIKit changes
/// the selection during a Scribble interaction.
bool get scribbleInProgress => TextInput._instance.scribbleInProgress;
/// Requests that the text input control become visible.
void show() {
assert(attached);
TextInput._instance._show();
}
/// Requests the system autofill UI to appear.
///
/// Currently only works on Android. Other platforms do not respond to this
/// message.
///
/// See also:
///
/// * [EditableText], a [TextInputClient] that calls this method when focused.
void requestAutofill() {
assert(attached);
TextInput._instance._requestAutofill();
}
/// Requests that the text input control update itself according to the new
/// [TextInputConfiguration].
void updateConfig(TextInputConfiguration configuration) {
assert(attached);
TextInput._instance._updateConfig(configuration);
}
/// Requests that the text input control change its internal state to match
/// the given state.
void setEditingState(TextEditingValue value) {
assert(attached);
TextInput._instance._setEditingState(value);
}
/// Send the size and transform of the editable text to engine.
///
/// The values are sent as platform messages so they can be used on web for
/// example to correctly position and size the html input field.
///
/// 1. [editableBoxSize]: size of the render editable box.
///
/// 2. [transform]: a matrix that maps the local paint coordinate system
/// to the [PipelineOwner.rootNode].
void setEditableSizeAndTransform(Size editableBoxSize, Matrix4 transform) {
if (editableBoxSize != _cachedSize || transform != _cachedTransform) {
_cachedSize = editableBoxSize;
_cachedTransform = transform;
TextInput._instance._setEditableSizeAndTransform(editableBoxSize, transform);
}
}
/// Send the smallest rect that covers the text in the client that's currently
/// being composed.
///
/// If any of the 4 coordinates of the given [Rect] is not finite, a [Rect] of
/// size (-1, -1) will be sent instead.
///
/// This information is used for positioning the IME candidates menu on each
/// platform.
void setComposingRect(Rect rect) {
if (rect == _cachedRect) {
return;
}
_cachedRect = rect;
final Rect validRect = rect.isFinite ? rect : Offset.zero & const Size(-1, -1);
TextInput._instance._setComposingTextRect(validRect);
}
/// Sends the coordinates of caret rect. This is used on macOS for positioning
/// the accent selection menu.
void setCaretRect(Rect rect) {
if (rect == _cachedCaretRect) {
return;
}
_cachedCaretRect = rect;
final Rect validRect = rect.isFinite ? rect : Offset.zero & const Size(-1, -1);
TextInput._instance._setCaretRect(validRect);
}
/// Send the bounding boxes of the current selected glyphs in the client to
/// the platform's text input plugin.
///
/// These are used by the engine during a UIDirectScribbleInteraction.
void setSelectionRects(List<SelectionRect> selectionRects) {
if (!listEquals(_cachedSelectionRects, selectionRects)) {
_cachedSelectionRects = selectionRects;
TextInput._instance._setSelectionRects(selectionRects);
}
}
/// Send text styling information.
///
/// This information is used by the Flutter Web Engine to change the style
/// of the hidden native input's content. Hence, the content size will match
/// to the size of the editable widget's content.
void setStyle({
required String? fontFamily,
required double? fontSize,
required FontWeight? fontWeight,
required TextDirection textDirection,
required TextAlign textAlign,
}) {
assert(attached);
TextInput._instance._setStyle(
fontFamily: fontFamily,
fontSize: fontSize,
fontWeight: fontWeight,
textDirection: textDirection,
textAlign: textAlign,
);
}
/// Stop interacting with the text input control.
///
/// After calling this method, the text input control might disappear if no
/// other client attaches to it within this animation frame.
void close() {
if (attached) {
TextInput._instance._clearClient();
}
assert(!attached);
}
/// Platform sent a notification informing the connection is closed.
///
/// [TextInputConnection] should clean current client connection.
void connectionClosedReceived() {
TextInput._instance._currentConnection = null;
assert(!attached);
}
}
TextInputAction _toTextInputAction(String action) {
return switch (action) {
'TextInputAction.none' => TextInputAction.none,
'TextInputAction.unspecified' => TextInputAction.unspecified,
'TextInputAction.go' => TextInputAction.go,
'TextInputAction.search' => TextInputAction.search,
'TextInputAction.send' => TextInputAction.send,
'TextInputAction.next' => TextInputAction.next,
'TextInputAction.previous' => TextInputAction.previous,
'TextInputAction.continueAction' => TextInputAction.continueAction,
'TextInputAction.join' => TextInputAction.join,
'TextInputAction.route' => TextInputAction.route,
'TextInputAction.emergencyCall' => TextInputAction.emergencyCall,
'TextInputAction.done' => TextInputAction.done,
'TextInputAction.newline' => TextInputAction.newline,
_ => throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Unknown text input action: $action')]),
};
}
FloatingCursorDragState _toTextCursorAction(String state) {
return switch (state) {
'FloatingCursorDragState.start' => FloatingCursorDragState.Start,
'FloatingCursorDragState.update' => FloatingCursorDragState.Update,
'FloatingCursorDragState.end' => FloatingCursorDragState.End,
_ => throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Unknown text cursor action: $state')]),
};
}
RawFloatingCursorPoint _toTextPoint(FloatingCursorDragState state, Map<String, dynamic> encoded) {
assert(encoded['X'] != null, 'You must provide a value for the horizontal location of the floating cursor.');
assert(encoded['Y'] != null, 'You must provide a value for the vertical location of the floating cursor.');
final Offset offset = state == FloatingCursorDragState.Update
? Offset((encoded['X'] as num).toDouble(), (encoded['Y'] as num).toDouble())
: Offset.zero;
return RawFloatingCursorPoint(offset: offset, state: state);
}
/// An low-level interface to the system's text input control.
///
/// To start interacting with the system's text input control, call [attach] to
/// establish a [TextInputConnection] between the system's text input control
/// and a [TextInputClient]. The majority of commands available for
/// interacting with the text input control reside in the returned
/// [TextInputConnection]. The communication between the system text input and
/// the [TextInputClient] is asynchronous.
///
/// The platform text input plugin (which represents the system's text input)
/// and the [TextInputClient] usually maintain their own text editing states
/// ([TextEditingValue]) separately. They must be kept in sync as long as the
/// [TextInputClient] is connected. The following methods can be used to send
/// [TextEditingValue] to update the other party, when either party's text
/// editing states change:
///
/// * The [TextInput.attach] method allows a [TextInputClient] to establish a
/// connection to the text input. An optional field in its `configuration`
/// parameter can be used to specify an initial value for the platform text
/// input plugin's [TextEditingValue].
///
/// * The [TextInputClient] sends its [TextEditingValue] to the platform text
/// input plugin using [TextInputConnection.setEditingState].
///
/// * The platform text input plugin sends its [TextEditingValue] to the
/// connected [TextInputClient] via a "TextInput.setEditingState" message.
///
/// * When autofill happens on a disconnected [TextInputClient], the platform
/// text input plugin sends the [TextEditingValue] to the connected
/// [TextInputClient]'s [AutofillScope], and the [AutofillScope] will further
/// relay the value to the correct [TextInputClient].
///
/// When synchronizing the [TextEditingValue]s, the communication may get stuck
/// in an infinite when both parties are trying to send their own update. To
/// mitigate the problem, only [TextInputClient]s are allowed to alter the
/// received [TextEditingValue]s while platform text input plugins are to accept
/// the received [TextEditingValue]s unmodified. More specifically:
///
/// * When a [TextInputClient] receives a new [TextEditingValue] from the
/// platform text input plugin, it's allowed to modify the value (for example,
/// apply [TextInputFormatter]s). If it decides to do so, it must send the
/// updated [TextEditingValue] back to the platform text input plugin to keep
/// the [TextEditingValue]s in sync.
///
/// * When the platform text input plugin receives a new value from the
/// connected [TextInputClient], it must accept the new value as-is, to avoid
/// sending back an updated value.
///
/// See also:
///
/// * [TextField], a widget in which the user may enter text.
/// * [EditableText], a [TextInputClient] that connects to [TextInput] when it
/// wants to take user input from the keyboard.
class TextInput {
TextInput._() {
_channel = SystemChannels.textInput;
_channel.setMethodCallHandler(_loudlyHandleTextInputInvocation);
}
/// Set the [MethodChannel] used to communicate with the system's text input
/// control.
///
/// This is only meant for testing within the Flutter SDK. Changing this
/// will break the ability to input text. This has no effect if asserts are
/// disabled.
@visibleForTesting
static void setChannel(MethodChannel newChannel) {
assert(() {
_instance._channel = newChannel..setMethodCallHandler(_instance._loudlyHandleTextInputInvocation);
return true;
}());
}
static final TextInput _instance = TextInput._();
static void _addInputControl(TextInputControl control) {
if (control != _PlatformTextInputControl.instance) {
_instance._inputControls.add(control);
}
}
static void _removeInputControl(TextInputControl control) {
if (control != _PlatformTextInputControl.instance) {
_instance._inputControls.remove(control);
}
}
/// Sets the current text input control.
///
/// The current text input control receives text input state changes and visual
/// text input control requests, such as showing and hiding the input control,
/// from the framework.
///
/// Setting the current text input control as `null` removes the visual text
/// input control.
///
/// See also:
///
/// * [TextInputControl], an interface for implementing text input controls.
/// * [TextInput.restorePlatformInputControl], a method to restore the default
/// platform text input control.
static void setInputControl(TextInputControl? newControl) {
final TextInputControl? oldControl = _instance._currentControl;
if (newControl == oldControl) {
return;
}
if (newControl != null) {
_addInputControl(newControl);
}
if (oldControl != null) {
_removeInputControl(oldControl);
}
_instance._currentControl = newControl;
final TextInputClient? client = _instance._currentConnection?._client;
client?.didChangeInputControl(oldControl, newControl);
}
/// Restores the default platform text input control.
///
/// See also:
///
/// * [TextInput.setInputControl], a method to set a custom input
/// control, or to remove the visual input control.
static void restorePlatformInputControl() {
setInputControl(_PlatformTextInputControl.instance);
}
TextInputControl? _currentControl = _PlatformTextInputControl.instance;
final Set<TextInputControl> _inputControls = <TextInputControl>{
_PlatformTextInputControl.instance,
};
static const List<TextInputAction> _androidSupportedInputActions = <TextInputAction>[
TextInputAction.none,
TextInputAction.unspecified,
TextInputAction.done,
TextInputAction.send,
TextInputAction.go,
TextInputAction.search,
TextInputAction.next,
TextInputAction.previous,
TextInputAction.newline,
];
static const List<TextInputAction> _iOSSupportedInputActions = <TextInputAction>[
TextInputAction.unspecified,
TextInputAction.done,
TextInputAction.send,
TextInputAction.go,
TextInputAction.search,
TextInputAction.next,
TextInputAction.newline,
TextInputAction.continueAction,
TextInputAction.join,
TextInputAction.route,
TextInputAction.emergencyCall,
];
/// Ensure that a [TextInput] instance has been set up so that the platform
/// can handle messages on the text input method channel.
static void ensureInitialized() {
_instance; // ignore: unnecessary_statements
}
/// Begin interacting with the text input control.
///
/// Calling this function helps multiple clients coordinate about which one is
/// currently interacting with the text input control. The returned
/// [TextInputConnection] provides an interface for actually interacting with
/// the text input control.
///
/// A client that no longer wishes to interact with the text input control
/// should call [TextInputConnection.close] on the returned
/// [TextInputConnection].
static TextInputConnection attach(TextInputClient client, TextInputConfiguration configuration) {
final TextInputConnection connection = TextInputConnection._(client);
_instance._attach(connection, configuration);
return connection;
}
// This method actually notifies the embedding of the client. It is utilized
// by [attach] and by [_handleTextInputInvocation] for the
// `TextInputClient.requestExistingInputState` method.
void _attach(TextInputConnection connection, TextInputConfiguration configuration) {
assert(_debugEnsureInputActionWorksOnPlatform(configuration.inputAction));
_currentConnection = connection;
_currentConfiguration = configuration;
_setClient(connection._client, configuration);
}
static bool _debugEnsureInputActionWorksOnPlatform(TextInputAction inputAction) {
assert(() {
if (kIsWeb) {
// TODO(flutterweb): what makes sense here?
return true;
}
if (Platform.isIOS) {
assert(
_iOSSupportedInputActions.contains(inputAction),
'The requested TextInputAction "$inputAction" is not supported on iOS.',
);
} else if (Platform.isAndroid) {
assert(
_androidSupportedInputActions.contains(inputAction),
'The requested TextInputAction "$inputAction" is not supported on Android.',
);
}
return true;
}());
return true;
}
late MethodChannel _channel;
TextInputConnection? _currentConnection;
late TextInputConfiguration _currentConfiguration;
final Map<String, ScribbleClient> _scribbleClients = <String, ScribbleClient>{};
bool _scribbleInProgress = false;
/// Used for testing within the Flutter SDK to get the currently registered [ScribbleClient] list.
@visibleForTesting
static Map<String, ScribbleClient> get scribbleClients => TextInput._instance._scribbleClients;
/// Returns true if a scribble interaction is currently happening.
bool get scribbleInProgress => _scribbleInProgress;
Future<dynamic> _loudlyHandleTextInputInvocation(MethodCall call) async {
try {
return await _handleTextInputInvocation(call);
} catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'services library',
context: ErrorDescription('during method call ${call.method}'),
informationCollector: () => <DiagnosticsNode>[
DiagnosticsProperty<MethodCall>('call', call, style: DiagnosticsTreeStyle.errorProperty),
],
));
rethrow;
}
}
Future<dynamic> _handleTextInputInvocation(MethodCall methodCall) async {
final String method = methodCall.method;
switch (methodCall.method) {
case 'TextInputClient.focusElement':
final List<dynamic> args = methodCall.arguments as List<dynamic>;
_scribbleClients[args[0]]?.onScribbleFocus(Offset((args[1] as num).toDouble(), (args[2] as num).toDouble()));
return;
case 'TextInputClient.requestElementsInRect':
final List<double> args = (methodCall.arguments as List<dynamic>).cast<num>().map<double>((num value) => value.toDouble()).toList();
return _scribbleClients.keys.where((String elementIdentifier) {
final Rect rect = Rect.fromLTWH(args[0], args[1], args[2], args[3]);
if (!(_scribbleClients[elementIdentifier]?.isInScribbleRect(rect) ?? false)) {
return false;
}
final Rect bounds = _scribbleClients[elementIdentifier]?.bounds ?? Rect.zero;
return !(bounds == Rect.zero || bounds.hasNaN || bounds.isInfinite);
}).map((String elementIdentifier) {
final Rect bounds = _scribbleClients[elementIdentifier]!.bounds;
return <dynamic>[elementIdentifier, ...<dynamic>[bounds.left, bounds.top, bounds.width, bounds.height]];
}).toList();
case 'TextInputClient.scribbleInteractionBegan':
_scribbleInProgress = true;
return;
case 'TextInputClient.scribbleInteractionFinished':
_scribbleInProgress = false;
return;
}
if (_currentConnection == null) {
return;
}
// The requestExistingInputState request needs to be handled regardless of
// the client ID, as long as we have a _currentConnection.
if (method == 'TextInputClient.requestExistingInputState') {
_attach(_currentConnection!, _currentConfiguration);
final TextEditingValue? editingValue = _currentConnection!._client.currentTextEditingValue;
if (editingValue != null) {
_setEditingState(editingValue);
}
return;
}
final List<dynamic> args = methodCall.arguments as List<dynamic>;
// The updateEditingStateWithTag request (autofill) can come up even to a
// text field that doesn't have a connection.
if (method == 'TextInputClient.updateEditingStateWithTag') {
final TextInputClient client = _currentConnection!._client;
final AutofillScope? scope = client.currentAutofillScope;
final Map<String, dynamic> editingValue = args[1] as Map<String, dynamic>;
for (final String tag in editingValue.keys) {
final TextEditingValue textEditingValue = TextEditingValue.fromJSON(
editingValue[tag] as Map<String, dynamic>,
);
final AutofillClient? client = scope?.getAutofillClient(tag);
if (client != null && client.textInputConfiguration.autofillConfiguration.enabled) {
client.autofill(textEditingValue);
}
}
return;
}
final int client = args[0] as int;
if (client != _currentConnection!._id) {
// If the client IDs don't match, the incoming message was for a different
// client.
bool debugAllowAnyway = false;
assert(() {
// In debug builds we allow "-1" as a magical client ID that ignores
// this verification step so that tests can always get through, even
// when they are not mocking the engine side of text input.
if (client == -1) {
debugAllowAnyway = true;
}
return true;
}());
if (!debugAllowAnyway) {
return;
}
}
switch (method) {
case 'TextInputClient.updateEditingState':
final TextEditingValue value = TextEditingValue.fromJSON(args[1] as Map<String, dynamic>);
TextInput._instance._updateEditingValue(value, exclude: _PlatformTextInputControl.instance);
case 'TextInputClient.updateEditingStateWithDeltas':
assert(_currentConnection!._client is DeltaTextInputClient, 'You must be using a DeltaTextInputClient if TextInputConfiguration.enableDeltaModel is set to true');
final List<TextEditingDelta> deltas = <TextEditingDelta>[];
final Map<String, dynamic> encoded = args[1] as Map<String, dynamic>;
for (final dynamic encodedDelta in encoded['deltas'] as List<dynamic>) {
final TextEditingDelta delta = TextEditingDelta.fromJSON(encodedDelta as Map<String, dynamic>);
deltas.add(delta);
}
(_currentConnection!._client as DeltaTextInputClient).updateEditingValueWithDeltas(deltas);
case 'TextInputClient.performAction':
if (args[1] as String == 'TextInputAction.commitContent') {
final KeyboardInsertedContent content = KeyboardInsertedContent.fromJson(args[2] as Map<String, dynamic>);
_currentConnection!._client.insertContent(content);
} else {
_currentConnection!._client.performAction(_toTextInputAction(args[1] as String));
}
case 'TextInputClient.performSelectors':
final List<String> selectors = (args[1] as List<dynamic>).cast<String>();
selectors.forEach(_currentConnection!._client.performSelector);
case 'TextInputClient.performPrivateCommand':
final Map<String, dynamic> firstArg = args[1] as Map<String, dynamic>;
_currentConnection!._client.performPrivateCommand(
firstArg['action'] as String,
firstArg['data'] == null
? <String, dynamic>{}
: firstArg['data'] as Map<String, dynamic>,
);
case 'TextInputClient.updateFloatingCursor':
_currentConnection!._client.updateFloatingCursor(_toTextPoint(
_toTextCursorAction(args[1] as String),
args[2] as Map<String, dynamic>,
));
case 'TextInputClient.onConnectionClosed':
_currentConnection!._client.connectionClosed();
case 'TextInputClient.showAutocorrectionPromptRect':
_currentConnection!._client.showAutocorrectionPromptRect(args[1] as int, args[2] as int);
case 'TextInputClient.showToolbar':
_currentConnection!._client.showToolbar();
case 'TextInputClient.insertTextPlaceholder':
_currentConnection!._client.insertTextPlaceholder(Size((args[1] as num).toDouble(), (args[2] as num).toDouble()));
case 'TextInputClient.removeTextPlaceholder':
_currentConnection!._client.removeTextPlaceholder();
default:
throw MissingPluginException();
}
}
bool _hidePending = false;
void _scheduleHide() {
if (_hidePending) {
return;
}
_hidePending = true;
// Schedule a deferred task that hides the text input. If someone else
// shows the keyboard during this update cycle, then the task will do
// nothing.
scheduleMicrotask(() {
_hidePending = false;
if (_currentConnection == null) {
_hide();
}
});
}
void _setClient(TextInputClient client, TextInputConfiguration configuration) {
for (final TextInputControl control in _inputControls) {
control.attach(client, configuration);
}
}
void _clearClient() {
final TextInputClient client = _currentConnection!._client;
for (final TextInputControl control in _inputControls) {
control.detach(client);
}
_currentConnection = null;
_scheduleHide();
}
void _updateConfig(TextInputConfiguration configuration) {
for (final TextInputControl control in _inputControls) {
control.updateConfig(configuration);
}
}
void _setEditingState(TextEditingValue value) {
for (final TextInputControl control in _inputControls) {
control.setEditingState(value);
}
}
void _show() {
for (final TextInputControl control in _inputControls) {
control.show();
}
}
void _hide() {
for (final TextInputControl control in _inputControls) {
control.hide();
}
}
void _setEditableSizeAndTransform(Size editableBoxSize, Matrix4 transform) {
for (final TextInputControl control in _inputControls) {
control.setEditableSizeAndTransform(editableBoxSize, transform);
}
}
void _setComposingTextRect(Rect rect) {
for (final TextInputControl control in _inputControls) {
control.setComposingRect(rect);
}
}
void _setCaretRect(Rect rect) {
for (final TextInputControl control in _inputControls) {
control.setCaretRect(rect);
}
}
void _setSelectionRects(List<SelectionRect> selectionRects) {
for (final TextInputControl control in _inputControls) {
control.setSelectionRects(selectionRects);
}
}
void _setStyle({
required String? fontFamily,
required double? fontSize,
required FontWeight? fontWeight,
required TextDirection textDirection,
required TextAlign textAlign,
}) {
for (final TextInputControl control in _inputControls) {
control.setStyle(
fontFamily: fontFamily,
fontSize: fontSize,
fontWeight: fontWeight,
textDirection: textDirection,
textAlign: textAlign,
);
}
}
void _requestAutofill() {
for (final TextInputControl control in _inputControls) {
control.requestAutofill();
}
}
void _updateEditingValue(TextEditingValue value, {TextInputControl? exclude}) {
if (_currentConnection == null) {
return;
}
for (final TextInputControl control in _instance._inputControls) {
if (control != exclude) {
control.setEditingState(value);
}
}
_instance._currentConnection!._client.updateEditingValue(value);
}
/// Updates the editing value of the attached input client.
///
/// This method should be called by the text input control implementation to
/// send editing value updates to the attached input client.
static void updateEditingValue(TextEditingValue value) {
_instance._updateEditingValue(value, exclude: _instance._currentControl);
}
/// Finishes the current autofill context, and potentially saves the user
/// input for future use if `shouldSave` is true.
///
/// Typically, this method should be called when the user has finalized their
/// input. For example, in a [Form], it's typically done immediately before or
/// after its content is submitted.
///
/// The topmost [AutofillGroup]s also call [finishAutofillContext]
/// automatically when they are disposed. The default behavior can be
/// overridden in [AutofillGroup.onDisposeAction].
///
/// {@template flutter.services.TextInput.finishAutofillContext}
/// An autofill context is a collection of input fields that live in the
/// platform's text input plugin. The platform is encouraged to save the user
/// input stored in the current autofill context before the context is
/// destroyed, when [TextInput.finishAutofillContext] is called with
/// `shouldSave` set to true.
///
/// Currently, there can only be at most one autofill context at any given
/// time. When any input field in an [AutofillGroup] requests for autofill
/// (which is done automatically when an autofillable [EditableText] gains
/// focus), the current autofill context will merge the content of that
/// [AutofillGroup] into itself. When there isn't an existing autofill context,
/// one will be created to hold the newly added input fields from the group.
///
/// Once added to an autofill context, an input field will stay in the context
/// until the context is destroyed. To prevent leaks, call
/// [TextInput.finishAutofillContext] to signal the text input plugin that the
/// user has finalized their input in the current autofill context. The
/// platform text input plugin either encourages or discourages the platform
/// from saving the user input based on the value of the `shouldSave`
/// parameter. The platform usually shows a "Save for autofill?" prompt for
/// user confirmation.
/// {@endtemplate}
///
/// On many platforms, calling [finishAutofillContext] shows the save user
/// input dialog and disrupts the user's flow. Ideally the dialog should only
/// be shown no more than once for every screen. Consider removing premature
/// [finishAutofillContext] calls to prevent showing the save user input UI
/// too frequently. However, calling [finishAutofillContext] when there's no
/// existing autofill context usually does not bring up the save user input
/// UI.
///
/// See also:
///
/// * [EditableText.autofillHints] for autofill save troubleshooting tips.
/// * [AutofillGroup.onDisposeAction], a configurable action that runs when a
/// topmost [AutofillGroup] is getting disposed.
static void finishAutofillContext({ bool shouldSave = true }) {
for (final TextInputControl control in TextInput._instance._inputControls) {
control.finishAutofillContext(shouldSave: shouldSave);
}
}
/// Registers a [ScribbleClient] with [elementIdentifier] that can be focused
/// by the engine.
///
/// For example, the registered [ScribbleClient] list is used to respond to
/// UIIndirectScribbleInteraction on an iPad.
static void registerScribbleElement(String elementIdentifier, ScribbleClient scribbleClient) {
TextInput._instance._scribbleClients[elementIdentifier] = scribbleClient;
}
/// Unregisters a [ScribbleClient] with [elementIdentifier].
static void unregisterScribbleElement(String elementIdentifier) {
TextInput._instance._scribbleClients.remove(elementIdentifier);
}
}
/// An interface for implementing text input controls that receive text editing
/// state changes and visual input control requests.
///
/// Editing state changes and input control requests are sent by the framework
/// when the editing state of the attached text input client changes, or it
/// requests the input control to be shown or hidden, for example.
///
/// The input control can be installed with [TextInput.setInputControl], and the
/// default platform text input control can be restored with
/// [TextInput.restorePlatformInputControl].
///
/// The [TextInputControl] class must be extended. [TextInputControl]
/// implementations should call [TextInput.updateEditingValue] to send user
/// input to the attached input client.
///
/// {@tool dartpad}
/// This example illustrates a basic [TextInputControl] implementation.
///
/// ** See code in examples/api/lib/services/text_input/text_input_control.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [TextInput.setInputControl], a method to install a custom text input control.
/// * [TextInput.restorePlatformInputControl], a method to restore the default
/// platform text input control.
/// * [TextInput.updateEditingValue], a method to send user input to
/// the framework.
mixin TextInputControl {
/// Requests the text input control to attach to the given input client.
///
/// This method is called when a text input client is attached. The input
/// control should update its configuration to match the client's configuration.
void attach(TextInputClient client, TextInputConfiguration configuration) {}
/// Requests the text input control to detach from the given input client.
///
/// This method is called when a text input client is detached. The input
/// control should release any resources allocated for the client.
void detach(TextInputClient client) {}
/// Requests that the text input control is shown.
///
/// This method is called when the input control should become visible.
void show() {}
/// Requests that the text input control is hidden.
///
/// This method is called when the input control should hide.
void hide() {}
/// Informs the text input control about input configuration changes.
///
/// This method is called when the configuration of the attached input client
/// has changed.
void updateConfig(TextInputConfiguration configuration) {}
/// Informs the text input control about editing state changes.
///
/// This method is called when the editing state of the attached input client
/// has changed.
void setEditingState(TextEditingValue value) {}
/// Informs the text input control about client position changes.
///
/// This method is called on when the input control should position itself in
/// relation to the attached input client.
void setEditableSizeAndTransform(Size editableBoxSize, Matrix4 transform) {}
/// Informs the text input control about composing area changes.
///
/// This method is called when the attached input client's composing area
/// changes.
void setComposingRect(Rect rect) {}
/// Informs the text input control about caret area changes.
///
/// This method is called when the attached input client's caret area
/// changes.
void setCaretRect(Rect rect) {}
/// Informs the text input control about selection area changes.
///
/// This method is called when the attached input client's selection area
/// changes.
void setSelectionRects(List<SelectionRect> selectionRects) {}
/// Informs the text input control about text style changes.
///
/// This method is called on the when the attached input client's text style
/// changes.
void setStyle({
required String? fontFamily,
required double? fontSize,
required FontWeight? fontWeight,
required TextDirection textDirection,
required TextAlign textAlign,
}) {}
/// Requests autofill from the text input control.
///
/// This method is called when the autofill UI should appear.
void requestAutofill() {}
/// Requests that the autofill context is finalized.
///
/// See also:
///
/// * [TextInput.finishAutofillContext]
void finishAutofillContext({bool shouldSave = true}) {}
}
/// Provides access to the platform text input control.
class _PlatformTextInputControl with TextInputControl {
_PlatformTextInputControl._();
/// The shared instance of [_PlatformTextInputControl].
static final _PlatformTextInputControl instance = _PlatformTextInputControl._();
MethodChannel get _channel => TextInput._instance._channel;
Map<String, dynamic> _configurationToJson(TextInputConfiguration configuration) {
final Map<String, dynamic> json = configuration.toJson();
if (TextInput._instance._currentControl != _PlatformTextInputControl.instance) {
final Map<String, dynamic> none = TextInputType.none.toJson();
// See: https://github.com/flutter/flutter/issues/125875
// On Web engine, use isMultiline to create <input> or <textarea> element
// When there's a custom [TextInputControl] installed.
// It's only needed When there's a custom [TextInputControl] installed.
if (kIsWeb) {
none['isMultiline'] = configuration.inputType == TextInputType.multiline;
}
json['inputType'] = none;
}
return json;
}
@override
void attach(TextInputClient client, TextInputConfiguration configuration) {
_channel.invokeMethod<void>(
'TextInput.setClient',
<Object>[
TextInput._instance._currentConnection!._id,
_configurationToJson(configuration),
],
);
}
@override
void detach(TextInputClient client) {
_channel.invokeMethod<void>('TextInput.clearClient');
}
@override
void updateConfig(TextInputConfiguration configuration) {
_channel.invokeMethod<void>(
'TextInput.updateConfig',
_configurationToJson(configuration),
);
}
@override
void setEditingState(TextEditingValue value) {
_channel.invokeMethod<void>(
'TextInput.setEditingState',
value.toJSON(),
);
}
@override
void show() {
_channel.invokeMethod<void>('TextInput.show');
}
@override
void hide() {
_channel.invokeMethod<void>('TextInput.hide');
}
@override
void setEditableSizeAndTransform(Size editableBoxSize, Matrix4 transform) {
_channel.invokeMethod<void>(
'TextInput.setEditableSizeAndTransform',
<String, dynamic>{
'width': editableBoxSize.width,
'height': editableBoxSize.height,
'transform': transform.storage,
},
);
}
@override
void setComposingRect(Rect rect) {
_channel.invokeMethod<void>(
'TextInput.setMarkedTextRect',
<String, dynamic>{
'width': rect.width,
'height': rect.height,
'x': rect.left,
'y': rect.top,
},
);
}
@override
void setCaretRect(Rect rect) {
_channel.invokeMethod<void>(
'TextInput.setCaretRect',
<String, dynamic>{
'width': rect.width,
'height': rect.height,
'x': rect.left,
'y': rect.top,
},
);
}
@override
void setSelectionRects(List<SelectionRect> selectionRects) {
_channel.invokeMethod<void>(
'TextInput.setSelectionRects',
selectionRects.map((SelectionRect rect) {
return <num>[
rect.bounds.left,
rect.bounds.top,
rect.bounds.width,
rect.bounds.height,
rect.position,
rect.direction.index,
];
}).toList(),
);
}
@override
void setStyle({
required String? fontFamily,
required double? fontSize,
required FontWeight? fontWeight,
required TextDirection textDirection,
required TextAlign textAlign,
}) {
_channel.invokeMethod<void>(
'TextInput.setStyle',
<String, dynamic>{
'fontFamily': fontFamily,
'fontSize': fontSize,
'fontWeightIndex': fontWeight?.index,
'textAlignIndex': textAlign.index,
'textDirectionIndex': textDirection.index,
},
);
}
@override
void requestAutofill() {
_channel.invokeMethod<void>('TextInput.requestAutofill');
}
@override
void finishAutofillContext({bool shouldSave = true}) {
_channel.invokeMethod<void>(
'TextInput.finishAutofillContext',
shouldSave,
);
}
}
| flutter/packages/flutter/lib/src/services/text_input.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/text_input.dart",
"repo_id": "flutter",
"token_count": 27411
} | 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:ui';
import 'package:flutter/foundation.dart';
import 'binding.dart';
/// A callback type that is used by [AppLifecycleListener.onExitRequested] to
/// ask the application if it wants to cancel application termination or not.
typedef AppExitRequestCallback = Future<AppExitResponse> Function();
/// A listener that can be used to listen to changes in the application
/// lifecycle.
///
/// To listen for requests for the application to exit, and to decide whether or
/// not the application should exit when requested, create an
/// [AppLifecycleListener] and set the [onExitRequested] callback.
///
/// To listen for changes in the application lifecycle state, define an
/// [onStateChange] callback. See the [AppLifecycleState] enum for details on
/// the various states.
///
/// The [onStateChange] callback is called for each state change, and the
/// individual state transitions ([onResume], [onInactive], etc.) are also
/// called if the state transition they represent occurs.
///
/// State changes will occur in accordance with the state machine described by
/// this diagram:
///
/// 
///
/// The initial state of the state machine is the [AppLifecycleState.detached]
/// state, and the arrows describe valid state transitions. Transitions in blue
/// are transitions that only happen on iOS and Android.
///
/// {@tool dartpad}
/// This example shows how an application can listen to changes in the
/// application state.
///
/// ** See code in examples/api/lib/widgets/app_lifecycle_listener/app_lifecycle_listener.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows how an application can optionally decide to abort a
/// request for exiting instead of obeying the request.
///
/// ** See code in examples/api/lib/widgets/app_lifecycle_listener/app_lifecycle_listener.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ServicesBinding.exitApplication] for a function to call that will request
/// that the application exits.
/// * [WidgetsBindingObserver.didRequestAppExit] for the handler which this
/// class uses to receive exit requests.
/// * [WidgetsBindingObserver.didChangeAppLifecycleState] for the handler which
/// this class uses to receive lifecycle state changes.
class AppLifecycleListener with WidgetsBindingObserver, Diagnosticable {
/// Creates an [AppLifecycleListener].
AppLifecycleListener({
WidgetsBinding? binding,
this.onResume,
this.onInactive,
this.onHide,
this.onShow,
this.onPause,
this.onRestart,
this.onDetach,
this.onExitRequested,
this.onStateChange,
}) : binding = binding ?? WidgetsBinding.instance,
_lifecycleState = (binding ?? WidgetsBinding.instance).lifecycleState {
// 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: '$AppLifecycleListener',
object: this,
);
}
this.binding.addObserver(this);
}
AppLifecycleState? _lifecycleState;
/// The [WidgetsBinding] to listen to for application lifecycle events.
///
/// Typically, this is set to [WidgetsBinding.instance], but may be
/// substituted for testing or other specialized bindings.
///
/// Defaults to [WidgetsBinding.instance].
final WidgetsBinding binding;
/// Called anytime the state changes, passing the new state.
final ValueChanged<AppLifecycleState>? onStateChange;
/// A callback that is called when the application loses input focus.
///
/// On mobile platforms, this can be during a phone call or when a system
/// dialog is visible.
///
/// On desktop platforms, this is when all views in an application have lost
/// input focus but at least one view of the application is still visible.
///
/// On the web, this is when the window (or tab) has lost input focus.
final VoidCallback? onInactive;
/// A callback that is called when a view in the application gains input
/// focus.
///
/// A call to this callback indicates that the application is entering a state
/// where it is visible, active, and accepting user input.
final VoidCallback? onResume;
/// A callback that is called when the application is hidden.
///
/// On mobile platforms, this is usually just before the application is
/// replaced by another application in the foreground.
///
/// On desktop platforms, this is just before the application is hidden by
/// being minimized or otherwise hiding all views of the application.
///
/// On the web, this is just before a window (or tab) is hidden.
final VoidCallback? onHide;
/// A callback that is called when the application is shown.
///
/// On mobile platforms, this is usually just before the application replaces
/// another application in the foreground.
///
/// On desktop platforms, this is just before the application is shown after
/// being minimized or otherwise made to show at least one view of the
/// application.
///
/// On the web, this is just before a window (or tab) is shown.
final VoidCallback? onShow;
/// A callback that is called when the application is paused.
///
/// On mobile platforms, this happens right before the application is replaced
/// by another application.
///
/// On desktop platforms and the web, this function is not called.
final VoidCallback? onPause;
/// A callback that is called when the application is resumed after being
/// paused.
///
/// On mobile platforms, this happens just before this application takes over
/// as the active application.
///
/// On desktop platforms and the web, this function is not called.
final VoidCallback? onRestart;
/// A callback used to ask the application if it will allow exiting the
/// application for cases where the exit is cancelable.
///
/// Exiting the application isn't always cancelable, but when it is, this
/// function will be called before exit occurs.
///
/// Responding [AppExitResponse.exit] will continue termination, and
/// responding [AppExitResponse.cancel] will cancel it. If termination is not
/// canceled, the application will immediately exit.
final AppExitRequestCallback? onExitRequested;
/// A callback that is called when an application has exited, and detached all
/// host views from the engine.
///
/// This callback is only called on iOS and Android.
final VoidCallback? onDetach;
bool _debugDisposed = false;
/// Call when the listener is no longer in use.
///
/// Do not use the object after calling [dispose].
///
/// Subclasses must call this method in their overridden [dispose], if any.
@mustCallSuper
void dispose() {
assert(_debugAssertNotDisposed());
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
binding.removeObserver(this);
assert(() {
_debugDisposed = true;
return true;
}());
}
bool _debugAssertNotDisposed() {
assert(() {
if (_debugDisposed) {
throw FlutterError(
'A $runtimeType was used after being disposed.\n'
'Once you have called dispose() on a $runtimeType, it '
'can no longer be used.',
);
}
return true;
}());
return true;
}
@override
Future<AppExitResponse> didRequestAppExit() async {
assert(_debugAssertNotDisposed());
if (onExitRequested == null) {
return AppExitResponse.exit;
}
return onExitRequested!();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
assert(_debugAssertNotDisposed());
final AppLifecycleState? previousState = _lifecycleState;
if (state == previousState) {
// Transitioning to the same state twice doesn't produce any
// notifications (but also won't actually occur).
return;
}
_lifecycleState = state;
switch (state) {
case AppLifecycleState.resumed:
assert(previousState == null || previousState == AppLifecycleState.inactive || previousState == AppLifecycleState.detached, 'Invalid state transition from $previousState to $state');
onResume?.call();
case AppLifecycleState.inactive:
assert(previousState == null || previousState == AppLifecycleState.hidden || previousState == AppLifecycleState.resumed, 'Invalid state transition from $previousState to $state');
if (previousState == AppLifecycleState.hidden) {
onShow?.call();
} else if (previousState == null || previousState == AppLifecycleState.resumed) {
onInactive?.call();
}
case AppLifecycleState.hidden:
assert(previousState == null || previousState == AppLifecycleState.paused || previousState == AppLifecycleState.inactive, 'Invalid state transition from $previousState to $state');
if (previousState == AppLifecycleState.paused) {
onRestart?.call();
} else if (previousState == null || previousState == AppLifecycleState.inactive) {
onHide?.call();
}
case AppLifecycleState.paused:
assert(previousState == null || previousState == AppLifecycleState.hidden, 'Invalid state transition from $previousState to $state');
if (previousState == null || previousState == AppLifecycleState.hidden) {
onPause?.call();
}
case AppLifecycleState.detached:
assert(previousState == null || previousState == AppLifecycleState.paused, 'Invalid state transition from $previousState to $state');
onDetach?.call();
}
// At this point, it can't be null anymore.
onStateChange?.call(_lifecycleState!);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<WidgetsBinding>('binding', binding));
properties.add(FlagProperty('onStateChange', value: onStateChange != null, ifTrue: 'onStateChange'));
properties.add(FlagProperty('onInactive', value: onInactive != null, ifTrue: 'onInactive'));
properties.add(FlagProperty('onResume', value: onResume != null, ifTrue: 'onResume'));
properties.add(FlagProperty('onHide', value: onHide != null, ifTrue: 'onHide'));
properties.add(FlagProperty('onShow', value: onShow != null, ifTrue: 'onShow'));
properties.add(FlagProperty('onPause', value: onPause != null, ifTrue: 'onPause'));
properties.add(FlagProperty('onRestart', value: onRestart != null, ifTrue: 'onRestart'));
properties.add(FlagProperty('onExitRequested', value: onExitRequested != null, ifTrue: 'onExitRequested'));
properties.add(FlagProperty('onDetach', value: onDetach != null, ifTrue: 'onDetach'));
}
}
| flutter/packages/flutter/lib/src/widgets/app_lifecycle_listener.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/app_lifecycle_listener.dart",
"repo_id": "flutter",
"token_count": 3446
} | 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 'basic.dart';
import 'framework.dart';
import 'inherited_theme.dart';
// Examples can assume:
// late BuildContext context;
/// The selection style to apply to descendant [EditableText] widgets which
/// don't have an explicit style.
///
/// {@macro flutter.cupertino.CupertinoApp.defaultSelectionStyle}
///
/// {@macro flutter.material.MaterialApp.defaultSelectionStyle}
///
/// See also:
/// * [TextSelectionTheme]: which also creates a [DefaultSelectionStyle] for
/// the subtree.
class DefaultSelectionStyle extends InheritedTheme {
/// Creates a default selection style widget that specifies the selection
/// properties for all widgets below it in the widget tree.
const DefaultSelectionStyle({
super.key,
this.cursorColor,
this.selectionColor,
this.mouseCursor,
required super.child,
});
/// A const-constructable default selection style that provides fallback
/// values (null).
///
/// Returned from [of] when the given [BuildContext] doesn't have an enclosing
/// default selection style.
///
/// This constructor creates a [DefaultTextStyle] with an invalid [child],
/// which means the constructed value cannot be incorporated into the tree.
const DefaultSelectionStyle.fallback({ super.key })
: cursorColor = null,
selectionColor = null,
mouseCursor = null,
super(child: const _NullWidget());
/// Creates a default selection style that overrides the selection styles in
/// scope at this point in the widget tree.
///
/// Any Arguments that are not null replace the corresponding properties on the
/// default selection style for the [BuildContext] where the widget is inserted.
static Widget merge({
Key? key,
Color? cursorColor,
Color? selectionColor,
MouseCursor? mouseCursor,
required Widget child,
}) {
return Builder(
builder: (BuildContext context) {
final DefaultSelectionStyle parent = DefaultSelectionStyle.of(context);
return DefaultSelectionStyle(
key: key,
cursorColor: cursorColor ?? parent.cursorColor,
selectionColor: selectionColor ?? parent.selectionColor,
mouseCursor: mouseCursor ?? parent.mouseCursor,
child: child,
);
},
);
}
/// The default cursor and selection color (semi-transparent grey).
///
/// This is the color that the [Text] widget uses when the specified selection
/// color is null.
static const Color defaultColor = Color(0x80808080);
/// The color of the text field's cursor.
///
/// The cursor indicates the current location of the text insertion point in
/// the field.
final Color? cursorColor;
/// The background color of selected text.
final Color? selectionColor;
/// The [MouseCursor] for mouse pointers hovering over selectable Text widgets.
///
/// If this property is null, [SystemMouseCursors.text] will be used.
final MouseCursor? mouseCursor;
/// The closest instance of this class that encloses the given context.
///
/// If no such instance exists, returns an instance created by
/// [DefaultSelectionStyle.fallback], which contains fallback values.
///
/// Typical usage is as follows:
///
/// ```dart
/// DefaultSelectionStyle style = DefaultSelectionStyle.of(context);
/// ```
static DefaultSelectionStyle of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DefaultSelectionStyle>() ?? const DefaultSelectionStyle.fallback();
}
@override
Widget wrap(BuildContext context, Widget child) {
return DefaultSelectionStyle(
cursorColor: cursorColor,
selectionColor: selectionColor,
mouseCursor: mouseCursor,
child: child
);
}
@override
bool updateShouldNotify(DefaultSelectionStyle oldWidget) {
return cursorColor != oldWidget.cursorColor ||
selectionColor != oldWidget.selectionColor ||
mouseCursor != oldWidget.mouseCursor;
}
}
class _NullWidget extends StatelessWidget {
const _NullWidget();
@override
Widget build(BuildContext context) {
throw FlutterError(
'A DefaultSelectionStyle constructed with DefaultSelectionStyle.fallback cannot be incorporated into the widget tree, '
'it is meant only to provide a fallback value returned by DefaultSelectionStyle.of() '
'when no enclosing default selection style is present in a BuildContext.',
);
}
}
| flutter/packages/flutter/lib/src/widgets/default_selection_style.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/default_selection_style.dart",
"repo_id": "flutter",
"token_count": 1369
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'basic.dart';
import 'framework.dart';
import 'media_query.dart';
import 'scroll_configuration.dart';
export 'package:flutter/gestures.dart' show
DragDownDetails,
DragEndDetails,
DragStartDetails,
DragUpdateDetails,
ForcePressDetails,
GestureDragCancelCallback,
GestureDragDownCallback,
GestureDragEndCallback,
GestureDragStartCallback,
GestureDragUpdateCallback,
GestureForcePressEndCallback,
GestureForcePressPeakCallback,
GestureForcePressStartCallback,
GestureForcePressUpdateCallback,
GestureLongPressCallback,
GestureLongPressEndCallback,
GestureLongPressMoveUpdateCallback,
GestureLongPressStartCallback,
GestureLongPressUpCallback,
GestureScaleEndCallback,
GestureScaleStartCallback,
GestureScaleUpdateCallback,
GestureTapCallback,
GestureTapCancelCallback,
GestureTapDownCallback,
GestureTapUpCallback,
LongPressEndDetails,
LongPressMoveUpdateDetails,
LongPressStartDetails,
ScaleEndDetails,
ScaleStartDetails,
ScaleUpdateDetails,
TapDownDetails,
TapUpDetails,
Velocity;
export 'package:flutter/rendering.dart' show RenderSemanticsGestureHandler;
// Examples can assume:
// late bool _lights;
// void setState(VoidCallback fn) { }
// late String _last;
// late Color _color;
/// Factory for creating gesture recognizers.
///
/// `T` is the type of gesture recognizer this class manages.
///
/// Used by [RawGestureDetector.gestures].
@optionalTypeArgs
abstract class GestureRecognizerFactory<T extends GestureRecognizer> {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const GestureRecognizerFactory();
/// Must return an instance of T.
T constructor();
/// Must configure the given instance (which will have been created by
/// `constructor`).
///
/// This normally means setting the callbacks.
void initializer(T instance);
bool _debugAssertTypeMatches(Type type) {
assert(type == T, 'GestureRecognizerFactory of type $T was used where type $type was specified.');
return true;
}
}
/// Signature for closures that implement [GestureRecognizerFactory.constructor].
typedef GestureRecognizerFactoryConstructor<T extends GestureRecognizer> = T Function();
/// Signature for closures that implement [GestureRecognizerFactory.initializer].
typedef GestureRecognizerFactoryInitializer<T extends GestureRecognizer> = void Function(T instance);
/// Factory for creating gesture recognizers that delegates to callbacks.
///
/// Used by [RawGestureDetector.gestures].
class GestureRecognizerFactoryWithHandlers<T extends GestureRecognizer> extends GestureRecognizerFactory<T> {
/// Creates a gesture recognizer factory with the given callbacks.
const GestureRecognizerFactoryWithHandlers(this._constructor, this._initializer);
final GestureRecognizerFactoryConstructor<T> _constructor;
final GestureRecognizerFactoryInitializer<T> _initializer;
@override
T constructor() => _constructor();
@override
void initializer(T instance) => _initializer(instance);
}
/// A widget that detects gestures.
///
/// Attempts to recognize gestures that correspond to its non-null callbacks.
///
/// If this widget has a child, it defers to that child for its sizing behavior.
/// If it does not have a child, it grows to fit the parent instead.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=WhVXkCFPmK4}
///
/// By default a GestureDetector with an invisible child ignores touches;
/// this behavior can be controlled with [behavior].
///
/// GestureDetector also listens for accessibility events and maps
/// them to the callbacks. To ignore accessibility events, set
/// [excludeFromSemantics] to true.
///
/// See <http://flutter.dev/gestures/> for additional information.
///
/// Material design applications typically react to touches with ink splash
/// effects. The [InkWell] class implements this effect and can be used in place
/// of a [GestureDetector] for handling taps.
///
/// {@tool dartpad}
/// This example contains a black light bulb wrapped in a [GestureDetector]. It
/// turns the light bulb yellow when the "TURN LIGHT ON" button is tapped by
/// setting the `_lights` field, and off again when "TURN LIGHT OFF" is tapped.
///
/// ** See code in examples/api/lib/widgets/gesture_detector/gesture_detector.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example uses a [Container] that wraps a [GestureDetector] widget which
/// detects a tap.
///
/// Since the [GestureDetector] does not have a child, it takes on the size of its
/// parent, making the entire area of the surrounding [Container] clickable. When
/// tapped, the [Container] turns yellow by setting the `_color` field. When
/// tapped again, it goes back to white.
///
/// ** See code in examples/api/lib/widgets/gesture_detector/gesture_detector.1.dart **
/// {@end-tool}
///
/// ### Troubleshooting
///
/// Why isn't my parent [GestureDetector.onTap] method called?
///
/// Given a parent [GestureDetector] with an onTap callback, and a child
/// GestureDetector that also defines an onTap callback, when the inner
/// GestureDetector is tapped, both GestureDetectors send a [GestureRecognizer]
/// into the gesture arena. This is because the pointer coordinates are within the
/// bounds of both GestureDetectors. The child GestureDetector wins in this
/// scenario because it was the first to enter the arena, resolving as first come,
/// first served. The child onTap is called, and the parent's is not as the gesture has
/// been consumed.
/// For more information on gesture disambiguation see:
/// [Gesture disambiguation](https://docs.flutter.dev/development/ui/advanced/gestures#gesture-disambiguation).
///
/// Setting [GestureDetector.behavior] to [HitTestBehavior.opaque]
/// or [HitTestBehavior.translucent] has no impact on parent-child relationships:
/// both GestureDetectors send a GestureRecognizer into the gesture arena, only one wins.
///
/// Some callbacks (e.g. onTapDown) can fire before a recognizer wins the arena,
/// and others (e.g. onTapCancel) fire even when it loses the arena. Therefore,
/// the parent detector in the example above may call some of its callbacks even
/// though it loses in the arena.
///
/// {@tool dartpad}
/// This example uses a [GestureDetector] that wraps a green [Container] and a second
/// GestureDetector that wraps a yellow Container. The second GestureDetector is
/// a child of the green Container.
/// Both GestureDetectors define an onTap callback. When the callback is called it
/// adds a red border to the corresponding Container.
///
/// When the green Container is tapped, it's parent GestureDetector enters
/// the gesture arena. It wins because there is no competing GestureDetector and
/// the green Container shows a red border.
/// When the yellow Container is tapped, it's parent GestureDetector enters
/// the gesture arena. The GestureDetector that wraps the green Container also
/// enters the gesture arena (the pointer events coordinates are inside both
/// GestureDetectors bounds). The GestureDetector that wraps the yellow Container
/// wins because it was the first detector to enter the arena.
///
/// This example sets [debugPrintGestureArenaDiagnostics] to true.
/// This flag prints useful information about gesture arenas.
///
/// Changing the [GestureDetector.behavior] property to [HitTestBehavior.translucent]
/// or [HitTestBehavior.opaque] has no impact: both GestureDetectors send a [GestureRecognizer]
/// into the gesture arena, only one wins.
///
/// ** See code in examples/api/lib/widgets/gesture_detector/gesture_detector.2.dart **
/// {@end-tool}
///
/// ## Debugging
///
/// To see how large the hit test box of a [GestureDetector] is for debugging
/// purposes, set [debugPaintPointersEnabled] to true.
///
/// See also:
///
/// * [Listener], a widget for listening to lower-level raw pointer events.
/// * [MouseRegion], a widget that tracks the movement of mice, even when no
/// button is pressed.
/// * [RawGestureDetector], a widget that is used to detect custom gestures.
class GestureDetector extends StatelessWidget {
/// Creates a widget that detects gestures.
///
/// Pan and scale callbacks cannot be used simultaneously because scale is a
/// superset of pan. Use the scale callbacks instead.
///
/// Horizontal and vertical drag callbacks cannot be used simultaneously
/// because a combination of a horizontal and vertical drag is a pan.
/// Use the pan callbacks instead.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=WhVXkCFPmK4}
///
/// By default, gesture detectors contribute semantic information to the tree
/// that is used by assistive technology.
GestureDetector({
super.key,
this.child,
this.onTapDown,
this.onTapUp,
this.onTap,
this.onTapCancel,
this.onSecondaryTap,
this.onSecondaryTapDown,
this.onSecondaryTapUp,
this.onSecondaryTapCancel,
this.onTertiaryTapDown,
this.onTertiaryTapUp,
this.onTertiaryTapCancel,
this.onDoubleTapDown,
this.onDoubleTap,
this.onDoubleTapCancel,
this.onLongPressDown,
this.onLongPressCancel,
this.onLongPress,
this.onLongPressStart,
this.onLongPressMoveUpdate,
this.onLongPressUp,
this.onLongPressEnd,
this.onSecondaryLongPressDown,
this.onSecondaryLongPressCancel,
this.onSecondaryLongPress,
this.onSecondaryLongPressStart,
this.onSecondaryLongPressMoveUpdate,
this.onSecondaryLongPressUp,
this.onSecondaryLongPressEnd,
this.onTertiaryLongPressDown,
this.onTertiaryLongPressCancel,
this.onTertiaryLongPress,
this.onTertiaryLongPressStart,
this.onTertiaryLongPressMoveUpdate,
this.onTertiaryLongPressUp,
this.onTertiaryLongPressEnd,
this.onVerticalDragDown,
this.onVerticalDragStart,
this.onVerticalDragUpdate,
this.onVerticalDragEnd,
this.onVerticalDragCancel,
this.onHorizontalDragDown,
this.onHorizontalDragStart,
this.onHorizontalDragUpdate,
this.onHorizontalDragEnd,
this.onHorizontalDragCancel,
this.onForcePressStart,
this.onForcePressPeak,
this.onForcePressUpdate,
this.onForcePressEnd,
this.onPanDown,
this.onPanStart,
this.onPanUpdate,
this.onPanEnd,
this.onPanCancel,
this.onScaleStart,
this.onScaleUpdate,
this.onScaleEnd,
this.behavior,
this.excludeFromSemantics = false,
this.dragStartBehavior = DragStartBehavior.start,
this.trackpadScrollCausesScale = false,
this.trackpadScrollToScaleFactor = kDefaultTrackpadScrollToScaleFactor,
this.supportedDevices,
}) : assert(() {
final bool haveVerticalDrag = onVerticalDragStart != null || onVerticalDragUpdate != null || onVerticalDragEnd != null;
final bool haveHorizontalDrag = onHorizontalDragStart != null || onHorizontalDragUpdate != null || onHorizontalDragEnd != null;
final bool havePan = onPanStart != null || onPanUpdate != null || onPanEnd != null;
final bool haveScale = onScaleStart != null || onScaleUpdate != null || onScaleEnd != null;
if (havePan || haveScale) {
if (havePan && haveScale) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Incorrect GestureDetector arguments.'),
ErrorDescription(
'Having both a pan gesture recognizer and a scale gesture recognizer is redundant; scale is a superset of pan.',
),
ErrorHint('Just use the scale gesture recognizer.'),
]);
}
final String recognizer = havePan ? 'pan' : 'scale';
if (haveVerticalDrag && haveHorizontalDrag) {
throw FlutterError(
'Incorrect GestureDetector arguments.\n'
'Simultaneously having a vertical drag gesture recognizer, a horizontal drag gesture recognizer, and a $recognizer gesture recognizer '
'will result in the $recognizer gesture recognizer being ignored, since the other two will catch all drags.',
);
}
}
return true;
}());
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// A pointer that might cause a tap with a primary button has contacted the
/// screen at a particular location.
///
/// This is called after a short timeout, even if the winning gesture has not
/// yet been selected. If the tap gesture wins, [onTapUp] will be called,
/// otherwise [onTapCancel] will be called.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapDownCallback? onTapDown;
/// A pointer that will trigger a tap with a primary button has stopped
/// contacting the screen at a particular location.
///
/// This triggers immediately before [onTap] in the case of the tap gesture
/// winning. If the tap gesture did not win, [onTapCancel] is called instead.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapUpCallback? onTapUp;
/// A tap with a primary button has occurred.
///
/// This triggers when the tap gesture wins. If the tap gesture did not win,
/// [onTapCancel] is called instead.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [onTapUp], which is called at the same time but includes details
/// regarding the pointer position.
final GestureTapCallback? onTap;
/// The pointer that previously triggered [onTapDown] will not end up causing
/// a tap.
///
/// This is called after [onTapDown], and instead of [onTapUp] and [onTap], if
/// the tap gesture did not win.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapCancelCallback? onTapCancel;
/// A tap with a secondary button has occurred.
///
/// This triggers when the tap gesture wins. If the tap gesture did not win,
/// [onSecondaryTapCancel] is called instead.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [onSecondaryTapUp], which is called at the same time but includes details
/// regarding the pointer position.
final GestureTapCallback? onSecondaryTap;
/// A pointer that might cause a tap with a secondary button has contacted the
/// screen at a particular location.
///
/// This is called after a short timeout, even if the winning gesture has not
/// yet been selected. If the tap gesture wins, [onSecondaryTapUp] will be
/// called, otherwise [onSecondaryTapCancel] will be called.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
final GestureTapDownCallback? onSecondaryTapDown;
/// A pointer that will trigger a tap with a secondary button has stopped
/// contacting the screen at a particular location.
///
/// This triggers in the case of the tap gesture winning. If the tap gesture
/// did not win, [onSecondaryTapCancel] is called instead.
///
/// See also:
///
/// * [onSecondaryTap], a handler triggered right after this one that doesn't
/// pass any details about the tap.
/// * [kSecondaryButton], the button this callback responds to.
final GestureTapUpCallback? onSecondaryTapUp;
/// The pointer that previously triggered [onSecondaryTapDown] will not end up
/// causing a tap.
///
/// This is called after [onSecondaryTapDown], and instead of
/// [onSecondaryTapUp], if the tap gesture did not win.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
final GestureTapCancelCallback? onSecondaryTapCancel;
/// A pointer that might cause a tap with a tertiary button has contacted the
/// screen at a particular location.
///
/// This is called after a short timeout, even if the winning gesture has not
/// yet been selected. If the tap gesture wins, [onTertiaryTapUp] will be
/// called, otherwise [onTertiaryTapCancel] will be called.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
final GestureTapDownCallback? onTertiaryTapDown;
/// A pointer that will trigger a tap with a tertiary button has stopped
/// contacting the screen at a particular location.
///
/// This triggers in the case of the tap gesture winning. If the tap gesture
/// did not win, [onTertiaryTapCancel] is called instead.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
final GestureTapUpCallback? onTertiaryTapUp;
/// The pointer that previously triggered [onTertiaryTapDown] will not end up
/// causing a tap.
///
/// This is called after [onTertiaryTapDown], and instead of
/// [onTertiaryTapUp], if the tap gesture did not win.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
final GestureTapCancelCallback? onTertiaryTapCancel;
/// A pointer that might cause a double tap has contacted the screen at a
/// particular location.
///
/// Triggered immediately after the down event of the second tap.
///
/// If the user completes the double tap and the gesture wins, [onDoubleTap]
/// will be called after this callback. Otherwise, [onDoubleTapCancel] will
/// be called after this callback.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapDownCallback? onDoubleTapDown;
/// The user has tapped the screen with a primary button at the same location
/// twice in quick succession.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapCallback? onDoubleTap;
/// The pointer that previously triggered [onDoubleTapDown] will not end up
/// causing a double tap.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapCancelCallback? onDoubleTapCancel;
/// The pointer has contacted the screen with a primary button, which might
/// be the start of a long-press.
///
/// This triggers after the pointer down event.
///
/// If the user completes the long-press, and this gesture wins,
/// [onLongPressStart] will be called after this callback. Otherwise,
/// [onLongPressCancel] will be called after this callback.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [onSecondaryLongPressDown], a similar callback but for a secondary button.
/// * [onTertiaryLongPressDown], a similar callback but for a tertiary button.
/// * [LongPressGestureRecognizer.onLongPressDown], which exposes this
/// callback at the gesture layer.
final GestureLongPressDownCallback? onLongPressDown;
/// A pointer that previously triggered [onLongPressDown] will not end up
/// causing a long-press.
///
/// This triggers once the gesture loses if [onLongPressDown] has previously
/// been triggered.
///
/// If the user completed the long-press, and the gesture won, then
/// [onLongPressStart] and [onLongPress] are called instead.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressCancel], which exposes this
/// callback at the gesture layer.
final GestureLongPressCancelCallback? onLongPressCancel;
/// Called when a long press gesture with a primary button has been recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately after) [onLongPressStart].
/// The only difference between the two is that this callback does not
/// contain details of the position at which the pointer initially contacted
/// the screen.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPress], which exposes this
/// callback at the gesture layer.
final GestureLongPressCallback? onLongPress;
/// Called when a long press gesture with a primary button has been recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately before) [onLongPress].
/// The only difference between the two is that this callback contains
/// details of the position at which the pointer initially contacted the
/// screen, whereas [onLongPress] does not.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressStart], which exposes this
/// callback at the gesture layer.
final GestureLongPressStartCallback? onLongPressStart;
/// A pointer has been drag-moved after a long-press with a primary button.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressMoveUpdate], which exposes this
/// callback at the gesture layer.
final GestureLongPressMoveUpdateCallback? onLongPressMoveUpdate;
/// A pointer that has triggered a long-press with a primary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately after) [onLongPressEnd].
/// The only difference between the two is that this callback does not
/// contain details of the state of the pointer when it stopped contacting
/// the screen.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressUp], which exposes this
/// callback at the gesture layer.
final GestureLongPressUpCallback? onLongPressUp;
/// A pointer that has triggered a long-press with a primary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately before) [onLongPressUp].
/// The only difference between the two is that this callback contains
/// details of the state of the pointer when it stopped contacting the
/// screen, whereas [onLongPressUp] does not.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressEnd], which exposes this
/// callback at the gesture layer.
final GestureLongPressEndCallback? onLongPressEnd;
/// The pointer has contacted the screen with a secondary button, which might
/// be the start of a long-press.
///
/// This triggers after the pointer down event.
///
/// If the user completes the long-press, and this gesture wins,
/// [onSecondaryLongPressStart] will be called after this callback. Otherwise,
/// [onSecondaryLongPressCancel] will be called after this callback.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [onLongPressDown], a similar callback but for a secondary button.
/// * [onTertiaryLongPressDown], a similar callback but for a tertiary button.
/// * [LongPressGestureRecognizer.onSecondaryLongPressDown], which exposes
/// this callback at the gesture layer.
final GestureLongPressDownCallback? onSecondaryLongPressDown;
/// A pointer that previously triggered [onSecondaryLongPressDown] will not
/// end up causing a long-press.
///
/// This triggers once the gesture loses if [onSecondaryLongPressDown] has
/// previously been triggered.
///
/// If the user completed the long-press, and the gesture won, then
/// [onSecondaryLongPressStart] and [onSecondaryLongPress] are called instead.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressCancel], which exposes
/// this callback at the gesture layer.
final GestureLongPressCancelCallback? onSecondaryLongPressCancel;
/// Called when a long press gesture with a secondary button has been
/// recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately after)
/// [onSecondaryLongPressStart]. The only difference between the two is that
/// this callback does not contain details of the position at which the
/// pointer initially contacted the screen.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPress], which exposes
/// this callback at the gesture layer.
final GestureLongPressCallback? onSecondaryLongPress;
/// Called when a long press gesture with a secondary button has been
/// recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately before)
/// [onSecondaryLongPress]. The only difference between the two is that this
/// callback contains details of the position at which the pointer initially
/// contacted the screen, whereas [onSecondaryLongPress] does not.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressStart], which exposes
/// this callback at the gesture layer.
final GestureLongPressStartCallback? onSecondaryLongPressStart;
/// A pointer has been drag-moved after a long press with a secondary button.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressMoveUpdate], which exposes
/// this callback at the gesture layer.
final GestureLongPressMoveUpdateCallback? onSecondaryLongPressMoveUpdate;
/// A pointer that has triggered a long-press with a secondary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately after)
/// [onSecondaryLongPressEnd]. The only difference between the two is that
/// this callback does not contain details of the state of the pointer when
/// it stopped contacting the screen.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressUp], which exposes
/// this callback at the gesture layer.
final GestureLongPressUpCallback? onSecondaryLongPressUp;
/// A pointer that has triggered a long-press with a secondary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately before)
/// [onSecondaryLongPressUp]. The only difference between the two is that
/// this callback contains details of the state of the pointer when it
/// stopped contacting the screen, whereas [onSecondaryLongPressUp] does not.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressEnd], which exposes
/// this callback at the gesture layer.
final GestureLongPressEndCallback? onSecondaryLongPressEnd;
/// The pointer has contacted the screen with a tertiary button, which might
/// be the start of a long-press.
///
/// This triggers after the pointer down event.
///
/// If the user completes the long-press, and this gesture wins,
/// [onTertiaryLongPressStart] will be called after this callback. Otherwise,
/// [onTertiaryLongPressCancel] will be called after this callback.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [onLongPressDown], a similar callback but for a primary button.
/// * [onSecondaryLongPressDown], a similar callback but for a secondary button.
/// * [LongPressGestureRecognizer.onTertiaryLongPressDown], which exposes
/// this callback at the gesture layer.
final GestureLongPressDownCallback? onTertiaryLongPressDown;
/// A pointer that previously triggered [onTertiaryLongPressDown] will not
/// end up causing a long-press.
///
/// This triggers once the gesture loses if [onTertiaryLongPressDown] has
/// previously been triggered.
///
/// If the user completed the long-press, and the gesture won, then
/// [onTertiaryLongPressStart] and [onTertiaryLongPress] are called instead.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressCancel], which exposes
/// this callback at the gesture layer.
final GestureLongPressCancelCallback? onTertiaryLongPressCancel;
/// Called when a long press gesture with a tertiary button has been
/// recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately after)
/// [onTertiaryLongPressStart]. The only difference between the two is that
/// this callback does not contain details of the position at which the
/// pointer initially contacted the screen.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPress], which exposes
/// this callback at the gesture layer.
final GestureLongPressCallback? onTertiaryLongPress;
/// Called when a long press gesture with a tertiary button has been
/// recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately before)
/// [onTertiaryLongPress]. The only difference between the two is that this
/// callback contains details of the position at which the pointer initially
/// contacted the screen, whereas [onTertiaryLongPress] does not.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressStart], which exposes
/// this callback at the gesture layer.
final GestureLongPressStartCallback? onTertiaryLongPressStart;
/// A pointer has been drag-moved after a long press with a tertiary button.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressMoveUpdate], which exposes
/// this callback at the gesture layer.
final GestureLongPressMoveUpdateCallback? onTertiaryLongPressMoveUpdate;
/// A pointer that has triggered a long-press with a tertiary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately after)
/// [onTertiaryLongPressEnd]. The only difference between the two is that
/// this callback does not contain details of the state of the pointer when
/// it stopped contacting the screen.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressUp], which exposes
/// this callback at the gesture layer.
final GestureLongPressUpCallback? onTertiaryLongPressUp;
/// A pointer that has triggered a long-press with a tertiary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately before)
/// [onTertiaryLongPressUp]. The only difference between the two is that
/// this callback contains details of the state of the pointer when it
/// stopped contacting the screen, whereas [onTertiaryLongPressUp] does not.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressEnd], which exposes
/// this callback at the gesture layer.
final GestureLongPressEndCallback? onTertiaryLongPressEnd;
/// A pointer has contacted the screen with a primary button and might begin
/// to move vertically.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragDownCallback? onVerticalDragDown;
/// A pointer has contacted the screen with a primary button and has begun to
/// move vertically.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragStartCallback? onVerticalDragStart;
/// A pointer that is in contact with the screen with a primary button and
/// moving vertically has moved in the vertical direction.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragUpdateCallback? onVerticalDragUpdate;
/// A pointer that was previously in contact with the screen with a primary
/// button and moving vertically is no longer in contact with the screen and
/// was moving at a specific velocity when it stopped contacting the screen.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragEndCallback? onVerticalDragEnd;
/// The pointer that previously triggered [onVerticalDragDown] did not
/// complete.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragCancelCallback? onVerticalDragCancel;
/// A pointer has contacted the screen with a primary button and might begin
/// to move horizontally.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragDownCallback? onHorizontalDragDown;
/// A pointer has contacted the screen with a primary button and has begun to
/// move horizontally.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragStartCallback? onHorizontalDragStart;
/// A pointer that is in contact with the screen with a primary button and
/// moving horizontally has moved in the horizontal direction.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragUpdateCallback? onHorizontalDragUpdate;
/// A pointer that was previously in contact with the screen with a primary
/// button and moving horizontally is no longer in contact with the screen and
/// was moving at a specific velocity when it stopped contacting the screen.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragEndCallback? onHorizontalDragEnd;
/// The pointer that previously triggered [onHorizontalDragDown] did not
/// complete.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragCancelCallback? onHorizontalDragCancel;
/// A pointer has contacted the screen with a primary button and might begin
/// to move.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragDownCallback? onPanDown;
/// A pointer has contacted the screen with a primary button and has begun to
/// move.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragStartCallback? onPanStart;
/// A pointer that is in contact with the screen with a primary button and
/// moving has moved again.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragUpdateCallback? onPanUpdate;
/// 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.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragEndCallback? onPanEnd;
/// The pointer that previously triggered [onPanDown] did not complete.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragCancelCallback? onPanCancel;
/// The pointers in contact with the screen have established a focal point and
/// initial scale of 1.0.
final GestureScaleStartCallback? onScaleStart;
/// The pointers in contact with the screen have indicated a new focal point
/// and/or scale.
final GestureScaleUpdateCallback? onScaleUpdate;
/// The pointers are no longer in contact with the screen.
final GestureScaleEndCallback? onScaleEnd;
/// The pointer is in contact with the screen and has pressed with sufficient
/// force to initiate a force press. The amount of force is at least
/// [ForcePressGestureRecognizer.startPressure].
///
/// This callback will only be fired on devices with pressure
/// detecting screens.
final GestureForcePressStartCallback? onForcePressStart;
/// The pointer is in contact with the screen and has pressed with the maximum
/// force. The amount of force is at least
/// [ForcePressGestureRecognizer.peakPressure].
///
/// This callback will only be fired on devices with pressure
/// detecting screens.
final GestureForcePressPeakCallback? onForcePressPeak;
/// A pointer is in contact with the screen, has previously passed the
/// [ForcePressGestureRecognizer.startPressure] and is either moving on the
/// plane of the screen, pressing the screen with varying forces or both
/// simultaneously.
///
/// This callback will only be fired on devices with pressure
/// detecting screens.
final GestureForcePressUpdateCallback? onForcePressUpdate;
/// The pointer tracked by [onForcePressStart] is no longer in contact with the screen.
///
/// This callback will only be fired on devices with pressure
/// detecting screens.
final GestureForcePressEndCallback? onForcePressEnd;
/// How this gesture detector should behave during hit testing when deciding
/// how the hit test propagates to children and whether to consider targets
/// behind this one.
///
/// This defaults to [HitTestBehavior.deferToChild] if [child] is not null and
/// [HitTestBehavior.translucent] if child is null.
///
/// See [HitTestBehavior] for the allowed values and their meanings.
final HitTestBehavior? behavior;
/// Whether to exclude these gestures from the semantics tree. For
/// example, the long-press gesture for showing a tooltip is
/// excluded because the tooltip itself is included in the semantics
/// tree directly and so having a gesture to show it would result in
/// duplication of information.
final bool excludeFromSemantics;
/// Determines the way that drag start behavior is handled.
///
/// If set to [DragStartBehavior.start], gesture drag behavior will
/// begin at the position where the drag gesture won the arena. If set to
/// [DragStartBehavior.down] it will begin at the position where a down event
/// is first detected.
///
/// In general, setting this to [DragStartBehavior.start] will make drag
/// animation smoother and setting it to [DragStartBehavior.down] will make
/// drag behavior feel slightly more reactive.
///
/// By default, the drag start behavior is [DragStartBehavior.start].
///
/// Only the [DragGestureRecognizer.onStart] callbacks for the
/// [VerticalDragGestureRecognizer], [HorizontalDragGestureRecognizer] and
/// [PanGestureRecognizer] are affected by this setting.
///
/// See also:
///
/// * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors.
final DragStartBehavior dragStartBehavior;
/// The kind of devices that are allowed to be recognized.
///
/// If set to null, events from all device types will be recognized. Defaults to null.
final Set<PointerDeviceKind>? supportedDevices;
/// {@macro flutter.gestures.scale.trackpadScrollCausesScale}
final bool trackpadScrollCausesScale;
/// {@macro flutter.gestures.scale.trackpadScrollToScaleFactor}
final Offset trackpadScrollToScaleFactor;
@override
Widget build(BuildContext context) {
final Map<Type, GestureRecognizerFactory> gestures = <Type, GestureRecognizerFactory>{};
final DeviceGestureSettings? gestureSettings = MediaQuery.maybeGestureSettingsOf(context);
final ScrollBehavior configuration = ScrollConfiguration.of(context);
if (onTapDown != null ||
onTapUp != null ||
onTap != null ||
onTapCancel != null ||
onSecondaryTap != null ||
onSecondaryTapDown != null ||
onSecondaryTapUp != null ||
onSecondaryTapCancel != null||
onTertiaryTapDown != null ||
onTertiaryTapUp != null ||
onTertiaryTapCancel != null
) {
gestures[TapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
() => TapGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(TapGestureRecognizer instance) {
instance
..onTapDown = onTapDown
..onTapUp = onTapUp
..onTap = onTap
..onTapCancel = onTapCancel
..onSecondaryTap = onSecondaryTap
..onSecondaryTapDown = onSecondaryTapDown
..onSecondaryTapUp = onSecondaryTapUp
..onSecondaryTapCancel = onSecondaryTapCancel
..onTertiaryTapDown = onTertiaryTapDown
..onTertiaryTapUp = onTertiaryTapUp
..onTertiaryTapCancel = onTertiaryTapCancel
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onDoubleTap != null ||
onDoubleTapDown != null ||
onDoubleTapCancel != null) {
gestures[DoubleTapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<DoubleTapGestureRecognizer>(
() => DoubleTapGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(DoubleTapGestureRecognizer instance) {
instance
..onDoubleTapDown = onDoubleTapDown
..onDoubleTap = onDoubleTap
..onDoubleTapCancel = onDoubleTapCancel
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onLongPressDown != null ||
onLongPressCancel != null ||
onLongPress != null ||
onLongPressStart != null ||
onLongPressMoveUpdate != null ||
onLongPressUp != null ||
onLongPressEnd != null ||
onSecondaryLongPressDown != null ||
onSecondaryLongPressCancel != null ||
onSecondaryLongPress != null ||
onSecondaryLongPressStart != null ||
onSecondaryLongPressMoveUpdate != null ||
onSecondaryLongPressUp != null ||
onSecondaryLongPressEnd != null ||
onTertiaryLongPressDown != null ||
onTertiaryLongPressCancel != null ||
onTertiaryLongPress != null ||
onTertiaryLongPressStart != null ||
onTertiaryLongPressMoveUpdate != null ||
onTertiaryLongPressUp != null ||
onTertiaryLongPressEnd != null) {
gestures[LongPressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
() => LongPressGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(LongPressGestureRecognizer instance) {
instance
..onLongPressDown = onLongPressDown
..onLongPressCancel = onLongPressCancel
..onLongPress = onLongPress
..onLongPressStart = onLongPressStart
..onLongPressMoveUpdate = onLongPressMoveUpdate
..onLongPressUp = onLongPressUp
..onLongPressEnd = onLongPressEnd
..onSecondaryLongPressDown = onSecondaryLongPressDown
..onSecondaryLongPressCancel = onSecondaryLongPressCancel
..onSecondaryLongPress = onSecondaryLongPress
..onSecondaryLongPressStart = onSecondaryLongPressStart
..onSecondaryLongPressMoveUpdate = onSecondaryLongPressMoveUpdate
..onSecondaryLongPressUp = onSecondaryLongPressUp
..onSecondaryLongPressEnd = onSecondaryLongPressEnd
..onTertiaryLongPressDown = onTertiaryLongPressDown
..onTertiaryLongPressCancel = onTertiaryLongPressCancel
..onTertiaryLongPress = onTertiaryLongPress
..onTertiaryLongPressStart = onTertiaryLongPressStart
..onTertiaryLongPressMoveUpdate = onTertiaryLongPressMoveUpdate
..onTertiaryLongPressUp = onTertiaryLongPressUp
..onTertiaryLongPressEnd = onTertiaryLongPressEnd
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onVerticalDragDown != null ||
onVerticalDragStart != null ||
onVerticalDragUpdate != null ||
onVerticalDragEnd != null ||
onVerticalDragCancel != null) {
gestures[VerticalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<VerticalDragGestureRecognizer>(
() => VerticalDragGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(VerticalDragGestureRecognizer instance) {
instance
..onDown = onVerticalDragDown
..onStart = onVerticalDragStart
..onUpdate = onVerticalDragUpdate
..onEnd = onVerticalDragEnd
..onCancel = onVerticalDragCancel
..dragStartBehavior = dragStartBehavior
..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context)
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onHorizontalDragDown != null ||
onHorizontalDragStart != null ||
onHorizontalDragUpdate != null ||
onHorizontalDragEnd != null ||
onHorizontalDragCancel != null) {
gestures[HorizontalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>(
() => HorizontalDragGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(HorizontalDragGestureRecognizer instance) {
instance
..onDown = onHorizontalDragDown
..onStart = onHorizontalDragStart
..onUpdate = onHorizontalDragUpdate
..onEnd = onHorizontalDragEnd
..onCancel = onHorizontalDragCancel
..dragStartBehavior = dragStartBehavior
..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context)
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onPanDown != null ||
onPanStart != null ||
onPanUpdate != null ||
onPanEnd != null ||
onPanCancel != null) {
gestures[PanGestureRecognizer] = GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
() => PanGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(PanGestureRecognizer instance) {
instance
..onDown = onPanDown
..onStart = onPanStart
..onUpdate = onPanUpdate
..onEnd = onPanEnd
..onCancel = onPanCancel
..dragStartBehavior = dragStartBehavior
..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context)
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onScaleStart != null || onScaleUpdate != null || onScaleEnd != null) {
gestures[ScaleGestureRecognizer] = GestureRecognizerFactoryWithHandlers<ScaleGestureRecognizer>(
() => ScaleGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(ScaleGestureRecognizer instance) {
instance
..onStart = onScaleStart
..onUpdate = onScaleUpdate
..onEnd = onScaleEnd
..dragStartBehavior = dragStartBehavior
..gestureSettings = gestureSettings
..trackpadScrollCausesScale = trackpadScrollCausesScale
..trackpadScrollToScaleFactor = trackpadScrollToScaleFactor
..supportedDevices = supportedDevices;
},
);
}
if (onForcePressStart != null ||
onForcePressPeak != null ||
onForcePressUpdate != null ||
onForcePressEnd != null) {
gestures[ForcePressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<ForcePressGestureRecognizer>(
() => ForcePressGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(ForcePressGestureRecognizer instance) {
instance
..onStart = onForcePressStart
..onPeak = onForcePressPeak
..onUpdate = onForcePressUpdate
..onEnd = onForcePressEnd
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
return RawGestureDetector(
gestures: gestures,
behavior: behavior,
excludeFromSemantics: excludeFromSemantics,
child: child,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<DragStartBehavior>('startBehavior', dragStartBehavior));
}
}
/// A widget that detects gestures described by the given gesture
/// factories.
///
/// For common gestures, use a [GestureDetector].
/// [RawGestureDetector] is useful primarily when developing your
/// own gesture recognizers.
///
/// Configuring the gesture recognizers requires a carefully constructed map, as
/// described in [gestures] and as shown in the example below.
///
/// {@tool snippet}
///
/// This example shows how to hook up a [TapGestureRecognizer]. It assumes that
/// the code is being used inside a [State] object with a `_last` field that is
/// then displayed as the child of the gesture detector.
///
/// ```dart
/// RawGestureDetector(
/// gestures: <Type, GestureRecognizerFactory>{
/// TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
/// () => TapGestureRecognizer(),
/// (TapGestureRecognizer instance) {
/// instance
/// ..onTapDown = (TapDownDetails details) { setState(() { _last = 'down'; }); }
/// ..onTapUp = (TapUpDetails details) { setState(() { _last = 'up'; }); }
/// ..onTap = () { setState(() { _last = 'tap'; }); }
/// ..onTapCancel = () { setState(() { _last = 'cancel'; }); };
/// },
/// ),
/// },
/// child: Container(width: 300.0, height: 300.0, color: Colors.yellow, child: Text(_last)),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [GestureDetector], a less flexible but much simpler widget that does the same thing.
/// * [Listener], a widget that reports raw pointer events.
/// * [GestureRecognizer], the class that you extend to create a custom gesture recognizer.
class RawGestureDetector extends StatefulWidget {
/// Creates a widget that detects gestures.
///
/// Gesture detectors can contribute semantic information to the tree that is
/// used by assistive technology. The behavior can be configured by
/// [semantics], or disabled with [excludeFromSemantics].
const RawGestureDetector({
super.key,
this.child,
this.gestures = const <Type, GestureRecognizerFactory>{},
this.behavior,
this.excludeFromSemantics = false,
this.semantics,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// The gestures that this widget will attempt to recognize.
///
/// This should be a map from [GestureRecognizer] subclasses to
/// [GestureRecognizerFactory] subclasses specialized with the same type.
///
/// This value can be late-bound at layout time using
/// [RawGestureDetectorState.replaceGestureRecognizers].
final Map<Type, GestureRecognizerFactory> gestures;
/// How this gesture detector should behave during hit testing.
///
/// This defaults to [HitTestBehavior.deferToChild] if [child] is not null and
/// [HitTestBehavior.translucent] if child is null.
final HitTestBehavior? behavior;
/// Whether to exclude these gestures from the semantics tree. For
/// example, the long-press gesture for showing a tooltip is
/// excluded because the tooltip itself is included in the semantics
/// tree directly and so having a gesture to show it would result in
/// duplication of information.
final bool excludeFromSemantics;
/// Describes the semantics notations that should be added to the underlying
/// render object [RenderSemanticsGestureHandler].
///
/// It has no effect if [excludeFromSemantics] is true.
///
/// When [semantics] is null, [RawGestureDetector] will fall back to a
/// default delegate which checks if the detector owns certain gesture
/// recognizers and calls their callbacks if they exist:
///
/// * During a semantic tap, it calls [TapGestureRecognizer]'s
/// `onTapDown`, `onTapUp`, and `onTap`.
/// * During a semantic long press, it calls [LongPressGestureRecognizer]'s
/// `onLongPressDown`, `onLongPressStart`, `onLongPress`, `onLongPressEnd`
/// and `onLongPressUp`.
/// * During a semantic horizontal drag, it calls [HorizontalDragGestureRecognizer]'s
/// `onDown`, `onStart`, `onUpdate` and `onEnd`, then
/// [PanGestureRecognizer]'s `onDown`, `onStart`, `onUpdate` and `onEnd`.
/// * During a semantic vertical drag, it calls [VerticalDragGestureRecognizer]'s
/// `onDown`, `onStart`, `onUpdate` and `onEnd`, then
/// [PanGestureRecognizer]'s `onDown`, `onStart`, `onUpdate` and `onEnd`.
///
/// {@tool snippet}
/// This custom gesture detector listens to force presses, while also allows
/// the same callback to be triggered by semantic long presses.
///
/// ```dart
/// class ForcePressGestureDetectorWithSemantics extends StatelessWidget {
/// const ForcePressGestureDetectorWithSemantics({
/// super.key,
/// required this.child,
/// required this.onForcePress,
/// });
///
/// final Widget child;
/// final VoidCallback onForcePress;
///
/// @override
/// Widget build(BuildContext context) {
/// return RawGestureDetector(
/// gestures: <Type, GestureRecognizerFactory>{
/// ForcePressGestureRecognizer: GestureRecognizerFactoryWithHandlers<ForcePressGestureRecognizer>(
/// () => ForcePressGestureRecognizer(debugOwner: this),
/// (ForcePressGestureRecognizer instance) {
/// instance.onStart = (_) => onForcePress();
/// }
/// ),
/// },
/// behavior: HitTestBehavior.opaque,
/// semantics: _LongPressSemanticsDelegate(onForcePress),
/// child: child,
/// );
/// }
/// }
///
/// class _LongPressSemanticsDelegate extends SemanticsGestureDelegate {
/// _LongPressSemanticsDelegate(this.onLongPress);
///
/// VoidCallback onLongPress;
///
/// @override
/// void assignSemantics(RenderSemanticsGestureHandler renderObject) {
/// renderObject.onLongPress = onLongPress;
/// }
/// }
/// ```
/// {@end-tool}
final SemanticsGestureDelegate? semantics;
@override
RawGestureDetectorState createState() => RawGestureDetectorState();
}
/// State for a [RawGestureDetector].
class RawGestureDetectorState extends State<RawGestureDetector> {
Map<Type, GestureRecognizer>? _recognizers = const <Type, GestureRecognizer>{};
SemanticsGestureDelegate? _semantics;
@override
void initState() {
super.initState();
_semantics = widget.semantics ?? _DefaultSemanticsGestureDelegate(this);
_syncAll(widget.gestures);
}
@override
void didUpdateWidget(RawGestureDetector oldWidget) {
super.didUpdateWidget(oldWidget);
if (!(oldWidget.semantics == null && widget.semantics == null)) {
_semantics = widget.semantics ?? _DefaultSemanticsGestureDelegate(this);
}
_syncAll(widget.gestures);
}
/// This method can be called after the build phase, during the
/// layout of the nearest descendant [RenderObjectWidget] of the
/// gesture detector, to update the list of active gesture
/// recognizers.
///
/// The typical use case is [Scrollable]s, which put their viewport
/// in their gesture detector, and then need to know the dimensions
/// of the viewport and the viewport's child to determine whether
/// the gesture detector should be enabled.
///
/// The argument should follow the same conventions as
/// [RawGestureDetector.gestures]. It acts like a temporary replacement for
/// that value until the next build.
void replaceGestureRecognizers(Map<Type, GestureRecognizerFactory> gestures) {
assert(() {
if (!context.findRenderObject()!.owner!.debugDoingLayout) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Unexpected call to replaceGestureRecognizers() method of RawGestureDetectorState.'),
ErrorDescription('The replaceGestureRecognizers() method can only be called during the layout phase.'),
ErrorHint(
'To set the gesture recognizers at other times, trigger a new build using setState() '
'and provide the new gesture recognizers as constructor arguments to the corresponding '
'RawGestureDetector or GestureDetector object.',
),
]);
}
return true;
}());
_syncAll(gestures);
if (!widget.excludeFromSemantics) {
final RenderSemanticsGestureHandler semanticsGestureHandler = context.findRenderObject()! as RenderSemanticsGestureHandler;
_updateSemanticsForRenderObject(semanticsGestureHandler);
}
}
/// This method can be called to filter the list of available semantic actions,
/// after the render object was created.
///
/// The actual filtering is happening in the next frame and a frame will be
/// scheduled if non is pending.
///
/// This is used by [Scrollable] to configure system accessibility tools so
/// that they know in which direction a particular list can be scrolled.
///
/// If this is never called, then the actions are not filtered. If the list of
/// actions to filter changes, it must be called again.
void replaceSemanticsActions(Set<SemanticsAction> actions) {
if (widget.excludeFromSemantics) {
return;
}
final RenderSemanticsGestureHandler? semanticsGestureHandler = context.findRenderObject() as RenderSemanticsGestureHandler?;
assert(() {
if (semanticsGestureHandler == null) {
throw FlutterError(
'Unexpected call to replaceSemanticsActions() method of RawGestureDetectorState.\n'
'The replaceSemanticsActions() method can only be called after the RenderSemanticsGestureHandler has been created.',
);
}
return true;
}());
semanticsGestureHandler!.validActions = actions; // will call _markNeedsSemanticsUpdate(), if required.
}
@override
void dispose() {
for (final GestureRecognizer recognizer in _recognizers!.values) {
recognizer.dispose();
}
_recognizers = null;
super.dispose();
}
void _syncAll(Map<Type, GestureRecognizerFactory> gestures) {
assert(_recognizers != null);
final Map<Type, GestureRecognizer> oldRecognizers = _recognizers!;
_recognizers = <Type, GestureRecognizer>{};
for (final Type type in gestures.keys) {
assert(gestures[type] != null);
assert(gestures[type]!._debugAssertTypeMatches(type));
assert(!_recognizers!.containsKey(type));
_recognizers![type] = oldRecognizers[type] ?? gestures[type]!.constructor();
assert(_recognizers![type].runtimeType == type, 'GestureRecognizerFactory of type $type created a GestureRecognizer of type ${_recognizers![type].runtimeType}. The GestureRecognizerFactory must be specialized with the type of the class that it returns from its constructor method.');
gestures[type]!.initializer(_recognizers![type]!);
}
for (final Type type in oldRecognizers.keys) {
if (!_recognizers!.containsKey(type)) {
oldRecognizers[type]!.dispose();
}
}
}
void _handlePointerDown(PointerDownEvent event) {
assert(_recognizers != null);
for (final GestureRecognizer recognizer in _recognizers!.values) {
recognizer.addPointer(event);
}
}
void _handlePointerPanZoomStart(PointerPanZoomStartEvent event) {
assert(_recognizers != null);
for (final GestureRecognizer recognizer in _recognizers!.values) {
recognizer.addPointerPanZoom(event);
}
}
HitTestBehavior get _defaultBehavior {
return widget.child == null ? HitTestBehavior.translucent : HitTestBehavior.deferToChild;
}
void _updateSemanticsForRenderObject(RenderSemanticsGestureHandler renderObject) {
assert(!widget.excludeFromSemantics);
assert(_semantics != null);
_semantics!.assignSemantics(renderObject);
}
@override
Widget build(BuildContext context) {
Widget result = Listener(
onPointerDown: _handlePointerDown,
onPointerPanZoomStart: _handlePointerPanZoomStart,
behavior: widget.behavior ?? _defaultBehavior,
child: widget.child,
);
if (!widget.excludeFromSemantics) {
result = _GestureSemantics(
behavior: widget.behavior ?? _defaultBehavior,
assignSemantics: _updateSemanticsForRenderObject,
child: result,
);
}
return result;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
if (_recognizers == null) {
properties.add(DiagnosticsNode.message('DISPOSED'));
} else {
final List<String> gestures = _recognizers!.values.map<String>((GestureRecognizer recognizer) => recognizer.debugDescription).toList();
properties.add(IterableProperty<String>('gestures', gestures, ifEmpty: '<none>'));
properties.add(IterableProperty<GestureRecognizer>('recognizers', _recognizers!.values, level: DiagnosticLevel.fine));
properties.add(DiagnosticsProperty<bool>('excludeFromSemantics', widget.excludeFromSemantics, defaultValue: false));
if (!widget.excludeFromSemantics) {
properties.add(DiagnosticsProperty<SemanticsGestureDelegate>('semantics', widget.semantics, defaultValue: null));
}
}
properties.add(EnumProperty<HitTestBehavior>('behavior', widget.behavior, defaultValue: null));
}
}
typedef _AssignSemantics = void Function(RenderSemanticsGestureHandler);
class _GestureSemantics extends SingleChildRenderObjectWidget {
const _GestureSemantics({
super.child,
required this.behavior,
required this.assignSemantics,
});
final HitTestBehavior behavior;
final _AssignSemantics assignSemantics;
@override
RenderSemanticsGestureHandler createRenderObject(BuildContext context) {
final RenderSemanticsGestureHandler renderObject = RenderSemanticsGestureHandler()
..behavior = behavior;
assignSemantics(renderObject);
return renderObject;
}
@override
void updateRenderObject(BuildContext context, RenderSemanticsGestureHandler renderObject) {
renderObject.behavior = behavior;
assignSemantics(renderObject);
}
}
/// A base class that describes what semantics notations a [RawGestureDetector]
/// should add to the render object [RenderSemanticsGestureHandler].
///
/// It is used to allow custom [GestureDetector]s to add semantics notations.
abstract class SemanticsGestureDelegate {
/// Create a delegate of gesture semantics.
const SemanticsGestureDelegate();
/// Assigns semantics notations to the [RenderSemanticsGestureHandler] render
/// object of the gesture detector.
///
/// This method is called when the widget is created, updated, or during
/// [RawGestureDetectorState.replaceGestureRecognizers].
void assignSemantics(RenderSemanticsGestureHandler renderObject);
@override
String toString() => '${objectRuntimeType(this, 'SemanticsGestureDelegate')}()';
}
// The default semantics delegate of [RawGestureDetector]. Its behavior is
// described in [RawGestureDetector.semantics].
//
// For readers who come here to learn how to write custom semantics delegates:
// this is not a proper sample code. It has access to the detector state as well
// as its private properties, which are inaccessible normally. It is designed
// this way in order to work independently in a [RawGestureRecognizer] to
// preserve existing behavior.
//
// Instead, a normal delegate will store callbacks as properties, and use them
// in `assignSemantics`.
class _DefaultSemanticsGestureDelegate extends SemanticsGestureDelegate {
_DefaultSemanticsGestureDelegate(this.detectorState);
final RawGestureDetectorState detectorState;
@override
void assignSemantics(RenderSemanticsGestureHandler renderObject) {
assert(!detectorState.widget.excludeFromSemantics);
final Map<Type, GestureRecognizer> recognizers = detectorState._recognizers!;
renderObject
..onTap = _getTapHandler(recognizers)
..onLongPress = _getLongPressHandler(recognizers)
..onHorizontalDragUpdate = _getHorizontalDragUpdateHandler(recognizers)
..onVerticalDragUpdate = _getVerticalDragUpdateHandler(recognizers);
}
GestureTapCallback? _getTapHandler(Map<Type, GestureRecognizer> recognizers) {
final TapGestureRecognizer? tap = recognizers[TapGestureRecognizer] as TapGestureRecognizer?;
if (tap == null) {
return null;
}
return () {
tap.onTapDown?.call(TapDownDetails());
tap.onTapUp?.call(TapUpDetails(kind: PointerDeviceKind.unknown));
tap.onTap?.call();
};
}
GestureLongPressCallback? _getLongPressHandler(Map<Type, GestureRecognizer> recognizers) {
final LongPressGestureRecognizer? longPress = recognizers[LongPressGestureRecognizer] as LongPressGestureRecognizer?;
if (longPress == null) {
return null;
}
return () {
longPress.onLongPressDown?.call(const LongPressDownDetails());
longPress.onLongPressStart?.call(const LongPressStartDetails());
longPress.onLongPress?.call();
longPress.onLongPressEnd?.call(const LongPressEndDetails());
longPress.onLongPressUp?.call();
};
}
GestureDragUpdateCallback? _getHorizontalDragUpdateHandler(Map<Type, GestureRecognizer> recognizers) {
final HorizontalDragGestureRecognizer? horizontal = recognizers[HorizontalDragGestureRecognizer] as HorizontalDragGestureRecognizer?;
final PanGestureRecognizer? pan = recognizers[PanGestureRecognizer] as PanGestureRecognizer?;
final GestureDragUpdateCallback? horizontalHandler = horizontal == null ?
null :
(DragUpdateDetails details) {
horizontal.onDown?.call(DragDownDetails());
horizontal.onStart?.call(DragStartDetails());
horizontal.onUpdate?.call(details);
horizontal.onEnd?.call(DragEndDetails(primaryVelocity: 0.0));
};
final GestureDragUpdateCallback? panHandler = pan == null ?
null :
(DragUpdateDetails details) {
pan.onDown?.call(DragDownDetails());
pan.onStart?.call(DragStartDetails());
pan.onUpdate?.call(details);
pan.onEnd?.call(DragEndDetails());
};
if (horizontalHandler == null && panHandler == null) {
return null;
}
return (DragUpdateDetails details) {
if (horizontalHandler != null) {
horizontalHandler(details);
}
if (panHandler != null) {
panHandler(details);
}
};
}
GestureDragUpdateCallback? _getVerticalDragUpdateHandler(Map<Type, GestureRecognizer> recognizers) {
final VerticalDragGestureRecognizer? vertical = recognizers[VerticalDragGestureRecognizer] as VerticalDragGestureRecognizer?;
final PanGestureRecognizer? pan = recognizers[PanGestureRecognizer] as PanGestureRecognizer?;
final GestureDragUpdateCallback? verticalHandler = vertical == null ?
null :
(DragUpdateDetails details) {
vertical.onDown?.call(DragDownDetails());
vertical.onStart?.call(DragStartDetails());
vertical.onUpdate?.call(details);
vertical.onEnd?.call(DragEndDetails(primaryVelocity: 0.0));
};
final GestureDragUpdateCallback? panHandler = pan == null ?
null :
(DragUpdateDetails details) {
pan.onDown?.call(DragDownDetails());
pan.onStart?.call(DragStartDetails());
pan.onUpdate?.call(details);
pan.onEnd?.call(DragEndDetails());
};
if (verticalHandler == null && panHandler == null) {
return null;
}
return (DragUpdateDetails details) {
if (verticalHandler != null) {
verticalHandler(details);
}
if (panHandler != null) {
panHandler(details);
}
};
}
}
| flutter/packages/flutter/lib/src/widgets/gesture_detector.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/gesture_detector.dart",
"repo_id": "flutter",
"token_count": 21917
} | 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/rendering.dart';
import 'debug.dart';
import 'framework.dart';
/// The signature of the [LayoutBuilder] builder function.
typedef LayoutWidgetBuilder = Widget Function(BuildContext context, BoxConstraints constraints);
/// An abstract superclass for widgets that defer their building until layout.
///
/// Similar to the [Builder] widget except that the framework calls the [builder]
/// function at layout time and provides the constraints that this widget should
/// adhere to. This is useful when the parent constrains the child's size and layout,
/// and doesn't depend on the child's intrinsic size.
///
/// {@template flutter.widgets.ConstrainedLayoutBuilder}
/// The [builder] function is called in the following situations:
///
/// * The first time the widget is laid out.
/// * When the parent widget passes different layout constraints.
/// * When the parent widget updates this widget.
/// * When the dependencies that the [builder] function subscribes to change.
///
/// The [builder] function is _not_ called during layout if the parent passes
/// the same constraints repeatedly.
/// {@endtemplate}
///
/// Subclasses must return a [RenderObject] that mixes in
/// [RenderConstrainedLayoutBuilder].
abstract class ConstrainedLayoutBuilder<ConstraintType extends Constraints> extends RenderObjectWidget {
/// Creates a widget that defers its building until layout.
const ConstrainedLayoutBuilder({
super.key,
required this.builder,
});
@override
RenderObjectElement createElement() => _LayoutBuilderElement<ConstraintType>(this);
/// Called at layout time to construct the widget tree.
///
/// The builder must not return null.
final Widget Function(BuildContext context, ConstraintType constraints) builder;
/// Whether [builder] needs to be called again even if the layout constraints
/// are the same.
///
/// When this widget's configuration is updated, the [builder] callback most
/// likely needs to be called to build this widget's child. However,
/// subclasses may provide ways in which the widget can be updated without
/// needing to rebuild the child. Such subclasses can use this method to tell
/// the framework when the child widget should be rebuilt.
///
/// When this method is called by the framework, the newly configured widget
/// is asked if it requires a rebuild, and it is passed the old widget as a
/// parameter.
///
/// See also:
///
/// * [State.setState] and [State.didUpdateWidget], which talk about widget
/// configuration changes and how they're triggered.
/// * [Element.update], the method that actually updates the widget's
/// configuration.
@protected
bool updateShouldRebuild(covariant ConstrainedLayoutBuilder<ConstraintType> oldWidget) => true;
// updateRenderObject is redundant with the logic in the LayoutBuilderElement below.
}
class _LayoutBuilderElement<ConstraintType extends Constraints> extends RenderObjectElement {
_LayoutBuilderElement(ConstrainedLayoutBuilder<ConstraintType> super.widget);
@override
RenderConstrainedLayoutBuilder<ConstraintType, RenderObject> get renderObject => super.renderObject as RenderConstrainedLayoutBuilder<ConstraintType, RenderObject>;
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) {
super.mount(parent, newSlot); // Creates the renderObject.
renderObject.updateCallback(_layout);
}
@override
void update(ConstrainedLayoutBuilder<ConstraintType> newWidget) {
assert(widget != newWidget);
final ConstrainedLayoutBuilder<ConstraintType> oldWidget = widget as ConstrainedLayoutBuilder<ConstraintType>;
super.update(newWidget);
assert(widget == newWidget);
renderObject.updateCallback(_layout);
if (newWidget.updateShouldRebuild(oldWidget)) {
renderObject.markNeedsBuild();
}
}
@override
void performRebuild() {
// This gets called if markNeedsBuild() is called on us.
// That might happen if, e.g., our builder uses Inherited widgets.
// Force the callback to be called, even if the layout constraints are the
// same. This is because that callback may depend on the updated widget
// configuration, or an inherited widget.
renderObject.markNeedsBuild();
super.performRebuild(); // Calls widget.updateRenderObject (a no-op in this case).
}
@override
void unmount() {
renderObject.updateCallback(null);
super.unmount();
}
void _layout(ConstraintType constraints) {
@pragma('vm:notify-debugger-on-exception')
void layoutCallback() {
Widget built;
try {
built = (widget as ConstrainedLayoutBuilder<ConstraintType>).builder(this, constraints);
debugWidgetBuilderValue(widget, built);
} catch (e, stack) {
built = ErrorWidget.builder(
_reportException(
ErrorDescription('building $widget'),
e,
stack,
informationCollector: () => <DiagnosticsNode>[
if (kDebugMode)
DiagnosticsDebugCreator(DebugCreator(this)),
],
),
);
}
try {
_child = updateChild(_child, built, null);
assert(_child != null);
} catch (e, stack) {
built = ErrorWidget.builder(
_reportException(
ErrorDescription('building $widget'),
e,
stack,
informationCollector: () => <DiagnosticsNode>[
if (kDebugMode)
DiagnosticsDebugCreator(DebugCreator(this)),
],
),
);
_child = updateChild(null, built, slot);
}
}
owner!.buildScope(this, layoutCallback);
}
@override
void insertRenderObjectChild(RenderObject child, Object? slot) {
final RenderObjectWithChildMixin<RenderObject> renderObject = this.renderObject;
assert(slot == null);
assert(renderObject.debugValidateChild(child));
renderObject.child = child;
assert(renderObject == this.renderObject);
}
@override
void moveRenderObjectChild(RenderObject child, Object? oldSlot, Object? newSlot) {
assert(false);
}
@override
void removeRenderObjectChild(RenderObject child, Object? slot) {
final RenderConstrainedLayoutBuilder<ConstraintType, RenderObject> renderObject = this.renderObject;
assert(renderObject.child == child);
renderObject.child = null;
assert(renderObject == this.renderObject);
}
}
/// Generic mixin for [RenderObject]s created by [ConstrainedLayoutBuilder].
///
/// Provides a callback that should be called at layout time, typically in
/// [RenderObject.performLayout].
mixin RenderConstrainedLayoutBuilder<ConstraintType extends Constraints, ChildType extends RenderObject> on RenderObjectWithChildMixin<ChildType> {
LayoutCallback<ConstraintType>? _callback;
/// Change the layout callback.
void updateCallback(LayoutCallback<ConstraintType>? value) {
if (value == _callback) {
return;
}
_callback = value;
markNeedsLayout();
}
bool _needsBuild = true;
/// Marks this layout builder as needing to rebuild.
///
/// The layout build rebuilds automatically when layout constraints change.
/// However, we must also rebuild when the widget updates, e.g. after
/// [State.setState], or [State.didChangeDependencies], even when the layout
/// constraints remain unchanged.
///
/// See also:
///
/// * [ConstrainedLayoutBuilder.builder], which is called during the rebuild.
void markNeedsBuild() {
// Do not call the callback directly. It must be called during the layout
// phase, when parent constraints are available. Calling `markNeedsLayout`
// will cause it to be called at the right time.
_needsBuild = true;
markNeedsLayout();
}
// The constraints that were passed to this class last time it was laid out.
// These constraints are compared to the new constraints to determine whether
// [ConstrainedLayoutBuilder.builder] needs to be called.
Constraints? _previousConstraints;
/// Invoke the callback supplied via [updateCallback].
///
/// Typically this results in [ConstrainedLayoutBuilder.builder] being called
/// during layout.
void rebuildIfNecessary() {
assert(_callback != null);
if (_needsBuild || constraints != _previousConstraints) {
_previousConstraints = constraints;
_needsBuild = false;
invokeLayoutCallback(_callback!);
}
}
}
/// Builds a widget tree that can depend on the parent widget's size.
///
/// Similar to the [Builder] widget except that the framework calls the [builder]
/// function at layout time and provides the parent widget's constraints. This
/// is useful when the parent constrains the child's size and doesn't depend on
/// the child's intrinsic size. The [LayoutBuilder]'s final size will match its
/// child's size.
///
/// {@macro flutter.widgets.ConstrainedLayoutBuilder}
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=IYDVcriKjsw}
///
/// If the child should be smaller than the parent, consider wrapping the child
/// in an [Align] widget. If the child might want to be bigger, consider
/// wrapping it in a [SingleChildScrollView] or [OverflowBox].
///
/// {@tool dartpad}
/// This example uses a [LayoutBuilder] to build a different widget depending on the available width. Resize the
/// DartPad window to see [LayoutBuilder] in action!
///
/// ** See code in examples/api/lib/widgets/layout_builder/layout_builder.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [SliverLayoutBuilder], the sliver counterpart of this widget.
/// * [Builder], which calls a `builder` function at build time.
/// * [StatefulBuilder], which passes its `builder` function a `setState` callback.
/// * [CustomSingleChildLayout], which positions its child during layout.
/// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
class LayoutBuilder extends ConstrainedLayoutBuilder<BoxConstraints> {
/// Creates a widget that defers its building until layout.
const LayoutBuilder({
super.key,
required super.builder,
});
@override
RenderObject createRenderObject(BuildContext context) => _RenderLayoutBuilder();
}
class _RenderLayoutBuilder extends RenderBox with RenderObjectWithChildMixin<RenderBox>, RenderConstrainedLayoutBuilder<BoxConstraints, RenderBox> {
@override
double computeMinIntrinsicWidth(double height) {
assert(_debugThrowIfNotCheckingIntrinsics());
return 0.0;
}
@override
double computeMaxIntrinsicWidth(double height) {
assert(_debugThrowIfNotCheckingIntrinsics());
return 0.0;
}
@override
double computeMinIntrinsicHeight(double width) {
assert(_debugThrowIfNotCheckingIntrinsics());
return 0.0;
}
@override
double computeMaxIntrinsicHeight(double width) {
assert(_debugThrowIfNotCheckingIntrinsics());
return 0.0;
}
@override
Size computeDryLayout(BoxConstraints constraints) {
assert(debugCannotComputeDryLayout(reason:
'Calculating the dry layout would require running the layout callback '
'speculatively, which might mutate the live render object tree.',
));
return Size.zero;
}
@override
void performLayout() {
final BoxConstraints constraints = this.constraints;
rebuildIfNecessary();
if (child != null) {
child!.layout(constraints, parentUsesSize: true);
size = constraints.constrain(child!.size);
} else {
size = constraints.biggest;
}
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
if (child != null) {
return child!.getDistanceToActualBaseline(baseline);
}
return super.computeDistanceToActualBaseline(baseline);
}
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return child?.hitTest(result, position: position) ?? false;
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null) {
context.paintChild(child!, offset);
}
}
bool _debugThrowIfNotCheckingIntrinsics() {
assert(() {
if (!RenderObject.debugCheckingIntrinsics) {
throw FlutterError(
'LayoutBuilder does not support returning intrinsic dimensions.\n'
'Calculating the intrinsic dimensions would require running the layout '
'callback speculatively, which might mutate the live render object tree.',
);
}
return true;
}());
return true;
}
}
FlutterErrorDetails _reportException(
DiagnosticsNode context,
Object exception,
StackTrace stack, {
InformationCollector? informationCollector,
}) {
final FlutterErrorDetails details = FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: context,
informationCollector: informationCollector,
);
FlutterError.reportError(details);
return details;
}
| flutter/packages/flutter/lib/src/widgets/layout_builder.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/layout_builder.dart",
"repo_id": "flutter",
"token_count": 4154
} | 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 'framework.dart';
// Examples can assume:
// late BuildContext context;
/// A [Key] that can be used to persist the widget state in storage after the
/// destruction and will be restored when recreated.
///
/// Each key with its value plus the ancestor chain of other [PageStorageKey]s
/// need to be unique within the widget's closest ancestor [PageStorage]. To
/// make it possible for a saved value to be found when a widget is recreated,
/// the key's value must not be objects whose identity will change each time the
/// widget is created.
///
/// See also:
///
/// * [PageStorage], which manages the data storage for widgets using
/// [PageStorageKey]s.
class PageStorageKey<T> extends ValueKey<T> {
/// Creates a [ValueKey] that defines where [PageStorage] values will be saved.
const PageStorageKey(super.value);
}
@immutable
class _StorageEntryIdentifier {
const _StorageEntryIdentifier(this.keys);
final List<PageStorageKey<dynamic>> keys;
bool get isNotEmpty => keys.isNotEmpty;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is _StorageEntryIdentifier
&& listEquals<PageStorageKey<dynamic>>(other.keys, keys);
}
@override
int get hashCode => Object.hashAll(keys);
@override
String toString() {
return 'StorageEntryIdentifier(${keys.join(":")})';
}
}
/// A storage bucket associated with a page in an app.
///
/// Useful for storing per-page state that persists across navigations from one
/// page to another.
class PageStorageBucket {
static bool _maybeAddKey(BuildContext context, List<PageStorageKey<dynamic>> keys) {
final Widget widget = context.widget;
final Key? key = widget.key;
if (key is PageStorageKey) {
keys.add(key);
}
return widget is! PageStorage;
}
List<PageStorageKey<dynamic>> _allKeys(BuildContext context) {
final List<PageStorageKey<dynamic>> keys = <PageStorageKey<dynamic>>[];
if (_maybeAddKey(context, keys)) {
context.visitAncestorElements((Element element) {
return _maybeAddKey(element, keys);
});
}
return keys;
}
_StorageEntryIdentifier _computeIdentifier(BuildContext context) {
return _StorageEntryIdentifier(_allKeys(context));
}
Map<Object, dynamic>? _storage;
/// Write the given data into this page storage bucket using the
/// specified identifier or an identifier computed from the given context.
/// The computed identifier is based on the [PageStorageKey]s
/// found in the path from context to the [PageStorage] widget that
/// owns this page storage bucket.
///
/// If an explicit identifier is not provided and no [PageStorageKey]s
/// are found, then the `data` is not saved.
void writeState(BuildContext context, dynamic data, { Object? identifier }) {
_storage ??= <Object, dynamic>{};
if (identifier != null) {
_storage![identifier] = data;
} else {
final _StorageEntryIdentifier contextIdentifier = _computeIdentifier(context);
if (contextIdentifier.isNotEmpty) {
_storage![contextIdentifier] = data;
}
}
}
/// Read given data from into this page storage bucket using the specified
/// identifier or an identifier computed from the given context.
/// The computed identifier is based on the [PageStorageKey]s
/// found in the path from context to the [PageStorage] widget that
/// owns this page storage bucket.
///
/// If an explicit identifier is not provided and no [PageStorageKey]s
/// are found, then null is returned.
dynamic readState(BuildContext context, { Object? identifier }) {
if (_storage == null) {
return null;
}
if (identifier != null) {
return _storage![identifier];
}
final _StorageEntryIdentifier contextIdentifier = _computeIdentifier(context);
return contextIdentifier.isNotEmpty ? _storage![contextIdentifier] : null;
}
}
/// Establish a subtree in which widgets can opt into persisting states after
/// being destroyed.
///
/// [PageStorage] is used to save and restore values that can outlive the widget.
/// For example, when multiple pages are grouped in tabs, when a page is
/// switched out, its widget is destroyed and its state is lost. By adding a
/// [PageStorage] at the root and adding a [PageStorageKey] to each page, some of the
/// page's state (e.g. the scroll position of a [Scrollable] widget) will be stored
/// automatically in its closest ancestor [PageStorage], and restored when it's
/// switched back.
///
/// Usually you don't need to explicitly use a [PageStorage], since it's already
/// included in routes.
///
/// [PageStorageKey] is used by [Scrollable] if [ScrollController.keepScrollOffset]
/// is enabled to save their [ScrollPosition]s. When more than one scrollable
/// ([ListView], [SingleChildScrollView], [TextField], etc.) appears within the
/// widget's closest ancestor [PageStorage] (such as within the same route), to
/// save all of their positions independently, one must give each of them unique
/// [PageStorageKey]s, or set the `keepScrollOffset` property of some such
/// widgets to false to prevent saving.
///
/// {@tool dartpad}
/// This sample shows how to explicitly use a [PageStorage] to
/// store the states of its children pages. Each page includes a scrollable
/// list, whose position is preserved when switching between the tabs thanks to
/// the help of [PageStorageKey].
///
/// ** See code in examples/api/lib/widgets/page_storage/page_storage.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ModalRoute], which includes this class.
class PageStorage extends StatelessWidget {
/// Creates a widget that provides a storage bucket for its descendants.
const PageStorage({
super.key,
required this.bucket,
required this.child,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// The page storage bucket to use for this subtree.
final PageStorageBucket bucket;
/// The [PageStorageBucket] from the closest instance of a [PageStorage]
/// widget that encloses the given context.
///
/// Returns null if none exists.
///
/// Typical usage is as follows:
///
/// ```dart
/// PageStorageBucket? bucket = PageStorage.of(context);
/// ```
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [PageStorage.of], which is similar to this method, but
/// asserts if no [PageStorage] ancestor is found.
static PageStorageBucket? maybeOf(BuildContext context) {
final PageStorage? widget = context.findAncestorWidgetOfExactType<PageStorage>();
return widget?.bucket;
}
/// The [PageStorageBucket] from the closest instance of a [PageStorage]
/// widget that encloses the given context.
///
/// If no ancestor is found, this method will assert in debug mode, and throw
/// an exception in release mode.
///
/// Typical usage is as follows:
///
/// ```dart
/// PageStorageBucket bucket = PageStorage.of(context);
/// ```
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [PageStorage.maybeOf], which is similar to this method, but
/// returns null if no [PageStorage] ancestor is found.
static PageStorageBucket of(BuildContext context) {
final PageStorageBucket? bucket = maybeOf(context);
assert(() {
if (bucket == null) {
throw FlutterError(
'PageStorage.of() was called with a context that does not contain a '
'PageStorage widget.\n'
'No PageStorage widget ancestor could be found starting from the '
'context that was passed to PageStorage.of(). This can happen '
'because you are using a widget that looks for a PageStorage '
'ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return bucket!;
}
@override
Widget build(BuildContext context) => child;
}
| flutter/packages/flutter/lib/src/widgets/page_storage.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/page_storage.dart",
"repo_id": "flutter",
"token_count": 2494
} | 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 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'actions.dart';
import 'basic.dart';
import 'display_feature_sub_screen.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'focus_traversal.dart';
import 'framework.dart';
import 'modal_barrier.dart';
import 'navigator.dart';
import 'overlay.dart';
import 'page_storage.dart';
import 'primary_scroll_controller.dart';
import 'restoration.dart';
import 'scroll_controller.dart';
import 'transitions.dart';
// Examples can assume:
// late NavigatorState navigator;
// late BuildContext context;
// Future<bool> askTheUserIfTheyAreSure() async { return true; }
// abstract class MyWidget extends StatefulWidget { const MyWidget({super.key}); }
// late dynamic _myState, newValue;
// late StateSetter setState;
/// A route that displays widgets in the [Navigator]'s [Overlay].
///
/// See also:
///
/// * [Route], which documents the meaning of the `T` generic type argument.
abstract class OverlayRoute<T> extends Route<T> {
/// Creates a route that knows how to interact with an [Overlay].
OverlayRoute({
super.settings,
});
/// Subclasses should override this getter to return the builders for the overlay.
@factory
Iterable<OverlayEntry> createOverlayEntries();
@override
List<OverlayEntry> get overlayEntries => _overlayEntries;
final List<OverlayEntry> _overlayEntries = <OverlayEntry>[];
@override
void install() {
assert(_overlayEntries.isEmpty);
_overlayEntries.addAll(createOverlayEntries());
super.install();
}
/// Controls whether [didPop] calls [NavigatorState.finalizeRoute].
///
/// If true, this route removes its overlay entries during [didPop].
/// Subclasses can override this getter if they want to delay finalization
/// (for example to animate the route's exit before removing it from the
/// overlay).
///
/// Subclasses that return false from [finishedWhenPopped] are responsible for
/// calling [NavigatorState.finalizeRoute] themselves.
@protected
bool get finishedWhenPopped => true;
@override
bool didPop(T? result) {
final bool returnValue = super.didPop(result);
assert(returnValue);
if (finishedWhenPopped) {
navigator!.finalizeRoute(this);
}
return returnValue;
}
@override
void dispose() {
for (final OverlayEntry entry in _overlayEntries) {
entry.dispose();
}
_overlayEntries.clear();
super.dispose();
}
}
/// A route with entrance and exit transitions.
///
/// See also:
///
/// * [Route], which documents the meaning of the `T` generic type argument.
abstract class TransitionRoute<T> extends OverlayRoute<T> {
/// Creates a route that animates itself when it is pushed or popped.
TransitionRoute({
super.settings,
});
/// This future completes only once the transition itself has finished, after
/// the overlay entries have been removed from the navigator's overlay.
///
/// This future completes once the animation has been dismissed. That will be
/// after [popped], because [popped] typically completes before the animation
/// even starts, as soon as the route is popped.
Future<T?> get completed => _transitionCompleter.future;
final Completer<T?> _transitionCompleter = Completer<T?>();
/// Handle to the performance mode request.
///
/// When the route is animating, the performance mode is requested. It is then
/// disposed when the animation ends. Requesting [DartPerformanceMode.latency]
/// indicates to the engine that the transition is latency sensitive and to delay
/// non-essential work while this handle is active.
PerformanceModeRequestHandle? _performanceModeRequestHandle;
/// {@template flutter.widgets.TransitionRoute.transitionDuration}
/// The duration the transition going forwards.
///
/// See also:
///
/// * [reverseTransitionDuration], which controls the duration of the
/// transition when it is in reverse.
/// {@endtemplate}
Duration get transitionDuration;
/// {@template flutter.widgets.TransitionRoute.reverseTransitionDuration}
/// The duration the transition going in reverse.
///
/// By default, the reverse transition duration is set to the value of
/// the forwards [transitionDuration].
/// {@endtemplate}
Duration get reverseTransitionDuration => transitionDuration;
/// {@template flutter.widgets.TransitionRoute.opaque}
/// Whether the route obscures previous routes when the transition is complete.
///
/// When an opaque route's entrance transition is complete, the routes behind
/// the opaque route will not be built to save resources.
/// {@endtemplate}
bool get opaque;
/// {@template flutter.widgets.TransitionRoute.allowSnapshotting}
/// Whether the route transition will prefer to animate a snapshot of the
/// entering/exiting routes.
///
/// When this value is true, certain route transitions (such as the Android
/// zoom page transition) will snapshot the entering and exiting routes.
/// These snapshots are then animated in place of the underlying widgets to
/// improve performance of the transition.
///
/// Generally this means that animations that occur on the entering/exiting
/// route while the route animation plays may appear frozen - unless they
/// are a hero animation or something that is drawn in a separate overlay.
/// {@endtemplate}
bool get allowSnapshotting => true;
// This ensures that if we got to the dismissed state while still current,
// we will still be disposed when we are eventually popped.
//
// This situation arises when dealing with the Cupertino dismiss gesture.
@override
bool get finishedWhenPopped => _controller!.status == AnimationStatus.dismissed && !_popFinalized;
bool _popFinalized = false;
/// The animation that drives the route's transition and the previous route's
/// forward transition.
Animation<double>? get animation => _animation;
Animation<double>? _animation;
/// The animation controller that the route uses to drive the transitions.
///
/// The animation itself is exposed by the [animation] property.
@protected
AnimationController? get controller => _controller;
AnimationController? _controller;
/// The animation for the route being pushed on top of this route. This
/// animation lets this route coordinate with the entrance and exit transition
/// of route pushed on top of this route.
Animation<double>? get secondaryAnimation => _secondaryAnimation;
final ProxyAnimation _secondaryAnimation = ProxyAnimation(kAlwaysDismissedAnimation);
/// Whether to takeover the [controller] created by [createAnimationController].
///
/// If true, this route will call [AnimationController.dispose] when the
/// controller is no longer needed.
/// If false, the controller should be disposed by whoever owned it.
///
/// It defaults to `true`.
bool willDisposeAnimationController = true;
/// Called to create the animation controller that will drive the transitions to
/// this route from the previous one, and back to the previous route from this
/// one.
///
/// The returned controller will be disposed by [AnimationController.dispose]
/// if the [willDisposeAnimationController] is `true`.
AnimationController createAnimationController() {
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
final Duration duration = transitionDuration;
final Duration reverseDuration = reverseTransitionDuration;
assert(duration >= Duration.zero);
return AnimationController(
duration: duration,
reverseDuration: reverseDuration,
debugLabel: debugLabel,
vsync: navigator!,
);
}
/// Called to create the animation that exposes the current progress of
/// the transition controlled by the animation controller created by
/// [createAnimationController()].
Animation<double> createAnimation() {
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
assert(_controller != null);
return _controller!.view;
}
T? _result;
void _handleStatusChanged(AnimationStatus status) {
switch (status) {
case AnimationStatus.completed:
if (overlayEntries.isNotEmpty) {
overlayEntries.first.opaque = opaque;
}
_performanceModeRequestHandle?.dispose();
_performanceModeRequestHandle = null;
case AnimationStatus.forward:
case AnimationStatus.reverse:
if (overlayEntries.isNotEmpty) {
overlayEntries.first.opaque = false;
}
_performanceModeRequestHandle ??=
SchedulerBinding.instance
.requestPerformanceMode(ui.DartPerformanceMode.latency);
case AnimationStatus.dismissed:
// We might still be an active route if a subclass is controlling the
// transition and hits the dismissed status. For example, the iOS
// back gesture drives this animation to the dismissed status before
// removing the route and disposing it.
if (!isActive) {
navigator!.finalizeRoute(this);
_popFinalized = true;
_performanceModeRequestHandle?.dispose();
_performanceModeRequestHandle = null;
}
}
}
@override
void install() {
assert(!_transitionCompleter.isCompleted, 'Cannot install a $runtimeType after disposing it.');
_controller = createAnimationController();
assert(_controller != null, '$runtimeType.createAnimationController() returned null.');
_animation = createAnimation()
..addStatusListener(_handleStatusChanged);
assert(_animation != null, '$runtimeType.createAnimation() returned null.');
super.install();
if (_animation!.isCompleted && overlayEntries.isNotEmpty) {
overlayEntries.first.opaque = opaque;
}
}
@override
TickerFuture didPush() {
assert(_controller != null, '$runtimeType.didPush called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
super.didPush();
return _controller!.forward();
}
@override
void didAdd() {
assert(_controller != null, '$runtimeType.didPush called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
super.didAdd();
_controller!.value = _controller!.upperBound;
}
@override
void didReplace(Route<dynamic>? oldRoute) {
assert(_controller != null, '$runtimeType.didReplace called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
if (oldRoute is TransitionRoute) {
_controller!.value = oldRoute._controller!.value;
}
super.didReplace(oldRoute);
}
@override
bool didPop(T? result) {
assert(_controller != null, '$runtimeType.didPop called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
_result = result;
_controller!.reverse();
return super.didPop(result);
}
@override
void didPopNext(Route<dynamic> nextRoute) {
assert(_controller != null, '$runtimeType.didPopNext called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
_updateSecondaryAnimation(nextRoute);
super.didPopNext(nextRoute);
}
@override
void didChangeNext(Route<dynamic>? nextRoute) {
assert(_controller != null, '$runtimeType.didChangeNext called before calling install() or after calling dispose().');
assert(!_transitionCompleter.isCompleted, 'Cannot reuse a $runtimeType after disposing it.');
_updateSecondaryAnimation(nextRoute);
super.didChangeNext(nextRoute);
}
// A callback method that disposes existing train hopping animation and
// removes its listener.
//
// This property is non-null if there is a train hopping in progress, and the
// caller must reset this property to null after it is called.
VoidCallback? _trainHoppingListenerRemover;
void _updateSecondaryAnimation(Route<dynamic>? nextRoute) {
// There is an existing train hopping in progress. Unfortunately, we cannot
// dispose current train hopping animation until we replace it with a new
// animation.
final VoidCallback? previousTrainHoppingListenerRemover = _trainHoppingListenerRemover;
_trainHoppingListenerRemover = null;
if (nextRoute is TransitionRoute<dynamic> && canTransitionTo(nextRoute) && nextRoute.canTransitionFrom(this)) {
final Animation<double>? current = _secondaryAnimation.parent;
if (current != null) {
final Animation<double> currentTrain = (current is TrainHoppingAnimation ? current.currentTrain : current)!;
final Animation<double> nextTrain = nextRoute._animation!;
if (
currentTrain.value == nextTrain.value ||
nextTrain.status == AnimationStatus.completed ||
nextTrain.status == AnimationStatus.dismissed
) {
_setSecondaryAnimation(nextTrain, nextRoute.completed);
} else {
// Two trains animate at different values. We have to do train hopping.
// There are three possibilities of train hopping:
// 1. We hop on the nextTrain when two trains meet in the middle using
// TrainHoppingAnimation.
// 2. There is no chance to hop on nextTrain because two trains never
// cross each other. We have to directly set the animation to
// nextTrain once the nextTrain stops animating.
// 3. A new _updateSecondaryAnimation is called before train hopping
// finishes. We leave a listener remover for the next call to
// properly clean up the existing train hopping.
TrainHoppingAnimation? newAnimation;
void jumpOnAnimationEnd(AnimationStatus status) {
switch (status) {
case AnimationStatus.completed:
case AnimationStatus.dismissed:
// The nextTrain has stopped animating without train hopping.
// Directly sets the secondary animation and disposes the
// TrainHoppingAnimation.
_setSecondaryAnimation(nextTrain, nextRoute.completed);
if (_trainHoppingListenerRemover != null) {
_trainHoppingListenerRemover!();
_trainHoppingListenerRemover = null;
}
case AnimationStatus.forward:
case AnimationStatus.reverse:
break;
}
}
_trainHoppingListenerRemover = () {
nextTrain.removeStatusListener(jumpOnAnimationEnd);
newAnimation?.dispose();
};
nextTrain.addStatusListener(jumpOnAnimationEnd);
newAnimation = TrainHoppingAnimation(
currentTrain,
nextTrain,
onSwitchedTrain: () {
assert(_secondaryAnimation.parent == newAnimation);
assert(newAnimation!.currentTrain == nextRoute._animation);
// We can hop on the nextTrain, so we don't need to listen to
// whether the nextTrain has stopped.
_setSecondaryAnimation(newAnimation!.currentTrain, nextRoute.completed);
if (_trainHoppingListenerRemover != null) {
_trainHoppingListenerRemover!();
_trainHoppingListenerRemover = null;
}
},
);
_setSecondaryAnimation(newAnimation, nextRoute.completed);
}
} else {
_setSecondaryAnimation(nextRoute._animation, nextRoute.completed);
}
} else {
_setSecondaryAnimation(kAlwaysDismissedAnimation);
}
// Finally, we dispose any previous train hopping animation because it
// has been successfully updated at this point.
if (previousTrainHoppingListenerRemover != null) {
previousTrainHoppingListenerRemover();
}
}
void _setSecondaryAnimation(Animation<double>? animation, [Future<dynamic>? disposed]) {
_secondaryAnimation.parent = animation;
// Releases the reference to the next route's animation when that route
// is disposed.
disposed?.then((dynamic _) {
if (_secondaryAnimation.parent == animation) {
_secondaryAnimation.parent = kAlwaysDismissedAnimation;
if (animation is TrainHoppingAnimation) {
animation.dispose();
}
}
});
}
/// Returns true if this route supports a transition animation that runs
/// when [nextRoute] is pushed on top of it or when [nextRoute] is popped
/// off of it.
///
/// Subclasses can override this method to restrict the set of routes they
/// need to coordinate transitions with.
///
/// If true, and `nextRoute.canTransitionFrom()` is true, then the
/// [ModalRoute.buildTransitions] `secondaryAnimation` will run from 0.0 - 1.0
/// when [nextRoute] is pushed on top of this one. Similarly, if
/// the [nextRoute] is popped off of this route, the
/// `secondaryAnimation` will run from 1.0 - 0.0.
///
/// If false, this route's [ModalRoute.buildTransitions] `secondaryAnimation` parameter
/// value will be [kAlwaysDismissedAnimation]. In other words, this route
/// will not animate when [nextRoute] is pushed on top of it or when
/// [nextRoute] is popped off of it.
///
/// Returns true by default.
///
/// See also:
///
/// * [canTransitionFrom], which must be true for [nextRoute] for the
/// [ModalRoute.buildTransitions] `secondaryAnimation` to run.
bool canTransitionTo(TransitionRoute<dynamic> nextRoute) => true;
/// Returns true if [previousRoute] should animate when this route
/// is pushed on top of it or when then this route is popped off of it.
///
/// Subclasses can override this method to restrict the set of routes they
/// need to coordinate transitions with.
///
/// If true, and `previousRoute.canTransitionTo()` is true, then the
/// previous route's [ModalRoute.buildTransitions] `secondaryAnimation` will
/// run from 0.0 - 1.0 when this route is pushed on top of
/// it. Similarly, if this route is popped off of [previousRoute]
/// the previous route's `secondaryAnimation` will run from 1.0 - 0.0.
///
/// If false, then the previous route's [ModalRoute.buildTransitions]
/// `secondaryAnimation` value will be kAlwaysDismissedAnimation. In
/// other words [previousRoute] will not animate when this route is
/// pushed on top of it or when then this route is popped off of it.
///
/// Returns true by default.
///
/// See also:
///
/// * [canTransitionTo], which must be true for [previousRoute] for its
/// [ModalRoute.buildTransitions] `secondaryAnimation` to run.
bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) => true;
@override
void dispose() {
assert(!_transitionCompleter.isCompleted, 'Cannot dispose a $runtimeType twice.');
_animation?.removeStatusListener(_handleStatusChanged);
_performanceModeRequestHandle?.dispose();
_performanceModeRequestHandle = null;
if (willDisposeAnimationController) {
_controller?.dispose();
}
_transitionCompleter.complete(_result);
super.dispose();
}
/// A short description of this route useful for debugging.
String get debugLabel => objectRuntimeType(this, 'TransitionRoute');
@override
String toString() => '${objectRuntimeType(this, 'TransitionRoute')}(animation: $_controller)';
}
/// An entry in the history of a [LocalHistoryRoute].
class LocalHistoryEntry {
/// Creates an entry in the history of a [LocalHistoryRoute].
///
/// The [impliesAppBarDismissal] defaults to true if not provided.
LocalHistoryEntry({ this.onRemove, this.impliesAppBarDismissal = true });
/// Called when this entry is removed from the history of its associated [LocalHistoryRoute].
final VoidCallback? onRemove;
LocalHistoryRoute<dynamic>? _owner;
/// Whether an [AppBar] in the route this entry belongs to should
/// automatically add a back button or close button.
///
/// Defaults to true.
final bool impliesAppBarDismissal;
/// Remove this entry from the history of its associated [LocalHistoryRoute].
void remove() {
_owner?.removeLocalHistoryEntry(this);
assert(_owner == null);
}
void _notifyRemoved() {
onRemove?.call();
}
}
/// A mixin used by routes to handle back navigations internally by popping a list.
///
/// When a [Navigator] is instructed to pop, the current route is given an
/// opportunity to handle the pop internally. A [LocalHistoryRoute] handles the
/// pop internally if its list of local history entries is non-empty. Rather
/// than being removed as the current route, the most recent [LocalHistoryEntry]
/// is removed from the list and its [LocalHistoryEntry.onRemove] is called.
///
/// See also:
///
/// * [Route], which documents the meaning of the `T` generic type argument.
mixin LocalHistoryRoute<T> on Route<T> {
List<LocalHistoryEntry>? _localHistory;
int _entriesImpliesAppBarDismissal = 0;
/// Adds a local history entry to this route.
///
/// When asked to pop, if this route has any local history entries, this route
/// will handle the pop internally by removing the most recently added local
/// history entry.
///
/// The given local history entry must not already be part of another local
/// history route.
///
/// {@tool snippet}
///
/// The following example is an app with 2 pages: `HomePage` and `SecondPage`.
/// The `HomePage` can navigate to the `SecondPage`.
///
/// The `SecondPage` uses a [LocalHistoryEntry] to implement local navigation
/// within that page. Pressing 'show rectangle' displays a red rectangle and
/// adds a local history entry. At that point, pressing the '< back' button
/// pops the latest route, which is the local history entry, and the red
/// rectangle disappears. Pressing the '< back' button a second time
/// once again pops the latest route, which is the `SecondPage`, itself.
/// Therefore, the second press navigates back to the `HomePage`.
///
/// ```dart
/// class App extends StatelessWidget {
/// const App({super.key});
///
/// @override
/// Widget build(BuildContext context) {
/// return MaterialApp(
/// initialRoute: '/',
/// routes: <String, WidgetBuilder>{
/// '/': (BuildContext context) => const HomePage(),
/// '/second_page': (BuildContext context) => const SecondPage(),
/// },
/// );
/// }
/// }
///
/// class HomePage extends StatefulWidget {
/// const HomePage({super.key});
///
/// @override
/// State<HomePage> createState() => _HomePageState();
/// }
///
/// class _HomePageState extends State<HomePage> {
/// @override
/// Widget build(BuildContext context) {
/// return Scaffold(
/// body: Center(
/// child: Column(
/// mainAxisSize: MainAxisSize.min,
/// children: <Widget>[
/// const Text('HomePage'),
/// // Press this button to open the SecondPage.
/// ElevatedButton(
/// child: const Text('Second Page >'),
/// onPressed: () {
/// Navigator.pushNamed(context, '/second_page');
/// },
/// ),
/// ],
/// ),
/// ),
/// );
/// }
/// }
///
/// class SecondPage extends StatefulWidget {
/// const SecondPage({super.key});
///
/// @override
/// State<SecondPage> createState() => _SecondPageState();
/// }
///
/// class _SecondPageState extends State<SecondPage> {
///
/// bool _showRectangle = false;
///
/// Future<void> _navigateLocallyToShowRectangle() async {
/// // This local history entry essentially represents the display of the red
/// // rectangle. When this local history entry is removed, we hide the red
/// // rectangle.
/// setState(() => _showRectangle = true);
/// ModalRoute.of(context)?.addLocalHistoryEntry(
/// LocalHistoryEntry(
/// onRemove: () {
/// // Hide the red rectangle.
/// setState(() => _showRectangle = false);
/// }
/// )
/// );
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// final Widget localNavContent = _showRectangle
/// ? Container(
/// width: 100.0,
/// height: 100.0,
/// color: Colors.red,
/// )
/// : ElevatedButton(
/// onPressed: _navigateLocallyToShowRectangle,
/// child: const Text('Show Rectangle'),
/// );
///
/// return Scaffold(
/// body: Center(
/// child: Column(
/// mainAxisAlignment: MainAxisAlignment.center,
/// children: <Widget>[
/// localNavContent,
/// ElevatedButton(
/// child: const Text('< Back'),
/// onPressed: () {
/// // Pop a route. If this is pressed while the red rectangle is
/// // visible then it will pop our local history entry, which
/// // will hide the red rectangle. Otherwise, the SecondPage will
/// // navigate back to the HomePage.
/// Navigator.of(context).pop();
/// },
/// ),
/// ],
/// ),
/// ),
/// );
/// }
/// }
/// ```
/// {@end-tool}
void addLocalHistoryEntry(LocalHistoryEntry entry) {
assert(entry._owner == null);
entry._owner = this;
_localHistory ??= <LocalHistoryEntry>[];
final bool wasEmpty = _localHistory!.isEmpty;
_localHistory!.add(entry);
bool internalStateChanged = false;
if (entry.impliesAppBarDismissal) {
internalStateChanged = _entriesImpliesAppBarDismissal == 0;
_entriesImpliesAppBarDismissal += 1;
}
if (wasEmpty || internalStateChanged) {
changedInternalState();
}
}
/// Remove a local history entry from this route.
///
/// The entry's [LocalHistoryEntry.onRemove] callback, if any, will be called
/// synchronously.
void removeLocalHistoryEntry(LocalHistoryEntry entry) {
assert(entry._owner == this);
assert(_localHistory!.contains(entry));
bool internalStateChanged = false;
if (_localHistory!.remove(entry) && entry.impliesAppBarDismissal) {
_entriesImpliesAppBarDismissal -= 1;
internalStateChanged = _entriesImpliesAppBarDismissal == 0;
}
entry._owner = null;
entry._notifyRemoved();
if (_localHistory!.isEmpty || internalStateChanged) {
assert(_entriesImpliesAppBarDismissal == 0);
if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
// The local history might be removed as a result of disposing inactive
// elements during finalizeTree. The state is locked at this moment, and
// we can only notify state has changed in the next frame.
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
if (isActive) {
changedInternalState();
}
}, debugLabel: 'LocalHistoryRoute.changedInternalState');
} else {
changedInternalState();
}
}
}
@Deprecated(
'Use popDisposition instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
@override
Future<RoutePopDisposition> willPop() async {
if (willHandlePopInternally) {
return RoutePopDisposition.pop;
}
return super.willPop();
}
@override
RoutePopDisposition get popDisposition {
if (willHandlePopInternally) {
return RoutePopDisposition.pop;
}
return super.popDisposition;
}
@override
bool didPop(T? result) {
if (_localHistory != null && _localHistory!.isNotEmpty) {
final LocalHistoryEntry entry = _localHistory!.removeLast();
assert(entry._owner == this);
entry._owner = null;
entry._notifyRemoved();
bool internalStateChanged = false;
if (entry.impliesAppBarDismissal) {
_entriesImpliesAppBarDismissal -= 1;
internalStateChanged = _entriesImpliesAppBarDismissal == 0;
}
if (_localHistory!.isEmpty || internalStateChanged) {
changedInternalState();
}
return false;
}
return super.didPop(result);
}
@override
bool get willHandlePopInternally {
return _localHistory != null && _localHistory!.isNotEmpty;
}
}
class _DismissModalAction extends DismissAction {
_DismissModalAction(this.context);
final BuildContext context;
@override
bool isEnabled(DismissIntent intent) {
final ModalRoute<dynamic> route = ModalRoute.of<dynamic>(context)!;
return route.barrierDismissible;
}
@override
Object invoke(DismissIntent intent) {
return Navigator.of(context).maybePop();
}
}
class _ModalScopeStatus extends InheritedWidget {
const _ModalScopeStatus({
required this.isCurrent,
required this.canPop,
required this.impliesAppBarDismissal,
required this.route,
required super.child,
});
final bool isCurrent;
final bool canPop;
final bool impliesAppBarDismissal;
final Route<dynamic> route;
@override
bool updateShouldNotify(_ModalScopeStatus old) {
return isCurrent != old.isCurrent ||
canPop != old.canPop ||
impliesAppBarDismissal != old.impliesAppBarDismissal ||
route != old.route;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder description) {
super.debugFillProperties(description);
description.add(FlagProperty('isCurrent', value: isCurrent, ifTrue: 'active', ifFalse: 'inactive'));
description.add(FlagProperty('canPop', value: canPop, ifTrue: 'can pop'));
description.add(FlagProperty('impliesAppBarDismissal', value: impliesAppBarDismissal, ifTrue: 'implies app bar dismissal'));
}
}
class _ModalScope<T> extends StatefulWidget {
const _ModalScope({
super.key,
required this.route,
});
final ModalRoute<T> route;
@override
_ModalScopeState<T> createState() => _ModalScopeState<T>();
}
class _ModalScopeState<T> extends State<_ModalScope<T>> {
// We cache the result of calling the route's buildPage, and clear the cache
// whenever the dependencies change. This implements the contract described in
// the documentation for buildPage, namely that it gets called once, unless
// something like a ModalRoute.of() dependency triggers an update.
Widget? _page;
// This is the combination of the two animations for the route.
late Listenable _listenable;
/// The node this scope will use for its root [FocusScope] widget.
final FocusScopeNode focusScopeNode = FocusScopeNode(
debugLabel: '$_ModalScopeState Focus Scope',
);
final ScrollController primaryScrollController = ScrollController();
@override
void initState() {
super.initState();
final List<Listenable> animations = <Listenable>[
if (widget.route.animation != null) widget.route.animation!,
if (widget.route.secondaryAnimation != null) widget.route.secondaryAnimation!,
];
_listenable = Listenable.merge(animations);
}
@override
void didUpdateWidget(_ModalScope<T> oldWidget) {
super.didUpdateWidget(oldWidget);
assert(widget.route == oldWidget.route);
_updateFocusScopeNode();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_page = null;
_updateFocusScopeNode();
}
void _updateFocusScopeNode() {
final TraversalEdgeBehavior traversalEdgeBehavior;
final ModalRoute<T> route = widget.route;
if (route.traversalEdgeBehavior != null) {
traversalEdgeBehavior = route.traversalEdgeBehavior!;
} else {
traversalEdgeBehavior = route.navigator!.widget.routeTraversalEdgeBehavior;
}
focusScopeNode.traversalEdgeBehavior = traversalEdgeBehavior;
if (route.isCurrent && _shouldRequestFocus) {
route.navigator!.focusNode.enclosingScope?.setFirstFocus(focusScopeNode);
}
}
void _forceRebuildPage() {
setState(() {
_page = null;
});
}
@override
void dispose() {
focusScopeNode.dispose();
primaryScrollController.dispose();
super.dispose();
}
bool get _shouldIgnoreFocusRequest {
return widget.route.animation?.status == AnimationStatus.reverse ||
(widget.route.navigator?.userGestureInProgress ?? false);
}
bool get _shouldRequestFocus {
return widget.route.navigator!.widget.requestFocus;
}
// This should be called to wrap any changes to route.isCurrent, route.canPop,
// and route.offstage.
void _routeSetState(VoidCallback fn) {
if (widget.route.isCurrent && !_shouldIgnoreFocusRequest && _shouldRequestFocus) {
widget.route.navigator!.focusNode.enclosingScope?.setFirstFocus(focusScopeNode);
}
setState(fn);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: widget.route.restorationScopeId,
builder: (BuildContext context, Widget? child) {
assert(child != null);
return RestorationScope(
restorationId: widget.route.restorationScopeId.value,
child: child!,
);
},
child: _ModalScopeStatus(
route: widget.route,
isCurrent: widget.route.isCurrent, // _routeSetState is called if this updates
canPop: widget.route.canPop, // _routeSetState is called if this updates
impliesAppBarDismissal: widget.route.impliesAppBarDismissal,
child: Offstage(
offstage: widget.route.offstage, // _routeSetState is called if this updates
child: PageStorage(
bucket: widget.route._storageBucket, // immutable
child: Builder(
builder: (BuildContext context) {
return Actions(
actions: <Type, Action<Intent>>{
DismissIntent: _DismissModalAction(context),
},
child: PrimaryScrollController(
controller: primaryScrollController,
child: FocusScope(
node: focusScopeNode, // immutable
// Only top most route can participate in focus traversal.
skipTraversal: !widget.route.isCurrent,
child: RepaintBoundary(
child: AnimatedBuilder(
animation: _listenable, // immutable
builder: (BuildContext context, Widget? child) {
return widget.route.buildTransitions(
context,
widget.route.animation!,
widget.route.secondaryAnimation!,
// This additional AnimatedBuilder is include because if the
// value of the userGestureInProgressNotifier changes, it's
// only necessary to rebuild the IgnorePointer widget and set
// the focus node's ability to focus.
AnimatedBuilder(
animation: widget.route.navigator?.userGestureInProgressNotifier ?? ValueNotifier<bool>(false),
builder: (BuildContext context, Widget? child) {
final bool ignoreEvents = _shouldIgnoreFocusRequest;
focusScopeNode.canRequestFocus = !ignoreEvents;
return IgnorePointer(
ignoring: ignoreEvents,
child: child,
);
},
child: child,
),
);
},
child: _page ??= RepaintBoundary(
key: widget.route._subtreeKey, // immutable
child: Builder(
builder: (BuildContext context) {
return widget.route.buildPage(
context,
widget.route.animation!,
widget.route.secondaryAnimation!,
);
},
),
),
),
),
),
),
);
},
),
),
),
),
);
}
}
/// A route that blocks interaction with previous routes.
///
/// [ModalRoute]s cover the entire [Navigator]. They are not necessarily
/// [opaque], however; for example, a pop-up menu uses a [ModalRoute] but only
/// shows the menu in a small box overlapping the previous route.
///
/// The `T` type argument is the return value of the route. If there is no
/// return value, consider using `void` as the return value.
///
/// See also:
///
/// * [Route], which further documents the meaning of the `T` generic type argument.
abstract class ModalRoute<T> extends TransitionRoute<T> with LocalHistoryRoute<T> {
/// Creates a route that blocks interaction with previous routes.
ModalRoute({
super.settings,
this.filter,
this.traversalEdgeBehavior,
});
/// The filter to add to the barrier.
///
/// If given, this filter will be applied to the modal barrier using
/// [BackdropFilter]. This allows blur effects, for example.
final ui.ImageFilter? filter;
/// Controls the transfer of focus beyond the first and the last items of a
/// [FocusScopeNode].
///
/// If set to null, [Navigator.routeTraversalEdgeBehavior] is used.
final TraversalEdgeBehavior? traversalEdgeBehavior;
// The API for general users of this class
/// Returns the modal route most closely associated with the given context.
///
/// Returns null if the given context is not associated with a modal route.
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// ModalRoute<int>? route = ModalRoute.of<int>(context);
/// ```
/// {@end-tool}
///
/// The given [BuildContext] will be rebuilt if the state of the route changes
/// while it is visible (specifically, if [isCurrent] or [canPop] change value).
@optionalTypeArgs
static ModalRoute<T>? of<T extends Object?>(BuildContext context) {
final _ModalScopeStatus? widget = context.dependOnInheritedWidgetOfExactType<_ModalScopeStatus>();
return widget?.route as ModalRoute<T>?;
}
/// Schedule a call to [buildTransitions].
///
/// Whenever you need to change internal state for a [ModalRoute] object, make
/// the change in a function that you pass to [setState], as in:
///
/// ```dart
/// setState(() { _myState = newValue; });
/// ```
///
/// If you just change the state directly without calling [setState], then the
/// route will not be scheduled for rebuilding, meaning that its rendering
/// will not be updated.
@protected
void setState(VoidCallback fn) {
if (_scopeKey.currentState != null) {
_scopeKey.currentState!._routeSetState(fn);
} else {
// The route isn't currently visible, so we don't have to call its setState
// method, but we do still need to call the fn callback, otherwise the state
// in the route won't be updated!
fn();
}
}
/// Returns a predicate that's true if the route has the specified name and if
/// popping the route will not yield the same route, i.e. if the route's
/// [willHandlePopInternally] property is false.
///
/// This function is typically used with [Navigator.popUntil()].
static RoutePredicate withName(String name) {
return (Route<dynamic> route) {
return !route.willHandlePopInternally
&& route is ModalRoute
&& route.settings.name == name;
};
}
// The API for subclasses to override - used by _ModalScope
/// Override this method to build the primary content of this route.
///
/// The arguments have the following meanings:
///
/// * `context`: The context in which the route is being built.
/// * [animation]: The animation for this route's transition. When entering,
/// the animation runs forward from 0.0 to 1.0. When exiting, this animation
/// runs backwards from 1.0 to 0.0.
/// * [secondaryAnimation]: The animation for the route being pushed on top of
/// this route. This animation lets this route coordinate with the entrance
/// and exit transition of routes pushed on top of this route.
///
/// This method is only called when the route is first built, and rarely
/// thereafter. In particular, it is not automatically called again when the
/// route's state changes unless it uses [ModalRoute.of]. For a builder that
/// is called every time the route's state changes, consider
/// [buildTransitions]. For widgets that change their behavior when the
/// route's state changes, consider [ModalRoute.of] to obtain a reference to
/// the route; this will cause the widget to be rebuilt each time the route
/// changes state.
///
/// In general, [buildPage] should be used to build the page contents, and
/// [buildTransitions] for the widgets that change as the page is brought in
/// and out of view. Avoid using [buildTransitions] for content that never
/// changes; building such content once from [buildPage] is more efficient.
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation);
/// Override this method to wrap the [child] with one or more transition
/// widgets that define how the route arrives on and leaves the screen.
///
/// By default, the child (which contains the widget returned by [buildPage])
/// is not wrapped in any transition widgets.
///
/// The [buildTransitions] method, in contrast to [buildPage], is called each
/// time the [Route]'s state changes while it is visible (e.g. if the value of
/// [canPop] changes on the active route).
///
/// The [buildTransitions] method is typically used to define transitions
/// that animate the new topmost route's comings and goings. When the
/// [Navigator] pushes a route on the top of its stack, the new route's
/// primary [animation] runs from 0.0 to 1.0. When the Navigator pops the
/// topmost route, e.g. because the use pressed the back button, the
/// primary animation runs from 1.0 to 0.0.
///
/// {@tool snippet}
/// The following example uses the primary animation to drive a
/// [SlideTransition] that translates the top of the new route vertically
/// from the bottom of the screen when it is pushed on the Navigator's
/// stack. When the route is popped the SlideTransition translates the
/// route from the top of the screen back to the bottom.
///
/// We've used [PageRouteBuilder] to demonstrate the [buildTransitions] method
/// here. The body of an override of the [buildTransitions] method would be
/// defined in the same way.
///
/// ```dart
/// PageRouteBuilder<void>(
/// pageBuilder: (BuildContext context,
/// Animation<double> animation,
/// Animation<double> secondaryAnimation,
/// ) {
/// return Scaffold(
/// appBar: AppBar(title: const Text('Hello')),
/// body: const Center(
/// child: Text('Hello World'),
/// ),
/// );
/// },
/// transitionsBuilder: (
/// BuildContext context,
/// Animation<double> animation,
/// Animation<double> secondaryAnimation,
/// Widget child,
/// ) {
/// return SlideTransition(
/// position: Tween<Offset>(
/// begin: const Offset(0.0, 1.0),
/// end: Offset.zero,
/// ).animate(animation),
/// child: child, // child is the value returned by pageBuilder
/// );
/// },
/// )
/// ```
/// {@end-tool}
///
/// When the [Navigator] pushes a route on the top of its stack, the
/// [secondaryAnimation] can be used to define how the route that was on
/// the top of the stack leaves the screen. Similarly when the topmost route
/// is popped, the secondaryAnimation can be used to define how the route
/// below it reappears on the screen. When the Navigator pushes a new route
/// on the top of its stack, the old topmost route's secondaryAnimation
/// runs from 0.0 to 1.0. When the Navigator pops the topmost route, the
/// secondaryAnimation for the route below it runs from 1.0 to 0.0.
///
/// {@tool snippet}
/// The example below adds a transition that's driven by the
/// [secondaryAnimation]. When this route disappears because a new route has
/// been pushed on top of it, it translates in the opposite direction of
/// the new route. Likewise when the route is exposed because the topmost
/// route has been popped off.
///
/// ```dart
/// PageRouteBuilder<void>(
/// pageBuilder: (BuildContext context,
/// Animation<double> animation,
/// Animation<double> secondaryAnimation,
/// ) {
/// return Scaffold(
/// appBar: AppBar(title: const Text('Hello')),
/// body: const Center(
/// child: Text('Hello World'),
/// ),
/// );
/// },
/// transitionsBuilder: (
/// BuildContext context,
/// Animation<double> animation,
/// Animation<double> secondaryAnimation,
/// Widget child,
/// ) {
/// return SlideTransition(
/// position: Tween<Offset>(
/// begin: const Offset(0.0, 1.0),
/// end: Offset.zero,
/// ).animate(animation),
/// child: SlideTransition(
/// position: Tween<Offset>(
/// begin: Offset.zero,
/// end: const Offset(0.0, 1.0),
/// ).animate(secondaryAnimation),
/// child: child,
/// ),
/// );
/// },
/// )
/// ```
/// {@end-tool}
///
/// In practice the `secondaryAnimation` is used pretty rarely.
///
/// The arguments to this method are as follows:
///
/// * `context`: The context in which the route is being built.
/// * [animation]: When the [Navigator] pushes a route on the top of its stack,
/// the new route's primary [animation] runs from 0.0 to 1.0. When the [Navigator]
/// pops the topmost route this animation runs from 1.0 to 0.0.
/// * [secondaryAnimation]: When the Navigator pushes a new route
/// on the top of its stack, the old topmost route's [secondaryAnimation]
/// runs from 0.0 to 1.0. When the [Navigator] pops the topmost route, the
/// [secondaryAnimation] for the route below it runs from 1.0 to 0.0.
/// * `child`, the page contents, as returned by [buildPage].
///
/// See also:
///
/// * [buildPage], which is used to describe the actual contents of the page,
/// and whose result is passed to the `child` argument of this method.
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return child;
}
@override
void install() {
super.install();
_animationProxy = ProxyAnimation(super.animation);
_secondaryAnimationProxy = ProxyAnimation(super.secondaryAnimation);
}
@override
TickerFuture didPush() {
if (_scopeKey.currentState != null && navigator!.widget.requestFocus) {
navigator!.focusNode.enclosingScope?.setFirstFocus(_scopeKey.currentState!.focusScopeNode);
}
return super.didPush();
}
@override
void didAdd() {
if (_scopeKey.currentState != null && navigator!.widget.requestFocus) {
navigator!.focusNode.enclosingScope?.setFirstFocus(_scopeKey.currentState!.focusScopeNode);
}
super.didAdd();
}
// The API for subclasses to override - used by this class
/// {@template flutter.widgets.ModalRoute.barrierDismissible}
/// Whether you can dismiss this route by tapping the modal barrier.
///
/// The modal barrier is the scrim that is rendered behind each route, which
/// generally prevents the user from interacting with the route below the
/// current route, and normally partially obscures such routes.
///
/// For example, when a dialog is on the screen, the page below the dialog is
/// usually darkened by the modal barrier.
///
/// If [barrierDismissible] is true, then tapping this barrier, pressing
/// the escape key on the keyboard, or calling route popping functions
/// such as [Navigator.pop] will cause the current route to be popped
/// with null as the value.
///
/// If [barrierDismissible] is false, then tapping the barrier has no effect.
///
/// If this getter would ever start returning a different value,
/// either [changedInternalState] or [changedExternalState] should
/// be invoked so that the change can take effect.
///
/// It is safe to use `navigator.context` to look up inherited
/// widgets here, because the [Navigator] calls
/// [changedExternalState] whenever its dependencies change, and
/// [changedExternalState] causes the modal barrier to rebuild.
///
/// See also:
///
/// * [Navigator.pop], which is used to dismiss the route.
/// * [barrierColor], which controls the color of the scrim for this route.
/// * [ModalBarrier], the widget that implements this feature.
/// {@endtemplate}
bool get barrierDismissible;
/// Whether the semantics of the modal barrier are included in the
/// semantics tree.
///
/// The modal barrier is the scrim that is rendered behind each route, which
/// generally prevents the user from interacting with the route below the
/// current route, and normally partially obscures such routes.
///
/// If [semanticsDismissible] is true, then modal barrier semantics are
/// included in the semantics tree.
///
/// If [semanticsDismissible] is false, then modal barrier semantics are
/// excluded from the semantics tree and tapping on the modal barrier
/// has no effect.
///
/// If this getter would ever start returning a different value,
/// either [changedInternalState] or [changedExternalState] should
/// be invoked so that the change can take effect.
///
/// It is safe to use `navigator.context` to look up inherited
/// widgets here, because the [Navigator] calls
/// [changedExternalState] whenever its dependencies change, and
/// [changedExternalState] causes the modal barrier to rebuild.
bool get semanticsDismissible => true;
/// {@template flutter.widgets.ModalRoute.barrierColor}
/// The color to use for the modal barrier. If this is null, the barrier will
/// be transparent.
///
/// The modal barrier is the scrim that is rendered behind each route, which
/// generally prevents the user from interacting with the route below the
/// current route, and normally partially obscures such routes.
///
/// For example, when a dialog is on the screen, the page below the dialog is
/// usually darkened by the modal barrier.
///
/// The color is ignored, and the barrier made invisible, when
/// [ModalRoute.offstage] is true.
///
/// While the route is animating into position, the color is animated from
/// transparent to the specified color.
/// {@endtemplate}
///
/// If this getter would ever start returning a different color, one
/// of the [changedInternalState] or [changedExternalState] methods
/// should be invoked so that the change can take effect.
///
/// It is safe to use `navigator.context` to look up inherited
/// widgets here, because the [Navigator] calls
/// [changedExternalState] whenever its dependencies change, and
/// [changedExternalState] causes the modal barrier to rebuild.
///
/// {@tool snippet}
///
/// For example, to make the barrier color use the theme's
/// background color, one could say:
///
/// ```dart
/// Color get barrierColor => Theme.of(navigator.context).colorScheme.surface;
/// ```
///
/// {@end-tool}
///
/// See also:
///
/// * [barrierDismissible], which controls the behavior of the barrier when
/// tapped.
/// * [ModalBarrier], the widget that implements this feature.
Color? get barrierColor;
/// {@template flutter.widgets.ModalRoute.barrierLabel}
/// The semantic label used for a dismissible barrier.
///
/// If the barrier is dismissible, this label will be read out if
/// accessibility tools (like VoiceOver on iOS) focus on the barrier.
///
/// The modal barrier is the scrim that is rendered behind each route, which
/// generally prevents the user from interacting with the route below the
/// current route, and normally partially obscures such routes.
///
/// For example, when a dialog is on the screen, the page below the dialog is
/// usually darkened by the modal barrier.
/// {@endtemplate}
///
/// If this getter would ever start returning a different label,
/// either [changedInternalState] or [changedExternalState] should
/// be invoked so that the change can take effect.
///
/// It is safe to use `navigator.context` to look up inherited
/// widgets here, because the [Navigator] calls
/// [changedExternalState] whenever its dependencies change, and
/// [changedExternalState] causes the modal barrier to rebuild.
///
/// See also:
///
/// * [barrierDismissible], which controls the behavior of the barrier when
/// tapped.
/// * [ModalBarrier], the widget that implements this feature.
String? get barrierLabel;
/// The curve that is used for animating the modal barrier in and out.
///
/// The modal barrier is the scrim that is rendered behind each route, which
/// generally prevents the user from interacting with the route below the
/// current route, and normally partially obscures such routes.
///
/// For example, when a dialog is on the screen, the page below the dialog is
/// usually darkened by the modal barrier.
///
/// While the route is animating into position, the color is animated from
/// transparent to the specified [barrierColor].
///
/// If this getter would ever start returning a different curve,
/// either [changedInternalState] or [changedExternalState] should
/// be invoked so that the change can take effect.
///
/// It is safe to use `navigator.context` to look up inherited
/// widgets here, because the [Navigator] calls
/// [changedExternalState] whenever its dependencies change, and
/// [changedExternalState] causes the modal barrier to rebuild.
///
/// It defaults to [Curves.ease].
///
/// See also:
///
/// * [barrierColor], which determines the color that the modal transitions
/// to.
/// * [Curves] for a collection of common curves.
/// * [AnimatedModalBarrier], the widget that implements this feature.
Curve get barrierCurve => Curves.ease;
/// {@template flutter.widgets.ModalRoute.maintainState}
/// Whether the route should remain in memory when it is inactive.
///
/// If this is true, then the route is maintained, so that any futures it is
/// holding from the next route will properly resolve when the next route
/// pops. If this is not necessary, this can be set to false to allow the
/// framework to entirely discard the route's widget hierarchy when it is not
/// visible.
///
/// Setting [maintainState] to false does not guarantee that the route will be
/// discarded. For instance, it will not be discarded if it is still visible
/// because the next above it is not opaque (e.g. it is a popup dialog).
/// {@endtemplate}
///
/// If this getter would ever start returning a different value, the
/// [changedInternalState] should be invoked so that the change can take
/// effect.
///
/// See also:
///
/// * [OverlayEntry.maintainState], which is the underlying implementation
/// of this property.
bool get maintainState;
// The API for _ModalScope and HeroController
/// Whether this route is currently offstage.
///
/// On the first frame of a route's entrance transition, the route is built
/// [Offstage] using an animation progress of 1.0. The route is invisible and
/// non-interactive, but each widget has its final size and position. This
/// mechanism lets the [HeroController] determine the final local of any hero
/// widgets being animated as part of the transition.
///
/// The modal barrier, if any, is not rendered if [offstage] is true (see
/// [barrierColor]).
///
/// Whenever this changes value, [changedInternalState] is called.
bool get offstage => _offstage;
bool _offstage = false;
set offstage(bool value) {
if (_offstage == value) {
return;
}
setState(() {
_offstage = value;
});
_animationProxy!.parent = _offstage ? kAlwaysCompleteAnimation : super.animation;
_secondaryAnimationProxy!.parent = _offstage ? kAlwaysDismissedAnimation : super.secondaryAnimation;
changedInternalState();
}
/// The build context for the subtree containing the primary content of this route.
BuildContext? get subtreeContext => _subtreeKey.currentContext;
@override
Animation<double>? get animation => _animationProxy;
ProxyAnimation? _animationProxy;
@override
Animation<double>? get secondaryAnimation => _secondaryAnimationProxy;
ProxyAnimation? _secondaryAnimationProxy;
final List<WillPopCallback> _willPopCallbacks = <WillPopCallback>[];
final Set<PopEntry> _popEntries = <PopEntry>{};
/// Returns [RoutePopDisposition.doNotPop] if any of callbacks added with
/// [addScopedWillPopCallback] returns either false or null. If they all
/// return true, the base [Route.willPop]'s result will be returned. The
/// callbacks will be called in the order they were added, and will only be
/// called if all previous callbacks returned true.
///
/// Typically this method is not overridden because applications usually
/// don't create modal routes directly, they use higher level primitives
/// like [showDialog]. The scoped [WillPopCallback] list makes it possible
/// for ModalRoute descendants to collectively define the value of [willPop].
///
/// See also:
///
/// * [Form], which provides an `onWillPop` callback that uses this mechanism.
/// * [addScopedWillPopCallback], which adds a callback to the list this
/// method checks.
/// * [removeScopedWillPopCallback], which removes a callback from the list
/// this method checks.
@Deprecated(
'Use popDisposition instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
@override
Future<RoutePopDisposition> willPop() async {
final _ModalScopeState<T>? scope = _scopeKey.currentState;
assert(scope != null);
for (final WillPopCallback callback in List<WillPopCallback>.of(_willPopCallbacks)) {
if (!await callback()) {
return RoutePopDisposition.doNotPop;
}
}
return super.willPop();
}
/// Returns [RoutePopDisposition.doNotPop] if any of the [PopEntry] instances
/// registered with [registerPopEntry] have [PopEntry.canPopNotifier] set to
/// false.
///
/// Typically this method is not overridden because applications usually
/// don't create modal routes directly, they use higher level primitives
/// like [showDialog]. The scoped [PopEntry] list makes it possible for
/// ModalRoute descendants to collectively define the value of
/// [popDisposition].
///
/// See also:
///
/// * [Form], which provides an `onPopInvoked` callback that is similar.
/// * [registerPopEntry], which adds a [PopEntry] to the list this method
/// checks.
/// * [unregisterPopEntry], which removes a [PopEntry] from the list this
/// method checks.
@override
RoutePopDisposition get popDisposition {
final bool canPop = _popEntries.every((PopEntry popEntry) {
return popEntry.canPopNotifier.value;
});
if (!canPop) {
return RoutePopDisposition.doNotPop;
}
return super.popDisposition;
}
@override
void onPopInvoked(bool didPop) {
for (final PopEntry popEntry in _popEntries) {
popEntry.onPopInvoked?.call(didPop);
}
}
/// Enables this route to veto attempts by the user to dismiss it.
///
/// This callback runs asynchronously and it's possible that it will be called
/// after its route has been disposed. The callback should check [State.mounted]
/// before doing anything.
///
/// A typical application of this callback would be to warn the user about
/// unsaved [Form] data if the user attempts to back out of the form. In that
/// case, use the [Form.onWillPop] property to register the callback.
///
/// See also:
///
/// * [WillPopScope], which manages the registration and unregistration
/// process automatically.
/// * [Form], which provides an `onWillPop` callback that uses this mechanism.
/// * [willPop], which runs the callbacks added with this method.
/// * [removeScopedWillPopCallback], which removes a callback from the list
/// that [willPop] checks.
@Deprecated(
'Use registerPopEntry or PopScope instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
void addScopedWillPopCallback(WillPopCallback callback) {
assert(_scopeKey.currentState != null, 'Tried to add a willPop callback to a route that is not currently in the tree.');
_willPopCallbacks.add(callback);
}
/// Remove one of the callbacks run by [willPop].
///
/// See also:
///
/// * [Form], which provides an `onWillPop` callback that uses this mechanism.
/// * [addScopedWillPopCallback], which adds callback to the list
/// checked by [willPop].
@Deprecated(
'Use unregisterPopEntry or PopScope instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
void removeScopedWillPopCallback(WillPopCallback callback) {
assert(_scopeKey.currentState != null, 'Tried to remove a willPop callback from a route that is not currently in the tree.');
_willPopCallbacks.remove(callback);
}
/// Registers the existence of a [PopEntry] in the route.
///
/// [PopEntry] instances registered in this way will have their
/// [PopEntry.onPopInvoked] callbacks called when a route is popped or a pop
/// is attempted. They will also be able to block pop operations with
/// [PopEntry.canPopNotifier] through this route's [popDisposition] method.
///
/// See also:
///
/// * [unregisterPopEntry], which performs the opposite operation.
void registerPopEntry(PopEntry popEntry) {
_popEntries.add(popEntry);
popEntry.canPopNotifier.addListener(_handlePopEntryChange);
_handlePopEntryChange();
}
/// Unregisters a [PopEntry] in the route's widget subtree.
///
/// See also:
///
/// * [registerPopEntry], which performs the opposite operation.
void unregisterPopEntry(PopEntry popEntry) {
_popEntries.remove(popEntry);
popEntry.canPopNotifier.removeListener(_handlePopEntryChange);
_handlePopEntryChange();
}
void _handlePopEntryChange() {
if (!isCurrent) {
return;
}
final NavigationNotification notification = NavigationNotification(
// canPop indicates that the originator of the Notification can handle a
// pop. In the case of PopScope, it handles pops when canPop is
// false. Hence the seemingly backward logic here.
canHandlePop: popDisposition == RoutePopDisposition.doNotPop,
);
// Avoid dispatching a notification in the middle of a build.
switch (SchedulerBinding.instance.schedulerPhase) {
case SchedulerPhase.postFrameCallbacks:
notification.dispatch(subtreeContext);
case SchedulerPhase.idle:
case SchedulerPhase.midFrameMicrotasks:
case SchedulerPhase.persistentCallbacks:
case SchedulerPhase.transientCallbacks:
SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
if (!(subtreeContext?.mounted ?? false)) {
return;
}
notification.dispatch(subtreeContext);
}, debugLabel: 'ModalRoute.dispatchNotification');
}
}
/// True if one or more [WillPopCallback] callbacks exist.
///
/// This method is used to disable the horizontal swipe pop gesture supported
/// by [MaterialPageRoute] for [TargetPlatform.iOS] and
/// [TargetPlatform.macOS]. If a pop might be vetoed, then the back gesture is
/// disabled.
///
/// The [buildTransitions] method will not be called again if this changes,
/// since it can change during the build as descendants of the route add or
/// remove callbacks.
///
/// See also:
///
/// * [addScopedWillPopCallback], which adds a callback.
/// * [removeScopedWillPopCallback], which removes a callback.
/// * [willHandlePopInternally], which reports on another reason why
/// a pop might be vetoed.
@Deprecated(
'Use popDisposition instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
@protected
bool get hasScopedWillPopCallback {
return _willPopCallbacks.isNotEmpty;
}
@override
void didChangePrevious(Route<dynamic>? previousRoute) {
super.didChangePrevious(previousRoute);
changedInternalState();
}
@override
void didChangeNext(Route<dynamic>? nextRoute) {
super.didChangeNext(nextRoute);
changedInternalState();
}
@override
void didPopNext(Route<dynamic> nextRoute) {
super.didPopNext(nextRoute);
changedInternalState();
}
@override
void changedInternalState() {
super.changedInternalState();
// No need to mark dirty if this method is called during build phase.
if (SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks) {
setState(() { /* internal state already changed */ });
_modalBarrier.markNeedsBuild();
}
_modalScope.maintainState = maintainState;
}
@override
void changedExternalState() {
super.changedExternalState();
_modalBarrier.markNeedsBuild();
if (_scopeKey.currentState != null) {
_scopeKey.currentState!._forceRebuildPage();
}
}
/// Whether this route can be popped.
///
/// A route can be popped if there is at least one active route below it, or
/// if [willHandlePopInternally] returns true.
///
/// When this changes, if the route is visible, the route will
/// rebuild, and any widgets that used [ModalRoute.of] will be
/// notified.
bool get canPop => hasActiveRouteBelow || willHandlePopInternally;
/// Whether an [AppBar] in the route should automatically add a back button or
/// close button.
///
/// This getter returns true if there is at least one active route below it,
/// or there is at least one [LocalHistoryEntry] with [impliesAppBarDismissal]
/// set to true
bool get impliesAppBarDismissal => hasActiveRouteBelow || _entriesImpliesAppBarDismissal > 0;
// Internals
final GlobalKey<_ModalScopeState<T>> _scopeKey = GlobalKey<_ModalScopeState<T>>();
final GlobalKey _subtreeKey = GlobalKey();
final PageStorageBucket _storageBucket = PageStorageBucket();
// one of the builders
late OverlayEntry _modalBarrier;
Widget _buildModalBarrier(BuildContext context) {
Widget barrier = buildModalBarrier();
if (filter != null) {
barrier = BackdropFilter(
filter: filter!,
child: barrier,
);
}
barrier = IgnorePointer(
ignoring: animation!.status == AnimationStatus.reverse || // changedInternalState is called when animation.status updates
animation!.status == AnimationStatus.dismissed, // dismissed is possible when doing a manual pop gesture
child: barrier,
);
if (semanticsDismissible && barrierDismissible) {
// To be sorted after the _modalScope.
barrier = Semantics(
sortKey: const OrdinalSortKey(1.0),
child: barrier,
);
}
return barrier;
}
/// Build the barrier for this [ModalRoute], subclasses can override
/// this method to create their own barrier with customized features such as
/// color or accessibility focus size.
///
/// See also:
/// * [ModalBarrier], which is typically used to build a barrier.
/// * [ModalBottomSheetRoute], which overrides this method to build a
/// customized barrier.
Widget buildModalBarrier() {
Widget barrier;
if (barrierColor != null && 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
);
barrier = AnimatedModalBarrier(
color: color,
dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
barrierSemanticsDismissible: semanticsDismissible,
);
} else {
barrier = ModalBarrier(
dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
barrierSemanticsDismissible: semanticsDismissible,
);
}
return barrier;
}
// We cache the part of the modal scope that doesn't change from frame to
// frame so that we minimize the amount of building that happens.
Widget? _modalScopeCache;
// one of the builders
Widget _buildModalScope(BuildContext context) {
// To be sorted before the _modalBarrier.
return _modalScopeCache ??= Semantics(
sortKey: const OrdinalSortKey(0.0),
child: _ModalScope<T>(
key: _scopeKey,
route: this,
// _ModalScope calls buildTransitions() and buildChild(), defined above
),
);
}
late OverlayEntry _modalScope;
@override
Iterable<OverlayEntry> createOverlayEntries() {
return <OverlayEntry>[
_modalBarrier = OverlayEntry(builder: _buildModalBarrier),
_modalScope = OverlayEntry(builder: _buildModalScope, maintainState: maintainState, canSizeOverlay: opaque),
];
}
@override
String toString() => '${objectRuntimeType(this, 'ModalRoute')}($settings, animation: $_animation)';
}
/// A modal route that overlays a widget over the current route.
///
/// {@macro flutter.widgets.ModalRoute.barrierDismissible}
///
/// {@tool dartpad}
/// This example shows how to create a dialog box that is dismissible.
///
/// ** See code in examples/api/lib/widgets/routes/popup_route.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ModalRoute], which is the base class for this class.
/// * [Navigator.pop], which is used to dismiss the route.
abstract class PopupRoute<T> extends ModalRoute<T> {
/// Initializes the [PopupRoute].
PopupRoute({
super.settings,
super.filter,
super.traversalEdgeBehavior,
});
@override
bool get opaque => false;
@override
bool get maintainState => true;
@override
bool get allowSnapshotting => false;
}
/// A [Navigator] observer that notifies [RouteAware]s of changes to the
/// state of their [Route].
///
/// [RouteObserver] informs subscribers whenever a route of type `R` is pushed
/// on top of their own route of type `R` or popped from it. This is for example
/// useful to keep track of page transitions, e.g. a `RouteObserver<PageRoute>`
/// will inform subscribed [RouteAware]s whenever the user navigates away from
/// the current page route to another page route.
///
/// To be informed about route changes of any type, consider instantiating a
/// `RouteObserver<Route>`.
///
/// ## Type arguments
///
/// When using more aggressive [lints](https://dart.dev/lints),
/// in particular lints such as `always_specify_types`,
/// the Dart analyzer will require that certain types
/// be given with their type arguments. Since the [Route] class and its
/// subclasses have a type argument, this includes the arguments passed to this
/// class. Consider using `dynamic` to specify the entire class of routes rather
/// than only specific subtypes. For example, to watch for all [ModalRoute]
/// variants, the `RouteObserver<ModalRoute<dynamic>>` type may be used.
///
/// {@tool dartpad}
/// This example demonstrates how to implement a [RouteObserver] that notifies
/// [RouteAware] widget of changes to the state of their [Route].
///
/// ** See code in examples/api/lib/widgets/routes/route_observer.0.dart **
/// {@end-tool}
///
/// See also:
/// * [RouteAware], this is used with [RouteObserver] to make a widget aware
/// of changes to the [Navigator]'s session history.
class RouteObserver<R extends Route<dynamic>> extends NavigatorObserver {
final Map<R, Set<RouteAware>> _listeners = <R, Set<RouteAware>>{};
/// Whether this observer is managing changes for the specified route.
///
/// If asserts are disabled, this method will throw an exception.
@visibleForTesting
bool debugObservingRoute(R route) {
late bool contained;
assert(() {
contained = _listeners.containsKey(route);
return true;
}());
return contained;
}
/// Subscribe [routeAware] to be informed about changes to [route].
///
/// Going forward, [routeAware] will be informed about qualifying changes
/// to [route], e.g. when [route] is covered by another route or when [route]
/// is popped off the [Navigator] stack.
void subscribe(RouteAware routeAware, R route) {
final Set<RouteAware> subscribers = _listeners.putIfAbsent(route, () => <RouteAware>{});
if (subscribers.add(routeAware)) {
routeAware.didPush();
}
}
/// Unsubscribe [routeAware].
///
/// [routeAware] is no longer informed about changes to its route. If the given argument was
/// subscribed to multiple types, this will unregister it (once) from each type.
void unsubscribe(RouteAware routeAware) {
final List<R> routes = _listeners.keys.toList();
for (final R route in routes) {
final Set<RouteAware>? subscribers = _listeners[route];
if (subscribers != null) {
subscribers.remove(routeAware);
if (subscribers.isEmpty) {
_listeners.remove(route);
}
}
}
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (route is R && previousRoute is R) {
final List<RouteAware>? previousSubscribers = _listeners[previousRoute]?.toList();
if (previousSubscribers != null) {
for (final RouteAware routeAware in previousSubscribers) {
routeAware.didPopNext();
}
}
final List<RouteAware>? subscribers = _listeners[route]?.toList();
if (subscribers != null) {
for (final RouteAware routeAware in subscribers) {
routeAware.didPop();
}
}
}
}
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (route is R && previousRoute is R) {
final Set<RouteAware>? previousSubscribers = _listeners[previousRoute];
if (previousSubscribers != null) {
for (final RouteAware routeAware in previousSubscribers) {
routeAware.didPushNext();
}
}
}
}
}
/// An interface for objects that are aware of their current [Route].
///
/// This is used with [RouteObserver] to make a widget aware of changes to the
/// [Navigator]'s session history.
abstract mixin class RouteAware {
/// Called when the top route has been popped off, and the current route
/// shows up.
void didPopNext() { }
/// Called when the current route has been pushed.
void didPush() { }
/// Called when the current route has been popped off.
void didPop() { }
/// Called when a new route has been pushed, and the current route is no
/// longer visible.
void didPushNext() { }
}
/// A general dialog route which allows for customization of the dialog popup.
///
/// It is used internally by [showGeneralDialog] or can be directly pushed
/// onto the [Navigator] stack to enable state restoration. See
/// [showGeneralDialog] for a state restoration app example.
///
/// This function takes a `pageBuilder`, which typically builds a dialog.
/// 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 `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 `settings` argument define the settings for this route. See
/// [RouteSettings] for details.
///
/// {@template flutter.widgets.RawDialogRoute}
/// A [DisplayFeature] can split the screen into sub-screens. The closest one to
/// [anchorPoint] is used to render the content.
///
/// If no [anchorPoint] is provided, then [Directionality] is used:
///
/// * for [TextDirection.ltr], [anchorPoint] is `Offset.zero`, which will
/// cause the content to appear in the top-left sub-screen.
/// * for [TextDirection.rtl], [anchorPoint] is `Offset(double.maxFinite, 0)`,
/// which will cause the content to appear in the top-right sub-screen.
///
/// If no [anchorPoint] is provided, and there is no [Directionality] ancestor
/// widget in the tree, then the widget asserts during build in debug mode.
/// {@endtemplate}
///
/// See also:
///
/// * [DisplayFeatureSubScreen], which documents the specifics of how
/// [DisplayFeature]s can split the screen into sub-screens.
/// * [showGeneralDialog], which is a way to display a RawDialogRoute.
/// * [showDialog], which is a way to display a DialogRoute.
/// * [showCupertinoDialog], which displays an iOS-style dialog.
class RawDialogRoute<T> extends PopupRoute<T> {
/// A general dialog route which allows for customization of the dialog popup.
RawDialogRoute({
required RoutePageBuilder pageBuilder,
bool barrierDismissible = true,
Color? barrierColor = const Color(0x80000000),
String? barrierLabel,
Duration transitionDuration = const Duration(milliseconds: 200),
RouteTransitionsBuilder? transitionBuilder,
super.settings,
this.anchorPoint,
super.traversalEdgeBehavior,
}) : _pageBuilder = pageBuilder,
_barrierDismissible = barrierDismissible,
_barrierLabel = barrierLabel,
_barrierColor = barrierColor,
_transitionDuration = transitionDuration,
_transitionBuilder = transitionBuilder;
final RoutePageBuilder _pageBuilder;
@override
bool get barrierDismissible => _barrierDismissible;
final bool _barrierDismissible;
@override
String? get barrierLabel => _barrierLabel;
final String? _barrierLabel;
@override
Color? get barrierColor => _barrierColor;
final Color? _barrierColor;
@override
Duration get transitionDuration => _transitionDuration;
final Duration _transitionDuration;
final RouteTransitionsBuilder? _transitionBuilder;
/// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint}
final Offset? anchorPoint;
@override
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
return Semantics(
scopesRoute: true,
explicitChildNodes: true,
child: DisplayFeatureSubScreen(
anchorPoint: anchorPoint,
child: _pageBuilder(context, animation, secondaryAnimation),
),
);
}
@override
Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
if (_transitionBuilder == null) {
// Some default transition.
return FadeTransition(
opacity: CurvedAnimation(
parent: animation,
curve: Curves.linear,
),
child: child,
);
}
return _transitionBuilder(context, animation, secondaryAnimation, child);
}
}
/// Displays a dialog above the current contents of the app.
///
/// This function allows for customization of aspects of the dialog popup.
///
/// This function takes a `pageBuilder` which is used to build the primary
/// content of the route (typically a dialog widget). Content below the dialog
/// is dimmed with a [ModalBarrier]. The widget returned by the `pageBuilder`
/// does not share a context with the location that [showGeneralDialog] 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] 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 `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.
///
/// 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)`.
///
/// The `barrierDismissible` argument is used to determine whether this route
/// can be dismissed by tapping the modal barrier. This argument defaults
/// to false. If `barrierDismissible` is true, a non-null `barrierLabel` must be
/// provided.
///
/// The `barrierLabel` argument is the semantic label used for a dismissible
/// barrier. This argument defaults to `null`.
///
/// The `barrierColor` argument is the color used for the modal barrier. This
/// argument defaults to `Color(0x80000000)`.
///
/// The `transitionDuration` argument is used to determine how long it takes
/// for the route to arrive on or leave off the screen. This argument defaults
/// to 200 milliseconds.
///
/// The `transitionBuilder` argument is used to define how the route arrives on
/// and leaves off the screen. By default, the transition is a linear fade of
/// the page's contents.
///
/// The `routeSettings` will be used in the construction of the dialog's route.
/// See [RouteSettings] for more details.
///
/// {@macro flutter.widgets.RawDialogRoute}
///
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
/// ### 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 [RawDialogRoute].
///
/// For more information about state restoration, see [RestorationManager].
///
/// {@tool sample}
/// This sample demonstrates how to create a restorable dialog. This is
/// accomplished by enabling state restoration by specifying
/// [WidgetsApp.restorationScopeId] and using [Navigator.restorablePush] to
/// push [RawDialogRoute] when the button is tapped.
///
/// {@macro flutter.widgets.RestorationManager}
///
/// ** See code in examples/api/lib/widgets/routes/show_general_dialog.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [DisplayFeatureSubScreen], which documents the specifics of how
/// [DisplayFeature]s can split the screen into sub-screens.
/// * [showDialog], which displays a Material-style dialog.
/// * [showCupertinoDialog], which displays an iOS-style dialog.
Future<T?> showGeneralDialog<T extends Object?>({
required BuildContext context,
required RoutePageBuilder pageBuilder,
bool barrierDismissible = false,
String? barrierLabel,
Color barrierColor = const Color(0x80000000),
Duration transitionDuration = const Duration(milliseconds: 200),
RouteTransitionsBuilder? transitionBuilder,
bool useRootNavigator = true,
RouteSettings? routeSettings,
Offset? anchorPoint,
}) {
assert(!barrierDismissible || barrierLabel != null);
return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(RawDialogRoute<T>(
pageBuilder: pageBuilder,
barrierDismissible: barrierDismissible,
barrierLabel: barrierLabel,
barrierColor: barrierColor,
transitionDuration: transitionDuration,
transitionBuilder: transitionBuilder,
settings: routeSettings,
anchorPoint: anchorPoint,
));
}
/// Signature for the function that builds a route's primary contents.
/// Used in [PageRouteBuilder] and [showGeneralDialog].
///
/// See [ModalRoute.buildPage] for complete definition of the parameters.
typedef RoutePageBuilder = Widget Function(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation);
/// Signature for the function that builds a route's transitions.
/// Used in [PageRouteBuilder] and [showGeneralDialog].
///
/// See [ModalRoute.buildTransitions] for complete definition of the parameters.
typedef RouteTransitionsBuilder = Widget Function(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child);
/// A callback type for informing that a navigation pop has been invoked,
/// whether or not it was handled successfully.
///
/// Accepts a didPop boolean indicating whether or not back navigation
/// succeeded.
typedef PopInvokedCallback = void Function(bool didPop);
/// Allows listening to and preventing pops.
///
/// Can be registered in [ModalRoute] to listen to pops with [onPopInvoked] or
/// to enable/disable them with [canPopNotifier].
///
/// See also:
///
/// * [PopScope], which provides similar functionality in a widget.
/// * [ModalRoute.registerPopEntry], which unregisters instances of this.
/// * [ModalRoute.unregisterPopEntry], which unregisters instances of this.
abstract class PopEntry {
/// {@macro flutter.widgets.PopScope.onPopInvoked}
PopInvokedCallback? get onPopInvoked;
/// {@macro flutter.widgets.PopScope.canPop}
ValueListenable<bool> get canPopNotifier;
@override
String toString() {
return 'PopEntry canPop: ${canPopNotifier.value}, onPopInvoked: $onPopInvoked';
}
}
| flutter/packages/flutter/lib/src/widgets/routes.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/routes.dart",
"repo_id": "flutter",
"token_count": 28320
} | 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 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'basic.dart';
import 'framework.dart';
import 'gesture_detector.dart';
import 'media_query.dart';
import 'notification_listener.dart';
import 'restoration.dart';
import 'restoration_properties.dart';
import 'scroll_activity.dart';
import 'scroll_configuration.dart';
import 'scroll_context.dart';
import 'scroll_controller.dart';
import 'scroll_physics.dart';
import 'scroll_position.dart';
import 'scrollable_helpers.dart';
import 'selectable_region.dart';
import 'selection_container.dart';
import 'ticker_provider.dart';
import 'view.dart';
import 'viewport.dart';
export 'package:flutter/physics.dart' show Tolerance;
// Examples can assume:
// late BuildContext context;
/// Signature used by [Scrollable] to build the viewport through which the
/// scrollable content is displayed.
typedef ViewportBuilder = Widget Function(BuildContext context, ViewportOffset position);
/// Signature used by [TwoDimensionalScrollable] to build the viewport through
/// which the scrollable content is displayed.
typedef TwoDimensionalViewportBuilder = Widget Function(BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition);
// The return type of _performEnsureVisible.
//
// The list of futures represents each pending ScrollPosition call to
// ensureVisible. The returned ScrollableState's context is used to find the
// next potential ancestor Scrollable.
typedef _EnsureVisibleResults = (List<Future<void>>, ScrollableState);
/// A widget that manages scrolling in one dimension and informs the [Viewport]
/// through which the content is viewed.
///
/// [Scrollable] implements the interaction model for a scrollable widget,
/// including gesture recognition, but does not have an opinion about how the
/// viewport, which actually displays the children, is constructed.
///
/// It's rare to construct a [Scrollable] directly. Instead, consider [ListView]
/// or [GridView], which combine scrolling, viewporting, and a layout model. To
/// combine layout models (or to use a custom layout mode), consider using
/// [CustomScrollView].
///
/// The static [Scrollable.of] and [Scrollable.ensureVisible] functions are
/// often used to interact with the [Scrollable] widget inside a [ListView] or
/// a [GridView].
///
/// To further customize scrolling behavior with a [Scrollable]:
///
/// 1. You can provide a [viewportBuilder] to customize the child model. For
/// example, [SingleChildScrollView] uses a viewport that displays a single
/// box child whereas [CustomScrollView] uses a [Viewport] or a
/// [ShrinkWrappingViewport], both of which display a list of slivers.
///
/// 2. You can provide a custom [ScrollController] that creates a custom
/// [ScrollPosition] subclass. For example, [PageView] uses a
/// [PageController], which creates a page-oriented scroll position subclass
/// that keeps the same page visible when the [Scrollable] resizes.
///
/// ## Persisting the scroll position during a session
///
/// Scrollables attempt to persist their scroll position using [PageStorage].
/// This can be disabled by setting [ScrollController.keepScrollOffset] to false
/// on the [controller]. If it is enabled, using a [PageStorageKey] for the
/// [key] of this widget (or one of its ancestors, e.g. a [ScrollView]) is
/// recommended to help disambiguate different [Scrollable]s from each other.
///
/// See also:
///
/// * [ListView], which is a commonly used [ScrollView] that displays a
/// scrolling, linear list of child widgets.
/// * [PageView], which is a scrolling list of child widgets that are each the
/// size of the viewport.
/// * [GridView], which is a [ScrollView] that displays a scrolling, 2D array
/// of child widgets.
/// * [CustomScrollView], which is a [ScrollView] that creates custom scroll
/// effects using slivers.
/// * [SingleChildScrollView], which is a scrollable widget that has a single
/// child.
/// * [ScrollNotification] and [NotificationListener], which can be used to watch
/// the scroll position without using a [ScrollController].
class Scrollable extends StatefulWidget {
/// Creates a widget that scrolls.
const Scrollable({
super.key,
this.axisDirection = AxisDirection.down,
this.controller,
this.physics,
required this.viewportBuilder,
this.incrementCalculator,
this.excludeFromSemantics = false,
this.semanticChildCount,
this.dragStartBehavior = DragStartBehavior.start,
this.restorationId,
this.scrollBehavior,
this.clipBehavior = Clip.hardEdge,
}) : assert(semanticChildCount == null || semanticChildCount >= 0);
/// {@template flutter.widgets.Scrollable.axisDirection}
/// The direction in which this widget scrolls.
///
/// For example, if the [Scrollable.axisDirection] is [AxisDirection.down],
/// increasing the scroll position will cause content below the bottom of the
/// viewport to become visible through the viewport. Similarly, if the
/// axisDirection is [AxisDirection.right], increasing the scroll position
/// will cause content beyond the right edge of the viewport to become visible
/// through the viewport.
///
/// Defaults to [AxisDirection.down].
/// {@endtemplate}
final AxisDirection axisDirection;
/// {@template flutter.widgets.Scrollable.controller}
/// An object that can be used to control the position to which this widget is
/// scrolled.
///
/// A [ScrollController] serves several purposes. It can be used to control
/// the initial scroll position (see [ScrollController.initialScrollOffset]).
/// It can be used to control whether the scroll view should automatically
/// save and restore its scroll position in the [PageStorage] (see
/// [ScrollController.keepScrollOffset]). It can be used to read the current
/// scroll position (see [ScrollController.offset]), or change it (see
/// [ScrollController.animateTo]).
///
/// If null, a [ScrollController] will be created internally by [Scrollable]
/// in order to create and manage the [ScrollPosition].
///
/// See also:
///
/// * [Scrollable.ensureVisible], which animates the scroll position to
/// reveal a given [BuildContext].
/// {@endtemplate}
final ScrollController? controller;
/// {@template flutter.widgets.Scrollable.physics}
/// How the widgets should respond to user input.
///
/// For example, determines how the widget continues to animate after the
/// user stops dragging the scroll view.
///
/// Defaults to matching platform conventions via the physics provided from
/// the ambient [ScrollConfiguration].
///
/// If an explicit [ScrollBehavior] is provided to
/// [Scrollable.scrollBehavior], the [ScrollPhysics] provided by that behavior
/// will take precedence after [Scrollable.physics].
///
/// The physics can be changed dynamically, but new physics will only take
/// effect if the _class_ of the provided object changes. Merely constructing
/// a new instance with a different configuration is insufficient to cause the
/// physics to be reapplied. (This is because the final object used is
/// generated dynamically, which can be relatively expensive, and it would be
/// inefficient to speculatively create this object each frame to see if the
/// physics should be updated.)
///
/// See also:
///
/// * [AlwaysScrollableScrollPhysics], which can be used to indicate that the
/// scrollable should react to scroll requests (and possible overscroll)
/// even if the scrollable's contents fit without scrolling being necessary.
/// {@endtemplate}
final ScrollPhysics? physics;
/// Builds the viewport through which the scrollable content is displayed.
///
/// A typical viewport uses the given [ViewportOffset] to determine which part
/// of its content is actually visible through the viewport.
///
/// See also:
///
/// * [Viewport], which is a viewport that displays a list of slivers.
/// * [ShrinkWrappingViewport], which is a viewport that displays a list of
/// slivers and sizes itself based on the size of the slivers.
final ViewportBuilder viewportBuilder;
/// {@template flutter.widgets.Scrollable.incrementCalculator}
/// An optional function that will be called to calculate the distance to
/// scroll when the scrollable is asked to scroll via the keyboard using a
/// [ScrollAction].
///
/// If not supplied, the [Scrollable] will scroll a default amount when a
/// keyboard navigation key is pressed (e.g. pageUp/pageDown, control-upArrow,
/// etc.), or otherwise invoked by a [ScrollAction].
///
/// If [incrementCalculator] is null, the default for
/// [ScrollIncrementType.page] is 80% of the size of the scroll window, and
/// for [ScrollIncrementType.line], 50 logical pixels.
/// {@endtemplate}
final ScrollIncrementCalculator? incrementCalculator;
/// {@template flutter.widgets.scrollable.excludeFromSemantics}
/// Whether the scroll actions introduced by this [Scrollable] are exposed
/// in the semantics tree.
///
/// Text fields with an overflow are usually scrollable to make sure that the
/// user can get to the beginning/end of the entered text. However, these
/// scrolling actions are generally not exposed to the semantics layer.
/// {@endtemplate}
///
/// See also:
///
/// * [GestureDetector.excludeFromSemantics], which is used to accomplish the
/// exclusion.
final bool excludeFromSemantics;
/// The number of children that will contribute semantic information.
///
/// The value will be null if the number of children is unknown or unbounded.
///
/// Some subtypes of [ScrollView] can infer this value automatically. For
/// example [ListView] will use the number of widgets in the child list,
/// while the [ListView.separated] constructor will use half that amount.
///
/// For [CustomScrollView] and other types which do not receive a builder
/// or list of widgets, the child count must be explicitly provided.
///
/// See also:
///
/// * [CustomScrollView], for an explanation of scroll semantics.
/// * [SemanticsConfiguration.scrollChildCount], the corresponding semantics property.
final int? semanticChildCount;
// TODO(jslavitz): Set the DragStartBehavior default to be start across all widgets.
/// {@template flutter.widgets.scrollable.dragStartBehavior}
/// Determines the way that drag start behavior is handled.
///
/// If set to [DragStartBehavior.start], scrolling drag behavior will
/// begin at the position where the drag gesture won the arena. If set to
/// [DragStartBehavior.down] it will begin at the position where a down
/// event is first detected.
///
/// In general, setting this to [DragStartBehavior.start] will make drag
/// animation smoother and setting it to [DragStartBehavior.down] will make
/// drag behavior feel slightly more reactive.
///
/// By default, the drag start behavior is [DragStartBehavior.start].
///
/// See also:
///
/// * [DragGestureRecognizer.dragStartBehavior], which gives an example for
/// the different behaviors.
///
/// {@endtemplate}
final DragStartBehavior dragStartBehavior;
/// {@template flutter.widgets.scrollable.restorationId}
/// Restoration ID to save and restore the scroll offset of the scrollable.
///
/// If a restoration id is provided, the scrollable will persist its current
/// scroll offset and restore it during state restoration.
///
/// The scroll offset is persisted in a [RestorationBucket] claimed from
/// the surrounding [RestorationScope] using the provided restoration ID.
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
/// {@endtemplate}
final String? restorationId;
/// {@macro flutter.widgets.shadow.scrollBehavior}
///
/// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit
/// [ScrollPhysics] is provided in [physics], it will take precedence,
/// followed by [scrollBehavior], and then the inherited ancestor
/// [ScrollBehavior].
final ScrollBehavior? scrollBehavior;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
///
/// This is passed to decorators in [ScrollableDetails], and does not directly affect
/// clipping of the [Scrollable]. This reflects the same [Clip] that is provided
/// to [ScrollView.clipBehavior] and is supplied to the [Viewport].
final Clip clipBehavior;
/// The axis along which the scroll view scrolls.
///
/// Determined by the [axisDirection].
Axis get axis => axisDirectionToAxis(axisDirection);
@override
ScrollableState createState() => ScrollableState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<AxisDirection>('axisDirection', axisDirection));
properties.add(DiagnosticsProperty<ScrollPhysics>('physics', physics));
properties.add(StringProperty('restorationId', restorationId));
}
/// The state from the closest instance of this class that encloses the given
/// context, or null if none is found.
///
/// Typical usage is as follows:
///
/// ```dart
/// ScrollableState? scrollable = Scrollable.maybeOf(context);
/// ```
///
/// Calling this method will create a dependency on the [ScrollableState]
/// that is returned, if there is one. This is typically the closest
/// [Scrollable], but may be a more distant ancestor if [axis] is used to
/// target a specific [Scrollable].
///
/// Using the optional [Axis] is useful when Scrollables are nested and the
/// target [Scrollable] is not the closest instance. When [axis] is provided,
/// the nearest enclosing [ScrollableState] in that [Axis] is returned, or
/// null if there is none.
///
/// This finds the nearest _ancestor_ [Scrollable] of the `context`. This
/// means that if the `context` is that of a [Scrollable], it will _not_ find
/// _that_ [Scrollable].
///
/// See also:
///
/// * [Scrollable.of], which is similar to this method, but asserts
/// if no [Scrollable] ancestor is found.
static ScrollableState? maybeOf(BuildContext context, { Axis? axis }) {
// This is the context that will need to establish the dependency.
final BuildContext originalContext = context;
InheritedElement? element = context.getElementForInheritedWidgetOfExactType<_ScrollableScope>();
while (element != null) {
final ScrollableState scrollable = (element.widget as _ScrollableScope).scrollable;
if (axis == null || axisDirectionToAxis(scrollable.axisDirection) == axis) {
// Establish the dependency on the correct context.
originalContext.dependOnInheritedElement(element);
return scrollable;
}
context = scrollable.context;
element = context.getElementForInheritedWidgetOfExactType<_ScrollableScope>();
}
return null;
}
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// Typical usage is as follows:
///
/// ```dart
/// ScrollableState scrollable = Scrollable.of(context);
/// ```
///
/// Calling this method will create a dependency on the [ScrollableState]
/// that is returned, if there is one. This is typically the closest
/// [Scrollable], but may be a more distant ancestor if [axis] is used to
/// target a specific [Scrollable].
///
/// Using the optional [Axis] is useful when Scrollables are nested and the
/// target [Scrollable] is not the closest instance. When [axis] is provided,
/// the nearest enclosing [ScrollableState] in that [Axis] is returned.
///
/// This finds the nearest _ancestor_ [Scrollable] of the `context`. This
/// means that if the `context` is that of a [Scrollable], it will _not_ find
/// _that_ [Scrollable].
///
/// If no [Scrollable] ancestor is found, then this method will assert in
/// debug mode, and throw an exception in release mode.
///
/// See also:
///
/// * [Scrollable.maybeOf], which is similar to this method, but returns null
/// if no [Scrollable] ancestor is found.
static ScrollableState of(BuildContext context, { Axis? axis }) {
final ScrollableState? scrollableState = maybeOf(context, axis: axis);
assert(() {
if (scrollableState == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'Scrollable.of() was called with a context that does not contain a '
'Scrollable widget.',
),
ErrorDescription(
'No Scrollable widget ancestor could be found '
'${axis == null ? '' : 'for the provided Axis: $axis '}'
'starting from the context that was passed to Scrollable.of(). This '
'can happen because you are using a widget that looks for a Scrollable '
'ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
),
if (axis != null) ErrorHint(
'When specifying an axis, this method will only look for a Scrollable '
'that matches the given Axis.',
),
]);
}
return true;
}());
return scrollableState!;
}
/// Provides a heuristic to determine if expensive frame-bound tasks should be
/// deferred for the [context] at a specific point in time.
///
/// Calling this method does _not_ create a dependency on any other widget.
/// This also means that the value returned is only good for the point in time
/// when it is called, and callers will not get updated if the value changes.
///
/// The heuristic used is determined by the [physics] of this [Scrollable]
/// via [ScrollPhysics.recommendDeferredLoading]. That method is called with
/// the current [ScrollPosition.activity]'s [ScrollActivity.velocity].
///
/// The optional [Axis] allows targeting of a specific [Scrollable] of that
/// axis, useful when Scrollables are nested. When [axis] is provided,
/// [ScrollPosition.recommendDeferredLoading] is called for the nearest
/// [Scrollable] in that [Axis].
///
/// If there is no [Scrollable] in the widget tree above the [context], this
/// method returns false.
static bool recommendDeferredLoadingForContext(BuildContext context, { Axis? axis }) {
_ScrollableScope? widget = context.getInheritedWidgetOfExactType<_ScrollableScope>();
while (widget != null) {
if (axis == null || axisDirectionToAxis(widget.scrollable.axisDirection) == axis) {
return widget.position.recommendDeferredLoading(context);
}
context = widget.scrollable.context;
widget = context.getInheritedWidgetOfExactType<_ScrollableScope>();
}
return false;
}
/// Scrolls the scrollables that enclose the given context so as to make the
/// given context visible.
///
/// If the [Scrollable] of the provided [BuildContext] is a
/// [TwoDimensionalScrollable], both vertical and horizontal axes will ensure
/// the target is made visible.
static Future<void> ensureVisible(
BuildContext context, {
double alignment = 0.0,
Duration duration = Duration.zero,
Curve curve = Curves.ease,
ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit,
}) {
final List<Future<void>> futures = <Future<void>>[];
// The targetRenderObject is used to record the first target renderObject.
// If there are multiple scrollable widgets nested, the targetRenderObject
// is made to be as visible as possible to improve the user experience. If
// the targetRenderObject is already visible, then let the outer
// renderObject be as visible as possible.
//
// Also see https://github.com/flutter/flutter/issues/65100
RenderObject? targetRenderObject;
ScrollableState? scrollable = Scrollable.maybeOf(context);
while (scrollable != null) {
final List<Future<void>> newFutures;
(newFutures, scrollable) = scrollable._performEnsureVisible(
context.findRenderObject()!,
alignment: alignment,
duration: duration,
curve: curve,
alignmentPolicy: alignmentPolicy,
targetRenderObject: targetRenderObject,
);
futures.addAll(newFutures);
targetRenderObject ??= context.findRenderObject();
context = scrollable.context;
scrollable = Scrollable.maybeOf(context);
}
if (futures.isEmpty || duration == Duration.zero) {
return Future<void>.value();
}
if (futures.length == 1) {
return futures.single;
}
return Future.wait<void>(futures).then<void>((List<void> _) => null);
}
}
// Enable Scrollable.of() to work as if ScrollableState was an inherited widget.
// ScrollableState.build() always rebuilds its _ScrollableScope.
class _ScrollableScope extends InheritedWidget {
const _ScrollableScope({
required this.scrollable,
required this.position,
required super.child,
});
final ScrollableState scrollable;
final ScrollPosition position;
@override
bool updateShouldNotify(_ScrollableScope old) {
return position != old.position;
}
}
/// State object for a [Scrollable] widget.
///
/// To manipulate a [Scrollable] widget's scroll position, use the object
/// obtained from the [position] property.
///
/// To be informed of when a [Scrollable] widget is scrolling, use a
/// [NotificationListener] to listen for [ScrollNotification] notifications.
///
/// This class is not intended to be subclassed. To specialize the behavior of a
/// [Scrollable], provide it with a [ScrollPhysics].
class ScrollableState extends State<Scrollable> with TickerProviderStateMixin, RestorationMixin
implements ScrollContext {
// GETTERS
/// The manager for this [Scrollable] widget's viewport position.
///
/// To control what kind of [ScrollPosition] is created for a [Scrollable],
/// provide it with custom [ScrollController] that creates the appropriate
/// [ScrollPosition] in its [ScrollController.createScrollPosition] method.
ScrollPosition get position => _position!;
ScrollPosition? _position;
/// The resolved [ScrollPhysics] of the [ScrollableState].
ScrollPhysics? get resolvedPhysics => _physics;
ScrollPhysics? _physics;
/// An [Offset] that represents the absolute distance from the origin, or 0,
/// of the [ScrollPosition] expressed in the associated [Axis].
///
/// Used by [EdgeDraggingAutoScroller] to progress the position forward when a
/// drag gesture reaches the edge of the [Viewport].
Offset get deltaToScrollOrigin {
return switch (axisDirection) {
AxisDirection.up => Offset(0, -position.pixels),
AxisDirection.down => Offset(0, position.pixels),
AxisDirection.left => Offset(-position.pixels, 0),
AxisDirection.right => Offset(position.pixels, 0),
};
}
ScrollController get _effectiveScrollController => widget.controller ?? _fallbackScrollController!;
@override
AxisDirection get axisDirection => widget.axisDirection;
@override
TickerProvider get vsync => this;
@override
double get devicePixelRatio => _devicePixelRatio;
late double _devicePixelRatio;
@override
BuildContext? get notificationContext => _gestureDetectorKey.currentContext;
@override
BuildContext get storageContext => context;
@override
String? get restorationId => widget.restorationId;
final _RestorableScrollOffset _persistedScrollOffset = _RestorableScrollOffset();
late ScrollBehavior _configuration;
ScrollController? _fallbackScrollController;
DeviceGestureSettings? _mediaQueryGestureSettings;
// Only call this from places that will definitely trigger a rebuild.
void _updatePosition() {
_configuration = widget.scrollBehavior ?? ScrollConfiguration.of(context);
_physics = _configuration.getScrollPhysics(context);
if (widget.physics != null) {
_physics = widget.physics!.applyTo(_physics);
} else if (widget.scrollBehavior != null) {
_physics = widget.scrollBehavior!.getScrollPhysics(context).applyTo(_physics);
}
final ScrollPosition? oldPosition = _position;
if (oldPosition != null) {
_effectiveScrollController.detach(oldPosition);
// It's important that we not dispose the old position until after the
// viewport has had a chance to unregister its listeners from the old
// position. So, schedule a microtask to do it.
scheduleMicrotask(oldPosition.dispose);
}
_position = _effectiveScrollController.createScrollPosition(_physics!, this, oldPosition);
assert(_position != null);
_effectiveScrollController.attach(position);
}
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_persistedScrollOffset, 'offset');
assert(_position != null);
if (_persistedScrollOffset.value != null) {
position.restoreOffset(_persistedScrollOffset.value!, initialRestore: initialRestore);
}
}
@override
void saveOffset(double offset) {
assert(debugIsSerializableForRestoration(offset));
_persistedScrollOffset.value = offset;
// [saveOffset] is called after a scrolling ends and it is usually not
// followed by a frame. Therefore, manually flush restoration data.
ServicesBinding.instance.restorationManager.flushData();
}
@override
void initState() {
if (widget.controller == null) {
_fallbackScrollController = ScrollController();
}
super.initState();
}
@override
void didChangeDependencies() {
_mediaQueryGestureSettings = MediaQuery.maybeGestureSettingsOf(context);
_devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context) ?? View.of(context).devicePixelRatio;
_updatePosition();
super.didChangeDependencies();
}
bool _shouldUpdatePosition(Scrollable oldWidget) {
if ((widget.scrollBehavior == null) != (oldWidget.scrollBehavior == null)) {
return true;
}
if (widget.scrollBehavior != null && oldWidget.scrollBehavior != null && widget.scrollBehavior!.shouldNotify(oldWidget.scrollBehavior!)) {
return true;
}
ScrollPhysics? newPhysics = widget.physics ?? widget.scrollBehavior?.getScrollPhysics(context);
ScrollPhysics? oldPhysics = oldWidget.physics ?? oldWidget.scrollBehavior?.getScrollPhysics(context);
do {
if (newPhysics?.runtimeType != oldPhysics?.runtimeType) {
return true;
}
newPhysics = newPhysics?.parent;
oldPhysics = oldPhysics?.parent;
} while (newPhysics != null || oldPhysics != null);
return widget.controller?.runtimeType != oldWidget.controller?.runtimeType;
}
@override
void didUpdateWidget(Scrollable oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller != oldWidget.controller) {
if (oldWidget.controller == null) {
// The old controller was null, meaning the fallback cannot be null.
// Dispose of the fallback.
assert(_fallbackScrollController != null);
assert(widget.controller != null);
_fallbackScrollController!.detach(position);
_fallbackScrollController!.dispose();
_fallbackScrollController = null;
} else {
// The old controller was not null, detach.
oldWidget.controller?.detach(position);
if (widget.controller == null) {
// If the new controller is null, we need to set up the fallback
// ScrollController.
_fallbackScrollController = ScrollController();
}
}
// Attach the updated effective scroll controller.
_effectiveScrollController.attach(position);
}
if (_shouldUpdatePosition(oldWidget)) {
_updatePosition();
}
}
@override
void dispose() {
if (widget.controller != null) {
widget.controller!.detach(position);
} else {
_fallbackScrollController?.detach(position);
_fallbackScrollController?.dispose();
}
position.dispose();
_persistedScrollOffset.dispose();
super.dispose();
}
// SEMANTICS
final GlobalKey _scrollSemanticsKey = GlobalKey();
@override
@protected
void setSemanticsActions(Set<SemanticsAction> actions) {
if (_gestureDetectorKey.currentState != null) {
_gestureDetectorKey.currentState!.replaceSemanticsActions(actions);
}
}
// GESTURE RECOGNITION AND POINTER IGNORING
final GlobalKey<RawGestureDetectorState> _gestureDetectorKey = GlobalKey<RawGestureDetectorState>();
final GlobalKey _ignorePointerKey = GlobalKey();
// This field is set during layout, and then reused until the next time it is set.
Map<Type, GestureRecognizerFactory> _gestureRecognizers = const <Type, GestureRecognizerFactory>{};
bool _shouldIgnorePointer = false;
bool? _lastCanDrag;
Axis? _lastAxisDirection;
@override
@protected
void setCanDrag(bool value) {
if (value == _lastCanDrag && (!value || widget.axis == _lastAxisDirection)) {
return;
}
if (!value) {
_gestureRecognizers = const <Type, GestureRecognizerFactory>{};
// Cancel the active hold/drag (if any) because the gesture recognizers
// will soon be disposed by our RawGestureDetector, and we won't be
// receiving pointer up events to cancel the hold/drag.
_handleDragCancel();
} else {
switch (widget.axis) {
case Axis.vertical:
_gestureRecognizers = <Type, GestureRecognizerFactory>{
VerticalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<VerticalDragGestureRecognizer>(
() => VerticalDragGestureRecognizer(supportedDevices: _configuration.dragDevices),
(VerticalDragGestureRecognizer instance) {
instance
..onDown = _handleDragDown
..onStart = _handleDragStart
..onUpdate = _handleDragUpdate
..onEnd = _handleDragEnd
..onCancel = _handleDragCancel
..minFlingDistance = _physics?.minFlingDistance
..minFlingVelocity = _physics?.minFlingVelocity
..maxFlingVelocity = _physics?.maxFlingVelocity
..velocityTrackerBuilder = _configuration.velocityTrackerBuilder(context)
..dragStartBehavior = widget.dragStartBehavior
..multitouchDragStrategy = _configuration.getMultitouchDragStrategy(context)
..gestureSettings = _mediaQueryGestureSettings
..supportedDevices = _configuration.dragDevices;
},
),
};
case Axis.horizontal:
_gestureRecognizers = <Type, GestureRecognizerFactory>{
HorizontalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>(
() => HorizontalDragGestureRecognizer(supportedDevices: _configuration.dragDevices),
(HorizontalDragGestureRecognizer instance) {
instance
..onDown = _handleDragDown
..onStart = _handleDragStart
..onUpdate = _handleDragUpdate
..onEnd = _handleDragEnd
..onCancel = _handleDragCancel
..minFlingDistance = _physics?.minFlingDistance
..minFlingVelocity = _physics?.minFlingVelocity
..maxFlingVelocity = _physics?.maxFlingVelocity
..velocityTrackerBuilder = _configuration.velocityTrackerBuilder(context)
..dragStartBehavior = widget.dragStartBehavior
..multitouchDragStrategy = _configuration.getMultitouchDragStrategy(context)
..gestureSettings = _mediaQueryGestureSettings
..supportedDevices = _configuration.dragDevices;
},
),
};
}
}
_lastCanDrag = value;
_lastAxisDirection = widget.axis;
if (_gestureDetectorKey.currentState != null) {
_gestureDetectorKey.currentState!.replaceGestureRecognizers(_gestureRecognizers);
}
}
@override
@protected
void setIgnorePointer(bool value) {
if (_shouldIgnorePointer == value) {
return;
}
_shouldIgnorePointer = value;
if (_ignorePointerKey.currentContext != null) {
final RenderIgnorePointer renderBox = _ignorePointerKey.currentContext!.findRenderObject()! as RenderIgnorePointer;
renderBox.ignoring = _shouldIgnorePointer;
}
}
// TOUCH HANDLERS
Drag? _drag;
ScrollHoldController? _hold;
void _handleDragDown(DragDownDetails details) {
assert(_drag == null);
assert(_hold == null);
_hold = position.hold(_disposeHold);
}
void _handleDragStart(DragStartDetails details) {
// It's possible for _hold to become null between _handleDragDown and
// _handleDragStart, for example if some user code calls jumpTo or otherwise
// triggers a new activity to begin.
assert(_drag == null);
_drag = position.drag(details, _disposeDrag);
assert(_drag != null);
assert(_hold == null);
}
void _handleDragUpdate(DragUpdateDetails details) {
// _drag might be null if the drag activity ended and called _disposeDrag.
assert(_hold == null || _drag == null);
_drag?.update(details);
}
void _handleDragEnd(DragEndDetails details) {
// _drag might be null if the drag activity ended and called _disposeDrag.
assert(_hold == null || _drag == null);
_drag?.end(details);
assert(_drag == null);
}
void _handleDragCancel() {
if (_gestureDetectorKey.currentContext == null) {
// The cancel was caused by the GestureDetector getting disposed, which
// means we will get disposed momentarily as well and shouldn't do
// any work.
return;
}
// _hold might be null if the drag started.
// _drag might be null if the drag activity ended and called _disposeDrag.
assert(_hold == null || _drag == null);
_hold?.cancel();
_drag?.cancel();
assert(_hold == null);
assert(_drag == null);
}
void _disposeHold() {
_hold = null;
}
void _disposeDrag() {
_drag = null;
}
// SCROLL WHEEL
// Returns the offset that should result from applying [event] to the current
// position, taking min/max scroll extent into account.
double _targetScrollOffsetForPointerScroll(double delta) {
return math.min(
math.max(position.pixels + delta, position.minScrollExtent),
position.maxScrollExtent,
);
}
// Returns the delta that should result from applying [event] with axis,
// direction, and any modifiers specified by the ScrollBehavior taken into
// account.
double _pointerSignalEventDelta(PointerScrollEvent event) {
final Set<LogicalKeyboardKey> pressed = HardwareKeyboard.instance.logicalKeysPressed;
final bool flipAxes = pressed.any(_configuration.pointerAxisModifiers.contains) &&
// Axes are only flipped for physical mouse wheel input.
// On some platforms, like web, trackpad input is handled through pointer
// signals, but should not be included in this axis modifying behavior.
// This is because on a trackpad, all directional axes are available to
// the user, while mouse scroll wheels typically are restricted to one
// axis.
event.kind == PointerDeviceKind.mouse;
final Axis axis = flipAxes ? flipAxis(widget.axis) : widget.axis;
final double delta = switch (axis) {
Axis.horizontal => event.scrollDelta.dx,
Axis.vertical => event.scrollDelta.dy,
};
return axisDirectionIsReversed(widget.axisDirection) ? -delta : delta;
}
void _receivedPointerSignal(PointerSignalEvent event) {
if (event is PointerScrollEvent && _position != null) {
if (_physics != null && !_physics!.shouldAcceptUserOffset(position)) {
return;
}
final double delta = _pointerSignalEventDelta(event);
final double targetScrollOffset = _targetScrollOffsetForPointerScroll(delta);
// Only express interest in the event if it would actually result in a scroll.
if (delta != 0.0 && targetScrollOffset != position.pixels) {
GestureBinding.instance.pointerSignalResolver.register(event, _handlePointerScroll);
}
} else if (event is PointerScrollInertiaCancelEvent) {
position.pointerScroll(0);
// Don't use the pointer signal resolver, all hit-tested scrollables should stop.
}
}
void _handlePointerScroll(PointerEvent event) {
assert(event is PointerScrollEvent);
final double delta = _pointerSignalEventDelta(event as PointerScrollEvent);
final double targetScrollOffset = _targetScrollOffsetForPointerScroll(delta);
if (delta != 0.0 && targetScrollOffset != position.pixels) {
position.pointerScroll(delta);
}
}
bool _handleScrollMetricsNotification(ScrollMetricsNotification notification) {
if (notification.depth == 0) {
final RenderObject? scrollSemanticsRenderObject = _scrollSemanticsKey.currentContext?.findRenderObject();
if (scrollSemanticsRenderObject != null) {
scrollSemanticsRenderObject.markNeedsSemanticsUpdate();
}
}
return false;
}
Widget _buildChrome(BuildContext context, Widget child) {
final ScrollableDetails details = ScrollableDetails(
direction: widget.axisDirection,
controller: _effectiveScrollController,
decorationClipBehavior: widget.clipBehavior,
);
return _configuration.buildScrollbar(
context,
_configuration.buildOverscrollIndicator(context, child, details),
details,
);
}
// DESCRIPTION
@override
Widget build(BuildContext context) {
assert(_position != null);
// _ScrollableScope must be placed above the BuildContext returned by notificationContext
// so that we can get this ScrollableState by doing the following:
//
// ScrollNotification notification;
// Scrollable.of(notification.context)
//
// Since notificationContext is pointing to _gestureDetectorKey.context, _ScrollableScope
// must be placed above the widget using it: RawGestureDetector
Widget result = _ScrollableScope(
scrollable: this,
position: position,
child: Listener(
onPointerSignal: _receivedPointerSignal,
child: RawGestureDetector(
key: _gestureDetectorKey,
gestures: _gestureRecognizers,
behavior: HitTestBehavior.opaque,
excludeFromSemantics: widget.excludeFromSemantics,
child: Semantics(
explicitChildNodes: !widget.excludeFromSemantics,
child: IgnorePointer(
key: _ignorePointerKey,
ignoring: _shouldIgnorePointer,
child: widget.viewportBuilder(context, position),
),
),
),
),
);
if (!widget.excludeFromSemantics) {
result = NotificationListener<ScrollMetricsNotification>(
onNotification: _handleScrollMetricsNotification,
child: _ScrollSemantics(
key: _scrollSemanticsKey,
position: position,
allowImplicitScrolling: _physics!.allowImplicitScrolling,
semanticChildCount: widget.semanticChildCount,
child: result,
)
);
}
result = _buildChrome(context, result);
// Selection is only enabled when there is a parent registrar.
final SelectionRegistrar? registrar = SelectionContainer.maybeOf(context);
if (registrar != null) {
result = _ScrollableSelectionHandler(
state: this,
position: position,
registrar: registrar,
child: result,
);
}
return result;
}
// Returns the Future from calling ensureVisible for the ScrollPosition, as
// as well as this ScrollableState instance so its context can be used to
// check for other ancestor Scrollables in executing ensureVisible.
_EnsureVisibleResults _performEnsureVisible(
RenderObject object, {
double alignment = 0.0,
Duration duration = Duration.zero,
Curve curve = Curves.ease,
ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit,
RenderObject? targetRenderObject,
}) {
final Future<void> ensureVisibleFuture = position.ensureVisible(
object,
alignment: alignment,
duration: duration,
curve: curve,
alignmentPolicy: alignmentPolicy,
targetRenderObject: targetRenderObject,
);
return (<Future<void>>[ ensureVisibleFuture ], this);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ScrollPosition>('position', _position));
properties.add(DiagnosticsProperty<ScrollPhysics>('effective physics', _physics));
}
}
/// A widget to handle selection for a scrollable.
///
/// This widget registers itself to the [registrar] and uses
/// [SelectionContainer] to collect selectables from its subtree.
class _ScrollableSelectionHandler extends StatefulWidget {
const _ScrollableSelectionHandler({
required this.state,
required this.position,
required this.registrar,
required this.child,
});
final ScrollableState state;
final ScrollPosition position;
final Widget child;
final SelectionRegistrar registrar;
@override
_ScrollableSelectionHandlerState createState() => _ScrollableSelectionHandlerState();
}
class _ScrollableSelectionHandlerState extends State<_ScrollableSelectionHandler> {
late _ScrollableSelectionContainerDelegate _selectionDelegate;
@override
void initState() {
super.initState();
_selectionDelegate = _ScrollableSelectionContainerDelegate(
state: widget.state,
position: widget.position,
);
}
@override
void didUpdateWidget(_ScrollableSelectionHandler oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.position != widget.position) {
_selectionDelegate.position = widget.position;
}
}
@override
void dispose() {
_selectionDelegate.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SelectionContainer(
registrar: widget.registrar,
delegate: _selectionDelegate,
child: widget.child,
);
}
}
/// This updater handles the case where the selectables change frequently, and
/// it optimizes toward scrolling updates.
///
/// It keeps track of the drag start offset relative to scroll origin for every
/// selectable. The records are used to determine whether the selection is up to
/// date with the scroll position when it sends the drag update event to a
/// selectable.
class _ScrollableSelectionContainerDelegate extends MultiSelectableSelectionContainerDelegate {
_ScrollableSelectionContainerDelegate({
required this.state,
required ScrollPosition position
}) : _position = position,
_autoScroller = EdgeDraggingAutoScroller(state, velocityScalar: _kDefaultSelectToScrollVelocityScalar) {
_position.addListener(_scheduleLayoutChange);
}
// Pointer drag is a single point, it should not have a size.
static const double _kDefaultDragTargetSize = 0;
// An eye-balled value for a smooth scrolling speed.
static const double _kDefaultSelectToScrollVelocityScalar = 30;
final ScrollableState state;
final EdgeDraggingAutoScroller _autoScroller;
bool _scheduledLayoutChange = false;
Offset? _currentDragStartRelatedToOrigin;
Offset? _currentDragEndRelatedToOrigin;
// The scrollable only auto scrolls if the selection starts in the scrollable.
bool _selectionStartsInScrollable = false;
ScrollPosition get position => _position;
ScrollPosition _position;
set position(ScrollPosition other) {
if (other == _position) {
return;
}
_position.removeListener(_scheduleLayoutChange);
_position = other;
_position.addListener(_scheduleLayoutChange);
}
// The layout will only be updated a frame later than position changes.
// Schedule PostFrameCallback to capture the accurate layout.
void _scheduleLayoutChange() {
if (_scheduledLayoutChange) {
return;
}
_scheduledLayoutChange = true;
SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
if (!_scheduledLayoutChange) {
return;
}
_scheduledLayoutChange = false;
layoutDidChange();
}, debugLabel: 'ScrollableSelectionContainer.layoutDidChange');
}
/// Stores the scroll offset when a scrollable receives the last
/// [SelectionEdgeUpdateEvent].
///
/// The stored scroll offset may be null if a scrollable never receives a
/// [SelectionEdgeUpdateEvent].
///
/// When a new [SelectionEdgeUpdateEvent] is dispatched to a selectable, this
/// updater checks the current scroll offset against the one stored in these
/// records. If the scroll offset is different, it synthesizes an opposite
/// [SelectionEdgeUpdateEvent] and dispatches the event before dispatching the
/// new event.
///
/// For example, if a selectable receives an end [SelectionEdgeUpdateEvent]
/// and its scroll offset in the records is different from the current value,
/// it synthesizes a start [SelectionEdgeUpdateEvent] and dispatches it before
/// dispatching the original end [SelectionEdgeUpdateEvent].
final Map<Selectable, double> _selectableStartEdgeUpdateRecords = <Selectable, double>{};
final Map<Selectable, double> _selectableEndEdgeUpdateRecords = <Selectable, double>{};
@override
void didChangeSelectables() {
final Set<Selectable> selectableSet = selectables.toSet();
_selectableStartEdgeUpdateRecords.removeWhere((Selectable key, double value) => !selectableSet.contains(key));
_selectableEndEdgeUpdateRecords.removeWhere((Selectable key, double value) => !selectableSet.contains(key));
super.didChangeSelectables();
}
@override
SelectionResult handleClearSelection(ClearSelectionEvent event) {
_selectableStartEdgeUpdateRecords.clear();
_selectableEndEdgeUpdateRecords.clear();
_currentDragStartRelatedToOrigin = null;
_currentDragEndRelatedToOrigin = null;
_selectionStartsInScrollable = false;
return super.handleClearSelection(event);
}
@override
SelectionResult handleSelectionEdgeUpdate(SelectionEdgeUpdateEvent event) {
if (_currentDragEndRelatedToOrigin == null && _currentDragStartRelatedToOrigin == null) {
assert(!_selectionStartsInScrollable);
_selectionStartsInScrollable = _globalPositionInScrollable(event.globalPosition);
}
final Offset deltaToOrigin = _getDeltaToScrollOrigin(state);
if (event.type == SelectionEventType.endEdgeUpdate) {
_currentDragEndRelatedToOrigin = _inferPositionRelatedToOrigin(event.globalPosition);
final Offset endOffset = _currentDragEndRelatedToOrigin!.translate(-deltaToOrigin.dx, -deltaToOrigin.dy);
event = SelectionEdgeUpdateEvent.forEnd(globalPosition: endOffset, granularity: event.granularity);
} else {
_currentDragStartRelatedToOrigin = _inferPositionRelatedToOrigin(event.globalPosition);
final Offset startOffset = _currentDragStartRelatedToOrigin!.translate(-deltaToOrigin.dx, -deltaToOrigin.dy);
event = SelectionEdgeUpdateEvent.forStart(globalPosition: startOffset, granularity: event.granularity);
}
final SelectionResult result = super.handleSelectionEdgeUpdate(event);
// Result may be pending if one of the selectable child is also a scrollable.
// In that case, the parent scrollable needs to wait for the child to finish
// scrolling.
if (result == SelectionResult.pending) {
_autoScroller.stopAutoScroll();
return result;
}
if (_selectionStartsInScrollable) {
_autoScroller.startAutoScrollIfNecessary(_dragTargetFromEvent(event));
if (_autoScroller.scrolling) {
return SelectionResult.pending;
}
}
return result;
}
Offset _inferPositionRelatedToOrigin(Offset globalPosition) {
final RenderBox box = state.context.findRenderObject()! as RenderBox;
final Offset localPosition = box.globalToLocal(globalPosition);
if (!_selectionStartsInScrollable) {
// If the selection starts outside of the scrollable, selecting across the
// scrollable boundary will act as selecting the entire content in the
// scrollable. This logic move the offset to the 0.0 or infinity to cover
// the entire content if the input position is outside of the scrollable.
if (localPosition.dy < 0 || localPosition.dx < 0) {
return box.localToGlobal(Offset.zero);
}
if (localPosition.dy > box.size.height || localPosition.dx > box.size.width) {
return Offset.infinite;
}
}
final Offset deltaToOrigin = _getDeltaToScrollOrigin(state);
return box.localToGlobal(localPosition.translate(deltaToOrigin.dx, deltaToOrigin.dy));
}
/// Infers the [_currentDragStartRelatedToOrigin] and
/// [_currentDragEndRelatedToOrigin] from the geometry.
///
/// This method is called after a select word and select all event where the
/// selection is triggered by none drag events. The
/// [_currentDragStartRelatedToOrigin] and [_currentDragEndRelatedToOrigin]
/// are essential to handle future [SelectionEdgeUpdateEvent]s.
void _updateDragLocationsFromGeometries({bool forceUpdateStart = true, bool forceUpdateEnd = true}) {
final Offset deltaToOrigin = _getDeltaToScrollOrigin(state);
final RenderBox box = state.context.findRenderObject()! as RenderBox;
final Matrix4 transform = box.getTransformTo(null);
if (currentSelectionStartIndex != -1 && (_currentDragStartRelatedToOrigin == null || forceUpdateStart)) {
final SelectionGeometry geometry = selectables[currentSelectionStartIndex].value;
assert(geometry.hasSelection);
final SelectionPoint start = geometry.startSelectionPoint!;
final Matrix4 childTransform = selectables[currentSelectionStartIndex].getTransformTo(box);
final Offset localDragStart = MatrixUtils.transformPoint(
childTransform,
start.localPosition + Offset(0, - start.lineHeight / 2),
);
_currentDragStartRelatedToOrigin = MatrixUtils.transformPoint(transform, localDragStart + deltaToOrigin);
}
if (currentSelectionEndIndex != -1 && (_currentDragEndRelatedToOrigin == null || forceUpdateEnd)) {
final SelectionGeometry geometry = selectables[currentSelectionEndIndex].value;
assert(geometry.hasSelection);
final SelectionPoint end = geometry.endSelectionPoint!;
final Matrix4 childTransform = selectables[currentSelectionEndIndex].getTransformTo(box);
final Offset localDragEnd = MatrixUtils.transformPoint(
childTransform,
end.localPosition + Offset(0, - end.lineHeight / 2),
);
_currentDragEndRelatedToOrigin = MatrixUtils.transformPoint(transform, localDragEnd + deltaToOrigin);
}
}
@override
SelectionResult handleSelectAll(SelectAllSelectionEvent event) {
assert(!_selectionStartsInScrollable);
final SelectionResult result = super.handleSelectAll(event);
assert((currentSelectionStartIndex == -1) == (currentSelectionEndIndex == -1));
if (currentSelectionStartIndex != -1) {
_updateDragLocationsFromGeometries();
}
return result;
}
@override
SelectionResult handleSelectWord(SelectWordSelectionEvent event) {
_selectionStartsInScrollable = _globalPositionInScrollable(event.globalPosition);
final SelectionResult result = super.handleSelectWord(event);
_updateDragLocationsFromGeometries();
return result;
}
@override
SelectionResult handleGranularlyExtendSelection(GranularlyExtendSelectionEvent event) {
final SelectionResult result = super.handleGranularlyExtendSelection(event);
// The selection geometry may not have the accurate offset for the edges
// that are outside of the viewport whose transform may not be valid. Only
// the edge this event is updating is sure to be accurate.
_updateDragLocationsFromGeometries(
forceUpdateStart: !event.isEnd,
forceUpdateEnd: event.isEnd,
);
if (_selectionStartsInScrollable) {
_jumpToEdge(event.isEnd);
}
return result;
}
@override
SelectionResult handleDirectionallyExtendSelection(DirectionallyExtendSelectionEvent event) {
final SelectionResult result = super.handleDirectionallyExtendSelection(event);
// The selection geometry may not have the accurate offset for the edges
// that are outside of the viewport whose transform may not be valid. Only
// the edge this event is updating is sure to be accurate.
_updateDragLocationsFromGeometries(
forceUpdateStart: !event.isEnd,
forceUpdateEnd: event.isEnd,
);
if (_selectionStartsInScrollable) {
_jumpToEdge(event.isEnd);
}
return result;
}
void _jumpToEdge(bool isExtent) {
final Selectable selectable;
final double? lineHeight;
final SelectionPoint? edge;
if (isExtent) {
selectable = selectables[currentSelectionEndIndex];
edge = selectable.value.endSelectionPoint;
lineHeight = selectable.value.endSelectionPoint!.lineHeight;
} else {
selectable = selectables[currentSelectionStartIndex];
edge = selectable.value.startSelectionPoint;
lineHeight = selectable.value.startSelectionPoint?.lineHeight;
}
if (lineHeight == null || edge == null) {
return;
}
final RenderBox scrollableBox = state.context.findRenderObject()! as RenderBox;
final Matrix4 transform = selectable.getTransformTo(scrollableBox);
final Offset edgeOffsetInScrollableCoordinates = MatrixUtils.transformPoint(transform, edge.localPosition);
final Rect scrollableRect = Rect.fromLTRB(0, 0, scrollableBox.size.width, scrollableBox.size.height);
switch (state.axisDirection) {
case AxisDirection.up:
final double edgeBottom = edgeOffsetInScrollableCoordinates.dy;
final double edgeTop = edgeOffsetInScrollableCoordinates.dy - lineHeight;
if (edgeBottom >= scrollableRect.bottom && edgeTop <= scrollableRect.top) {
return;
}
if (edgeBottom > scrollableRect.bottom) {
position.jumpTo(position.pixels + scrollableRect.bottom - edgeBottom);
return;
}
if (edgeTop < scrollableRect.top) {
position.jumpTo(position.pixels + scrollableRect.top - edgeTop);
}
return;
case AxisDirection.right:
final double edge = edgeOffsetInScrollableCoordinates.dx;
if (edge >= scrollableRect.right && edge <= scrollableRect.left) {
return;
}
if (edge > scrollableRect.right) {
position.jumpTo(position.pixels + edge - scrollableRect.right);
return;
}
if (edge < scrollableRect.left) {
position.jumpTo(position.pixels + edge - scrollableRect.left);
}
return;
case AxisDirection.down:
final double edgeBottom = edgeOffsetInScrollableCoordinates.dy;
final double edgeTop = edgeOffsetInScrollableCoordinates.dy - lineHeight;
if (edgeBottom >= scrollableRect.bottom && edgeTop <= scrollableRect.top) {
return;
}
if (edgeBottom > scrollableRect.bottom) {
position.jumpTo(position.pixels + edgeBottom - scrollableRect.bottom);
return;
}
if (edgeTop < scrollableRect.top) {
position.jumpTo(position.pixels + edgeTop - scrollableRect.top);
}
return;
case AxisDirection.left:
final double edge = edgeOffsetInScrollableCoordinates.dx;
if (edge >= scrollableRect.right && edge <= scrollableRect.left) {
return;
}
if (edge > scrollableRect.right) {
position.jumpTo(position.pixels + scrollableRect.right - edge);
return;
}
if (edge < scrollableRect.left) {
position.jumpTo(position.pixels + scrollableRect.left - edge);
}
return;
}
}
bool _globalPositionInScrollable(Offset globalPosition) {
final RenderBox box = state.context.findRenderObject()! as RenderBox;
final Offset localPosition = box.globalToLocal(globalPosition);
final Rect rect = Rect.fromLTWH(0, 0, box.size.width, box.size.height);
return rect.contains(localPosition);
}
Rect _dragTargetFromEvent(SelectionEdgeUpdateEvent event) {
return Rect.fromCenter(center: event.globalPosition, width: _kDefaultDragTargetSize, height: _kDefaultDragTargetSize);
}
@override
SelectionResult dispatchSelectionEventToChild(Selectable selectable, SelectionEvent event) {
switch (event.type) {
case SelectionEventType.startEdgeUpdate:
_selectableStartEdgeUpdateRecords[selectable] = state.position.pixels;
ensureChildUpdated(selectable);
case SelectionEventType.endEdgeUpdate:
_selectableEndEdgeUpdateRecords[selectable] = state.position.pixels;
ensureChildUpdated(selectable);
case SelectionEventType.granularlyExtendSelection:
case SelectionEventType.directionallyExtendSelection:
ensureChildUpdated(selectable);
_selectableStartEdgeUpdateRecords[selectable] = state.position.pixels;
_selectableEndEdgeUpdateRecords[selectable] = state.position.pixels;
case SelectionEventType.clear:
_selectableEndEdgeUpdateRecords.remove(selectable);
_selectableStartEdgeUpdateRecords.remove(selectable);
case SelectionEventType.selectAll:
case SelectionEventType.selectWord:
_selectableEndEdgeUpdateRecords[selectable] = state.position.pixels;
_selectableStartEdgeUpdateRecords[selectable] = state.position.pixels;
}
return super.dispatchSelectionEventToChild(selectable, event);
}
@override
void ensureChildUpdated(Selectable selectable) {
final double newRecord = state.position.pixels;
final double? previousStartRecord = _selectableStartEdgeUpdateRecords[selectable];
if (_currentDragStartRelatedToOrigin != null &&
(previousStartRecord == null || (newRecord - previousStartRecord).abs() > precisionErrorTolerance)) {
// Make sure the selectable has up to date events.
final Offset deltaToOrigin = _getDeltaToScrollOrigin(state);
final Offset startOffset = _currentDragStartRelatedToOrigin!.translate(-deltaToOrigin.dx, -deltaToOrigin.dy);
selectable.dispatchSelectionEvent(SelectionEdgeUpdateEvent.forStart(globalPosition: startOffset));
// Make sure we track that we have synthesized a start event for this selectable,
// so we don't synthesize events unnecessarily.
_selectableStartEdgeUpdateRecords[selectable] = state.position.pixels;
}
final double? previousEndRecord = _selectableEndEdgeUpdateRecords[selectable];
if (_currentDragEndRelatedToOrigin != null &&
(previousEndRecord == null || (newRecord - previousEndRecord).abs() > precisionErrorTolerance)) {
// Make sure the selectable has up to date events.
final Offset deltaToOrigin = _getDeltaToScrollOrigin(state);
final Offset endOffset = _currentDragEndRelatedToOrigin!.translate(-deltaToOrigin.dx, -deltaToOrigin.dy);
selectable.dispatchSelectionEvent(SelectionEdgeUpdateEvent.forEnd(globalPosition: endOffset));
// Make sure we track that we have synthesized an end event for this selectable,
// so we don't synthesize events unnecessarily.
_selectableEndEdgeUpdateRecords[selectable] = state.position.pixels;
}
}
@override
void dispose() {
_selectableStartEdgeUpdateRecords.clear();
_selectableEndEdgeUpdateRecords.clear();
_scheduledLayoutChange = false;
_autoScroller.stopAutoScroll();
super.dispose();
}
}
Offset _getDeltaToScrollOrigin(ScrollableState scrollableState) {
return switch (scrollableState.axisDirection) {
AxisDirection.up => Offset(0, -scrollableState.position.pixels),
AxisDirection.down => Offset(0, scrollableState.position.pixels),
AxisDirection.left => Offset(-scrollableState.position.pixels, 0),
AxisDirection.right => Offset(scrollableState.position.pixels, 0),
};
}
/// With [_ScrollSemantics] certain child [SemanticsNode]s can be
/// excluded from the scrollable area for semantics purposes.
///
/// Nodes, that are to be excluded, have to be tagged with
/// [RenderViewport.excludeFromScrolling] and the [RenderAbstractViewport] in
/// use has to add the [RenderViewport.useTwoPaneSemantics] tag to its
/// [SemanticsConfiguration] by overriding
/// [RenderObject.describeSemanticsConfiguration].
///
/// If the tag [RenderViewport.useTwoPaneSemantics] is present on the viewport,
/// two semantics nodes will be used to represent the [Scrollable]: The outer
/// node will contain all children, that are excluded from scrolling. The inner
/// node, which is annotated with the scrolling actions, will house the
/// scrollable children.
class _ScrollSemantics extends SingleChildRenderObjectWidget {
const _ScrollSemantics({
super.key,
required this.position,
required this.allowImplicitScrolling,
required this.semanticChildCount,
super.child,
}) : assert(semanticChildCount == null || semanticChildCount >= 0);
final ScrollPosition position;
final bool allowImplicitScrolling;
final int? semanticChildCount;
@override
_RenderScrollSemantics createRenderObject(BuildContext context) {
return _RenderScrollSemantics(
position: position,
allowImplicitScrolling: allowImplicitScrolling,
semanticChildCount: semanticChildCount,
);
}
@override
void updateRenderObject(BuildContext context, _RenderScrollSemantics renderObject) {
renderObject
..allowImplicitScrolling = allowImplicitScrolling
..position = position
..semanticChildCount = semanticChildCount;
}
}
class _RenderScrollSemantics extends RenderProxyBox {
_RenderScrollSemantics({
required ScrollPosition position,
required bool allowImplicitScrolling,
required int? semanticChildCount,
RenderBox? child,
}) : _position = position,
_allowImplicitScrolling = allowImplicitScrolling,
_semanticChildCount = semanticChildCount,
super(child) {
position.addListener(markNeedsSemanticsUpdate);
}
/// Whether this render object is excluded from the semantic tree.
ScrollPosition get position => _position;
ScrollPosition _position;
set position(ScrollPosition value) {
if (value == _position) {
return;
}
_position.removeListener(markNeedsSemanticsUpdate);
_position = value;
_position.addListener(markNeedsSemanticsUpdate);
markNeedsSemanticsUpdate();
}
/// Whether this node can be scrolled implicitly.
bool get allowImplicitScrolling => _allowImplicitScrolling;
bool _allowImplicitScrolling;
set allowImplicitScrolling(bool value) {
if (value == _allowImplicitScrolling) {
return;
}
_allowImplicitScrolling = value;
markNeedsSemanticsUpdate();
}
int? get semanticChildCount => _semanticChildCount;
int? _semanticChildCount;
set semanticChildCount(int? value) {
if (value == semanticChildCount) {
return;
}
_semanticChildCount = value;
markNeedsSemanticsUpdate();
}
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
config.isSemanticBoundary = true;
if (position.haveDimensions) {
config
..hasImplicitScrolling = allowImplicitScrolling
..scrollPosition = _position.pixels
..scrollExtentMax = _position.maxScrollExtent
..scrollExtentMin = _position.minScrollExtent
..scrollChildCount = semanticChildCount;
}
}
SemanticsNode? _innerNode;
@override
void assembleSemanticsNode(SemanticsNode node, SemanticsConfiguration config, Iterable<SemanticsNode> children) {
if (children.isEmpty || !children.first.isTagged(RenderViewport.useTwoPaneSemantics)) {
_innerNode = null;
super.assembleSemanticsNode(node, config, children);
return;
}
(_innerNode ??= SemanticsNode(showOnScreen: showOnScreen)).rect = node.rect;
int? firstVisibleIndex;
final List<SemanticsNode> excluded = <SemanticsNode>[_innerNode!];
final List<SemanticsNode> included = <SemanticsNode>[];
for (final SemanticsNode child in children) {
assert(child.isTagged(RenderViewport.useTwoPaneSemantics));
if (child.isTagged(RenderViewport.excludeFromScrolling)) {
excluded.add(child);
} else {
if (!child.hasFlag(SemanticsFlag.isHidden)) {
firstVisibleIndex ??= child.indexInParent;
}
included.add(child);
}
}
config.scrollIndex = firstVisibleIndex;
node.updateWith(config: null, childrenInInversePaintOrder: excluded);
_innerNode!.updateWith(config: config, childrenInInversePaintOrder: included);
}
@override
void clearSemantics() {
super.clearSemantics();
_innerNode = null;
}
}
// Not using a RestorableDouble because we want to allow null values and override
// [enabled].
class _RestorableScrollOffset extends RestorableValue<double?> {
@override
double? createDefaultValue() => null;
@override
void didUpdateValue(double? oldValue) {
notifyListeners();
}
@override
double fromPrimitives(Object? data) {
return data! as double;
}
@override
Object? toPrimitives() {
return value;
}
@override
bool get enabled => value != null;
}
// 2D SCROLLING
/// Specifies how to configure the [DragGestureRecognizer]s of a
/// [TwoDimensionalScrollable].
// TODO(Piinks): Add sample code, https://github.com/flutter/flutter/issues/126298
enum DiagonalDragBehavior {
/// This behavior will not allow for any diagonal scrolling.
///
/// Drag gestures in one direction or the other will lock the input axis until
/// the gesture is released.
none,
/// This behavior will only allow diagonal scrolling on a weighted
/// scale per gesture event.
///
/// This means that after initially evaluating the drag gesture, the weighted
/// evaluation (based on [kTouchSlop]) stands until the gesture is released.
weightedEvent,
/// This behavior will only allow diagonal scrolling on a weighted
/// scale that is evaluated throughout a gesture event.
///
/// This means that during each update to the drag gesture, the scrolling
/// axis will be allowed to scroll diagonally if it exceeds the
/// [kTouchSlop].
weightedContinuous,
/// This behavior allows free movement in any and all directions when
/// dragging.
free,
}
/// A widget that manages scrolling in both the vertical and horizontal
/// dimensions and informs the [TwoDimensionalViewport] through which the
/// content is viewed.
///
/// [TwoDimensionalScrollable] implements the interaction model for a scrollable
/// widget in both the vertical and horizontal axes, including gesture
/// recognition, but does not have an opinion about how the
/// [TwoDimensionalViewport], which actually displays the children, is
/// constructed.
///
/// It's rare to construct a [TwoDimensionalScrollable] directly. Instead,
/// consider subclassing [TwoDimensionalScrollView], which combines scrolling,
/// viewporting, and a layout model in both dimensions.
///
/// See also:
///
/// * [TwoDimensionalScrollView], an abstract base class for displaying a
/// scrolling array of children in both directions.
/// * [TwoDimensionalViewport], which can be used to customize the child layout
/// model.
class TwoDimensionalScrollable extends StatefulWidget {
/// Creates a widget that scrolls in two dimensions.
///
/// The [horizontalDetails], [verticalDetails], and [viewportBuilder] must not
/// be null.
const TwoDimensionalScrollable({
super.key,
required this.horizontalDetails,
required this.verticalDetails,
required this.viewportBuilder,
this.incrementCalculator,
this.restorationId,
this.excludeFromSemantics = false,
this.diagonalDragBehavior = DiagonalDragBehavior.none,
this.dragStartBehavior = DragStartBehavior.start,
});
/// How scrolling gestures should lock to one axis, or allow free movement
/// in both axes.
final DiagonalDragBehavior diagonalDragBehavior;
/// The configuration of the horizontal [Scrollable].
///
/// These [ScrollableDetails] can be used to set the [AxisDirection],
/// [ScrollController], [ScrollPhysics] and more for the horizontal axis.
final ScrollableDetails horizontalDetails;
/// The configuration of the vertical [Scrollable].
///
/// These [ScrollableDetails] can be used to set the [AxisDirection],
/// [ScrollController], [ScrollPhysics] and more for the vertical axis.
final ScrollableDetails verticalDetails;
/// Builds the viewport through which the scrollable content is displayed.
///
/// A [TwoDimensionalViewport] uses two given [ViewportOffset]s to determine
/// which part of its content is actually visible through the viewport.
///
/// See also:
///
/// * [TwoDimensionalViewport], which is a viewport that displays a span of
/// widgets in both dimensions.
final TwoDimensionalViewportBuilder viewportBuilder;
/// {@macro flutter.widgets.Scrollable.incrementCalculator}
///
/// This value applies in both axes.
final ScrollIncrementCalculator? incrementCalculator;
/// {@macro flutter.widgets.scrollable.restorationId}
///
/// Internally, the [TwoDimensionalScrollable] will introduce a
/// [RestorationScope] that will be assigned this value. The two [Scrollable]s
/// within will then be given unique IDs within this scope.
final String? restorationId;
/// {@macro flutter.widgets.scrollable.excludeFromSemantics}
///
/// This value applies to both axes.
final bool excludeFromSemantics;
/// {@macro flutter.widgets.scrollable.dragStartBehavior}
///
/// This value applies in both axes.
final DragStartBehavior dragStartBehavior;
@override
State<TwoDimensionalScrollable> createState() => TwoDimensionalScrollableState();
/// The state from the closest instance of this class that encloses the given
/// context, or null if none is found.
///
/// Typical usage is as follows:
///
/// ```dart
/// TwoDimensionalScrollableState? scrollable = TwoDimensionalScrollable.maybeOf(context);
/// ```
///
/// Calling this method will create a dependency on the closest
/// [TwoDimensionalScrollable] in the [context]. The internal [Scrollable]s
/// can be accessed through [TwoDimensionalScrollableState.verticalScrollable]
/// and [TwoDimensionalScrollableState.horizontalScrollable].
///
/// Alternatively, [Scrollable.maybeOf] can be used by providing the desired
/// [Axis] to the `axis` parameter.
///
/// See also:
///
/// * [TwoDimensionalScrollable.of], which is similar to this method, but
/// asserts if no [Scrollable] ancestor is found.
static TwoDimensionalScrollableState? maybeOf(BuildContext context) {
final _TwoDimensionalScrollableScope? widget = context.dependOnInheritedWidgetOfExactType<_TwoDimensionalScrollableScope>();
return widget?.twoDimensionalScrollable;
}
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// Typical usage is as follows:
///
/// ```dart
/// TwoDimensionalScrollableState scrollable = TwoDimensionalScrollable.of(context);
/// ```
///
/// Calling this method will create a dependency on the closest
/// [TwoDimensionalScrollable] in the [context]. The internal [Scrollable]s
/// can be accessed through [TwoDimensionalScrollableState.verticalScrollable]
/// and [TwoDimensionalScrollableState.horizontalScrollable].
///
/// If no [TwoDimensionalScrollable] ancestor is found, then this method will
/// assert in debug mode, and throw an exception in release mode.
///
/// Alternatively, [Scrollable.of] can be used by providing the desired [Axis]
/// to the `axis` parameter.
///
/// See also:
///
/// * [TwoDimensionalScrollable.maybeOf], which is similar to this method,
/// but returns null if no [TwoDimensionalScrollable] ancestor is found.
static TwoDimensionalScrollableState of(BuildContext context) {
final TwoDimensionalScrollableState? scrollableState = maybeOf(context);
assert(() {
if (scrollableState == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'TwoDimensionalScrollable.of() was called with a context that does '
'not contain a TwoDimensionalScrollable widget.\n'
),
ErrorDescription(
'No TwoDimensionalScrollable widget ancestor could be found starting '
'from the context that was passed to TwoDimensionalScrollable.of(). '
'This can happen because you are using a widget that looks for a '
'TwoDimensionalScrollable ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
),
]);
}
return true;
}());
return scrollableState!;
}
}
/// State object for a [TwoDimensionalScrollable] widget.
///
/// To manipulate one of the internal [Scrollable] widget's scroll position, use
/// the object obtained from the [verticalScrollable] or [horizontalScrollable]
/// property.
///
/// To be informed of when a [TwoDimensionalScrollable] widget is scrolling,
/// use a [NotificationListener] to listen for [ScrollNotification]s.
/// Both axes will have the same viewport depth since there is only one
/// viewport, and so should be differentiated by the [Axis] of the
/// [ScrollMetrics] provided by the notification.
class TwoDimensionalScrollableState extends State<TwoDimensionalScrollable> {
ScrollController? _verticalFallbackController;
ScrollController? _horizontalFallbackController;
final GlobalKey<ScrollableState> _verticalOuterScrollableKey = GlobalKey<ScrollableState>();
final GlobalKey<ScrollableState> _horizontalInnerScrollableKey = GlobalKey<ScrollableState>();
/// The [ScrollableState] of the vertical axis.
///
/// Accessible by calling [TwoDimensionalScrollable.of].
///
/// Alternatively, [Scrollable.of] can be used by providing [Axis.vertical]
/// to the `axis` parameter.
ScrollableState get verticalScrollable {
assert(_verticalOuterScrollableKey.currentState != null);
return _verticalOuterScrollableKey.currentState!;
}
/// The [ScrollableState] of the horizontal axis.
///
/// Accessible by calling [TwoDimensionalScrollable.of].
///
/// Alternatively, [Scrollable.of] can be used by providing [Axis.horizontal]
/// to the `axis` parameter.
ScrollableState get horizontalScrollable {
assert(_horizontalInnerScrollableKey.currentState != null);
return _horizontalInnerScrollableKey.currentState!;
}
@override
void initState() {
if (widget.verticalDetails.controller == null) {
_verticalFallbackController = ScrollController();
}
if (widget.horizontalDetails.controller == null) {
_horizontalFallbackController = ScrollController();
}
super.initState();
}
@override
void didUpdateWidget(TwoDimensionalScrollable oldWidget) {
super.didUpdateWidget(oldWidget);
// Handle changes in the provided/fallback scroll controllers
// Vertical
if (oldWidget.verticalDetails.controller != widget.verticalDetails.controller) {
if (oldWidget.verticalDetails.controller == null) {
// The old controller was null, meaning the fallback cannot be null.
// Dispose of the fallback.
assert(_verticalFallbackController != null);
assert(widget.verticalDetails.controller != null);
_verticalFallbackController!.dispose();
_verticalFallbackController = null;
} else if (widget.verticalDetails.controller == null) {
// If the new controller is null, we need to set up the fallback
// ScrollController.
assert(_verticalFallbackController == null);
_verticalFallbackController = ScrollController();
}
}
// Horizontal
if (oldWidget.horizontalDetails.controller != widget.horizontalDetails.controller) {
if (oldWidget.horizontalDetails.controller == null) {
// The old controller was null, meaning the fallback cannot be null.
// Dispose of the fallback.
assert(_horizontalFallbackController != null);
assert(widget.horizontalDetails.controller != null);
_horizontalFallbackController!.dispose();
_horizontalFallbackController = null;
} else if (widget.horizontalDetails.controller == null) {
// If the new controller is null, we need to set up the fallback
// ScrollController.
assert(_horizontalFallbackController == null);
_horizontalFallbackController = ScrollController();
}
}
}
@override
Widget build(BuildContext context) {
assert(
axisDirectionToAxis(widget.verticalDetails.direction) == Axis.vertical,
'TwoDimensionalScrollable.verticalDetails are not Axis.vertical.'
);
assert(
axisDirectionToAxis(widget.horizontalDetails.direction) == Axis.horizontal,
'TwoDimensionalScrollable.horizontalDetails are not Axis.horizontal.'
);
final Widget result = RestorationScope(
restorationId: widget.restorationId,
child: _VerticalOuterDimension(
key: _verticalOuterScrollableKey,
// For gesture forwarding
horizontalKey: _horizontalInnerScrollableKey,
axisDirection: widget.verticalDetails.direction,
controller: widget.verticalDetails.controller
?? _verticalFallbackController!,
physics: widget.verticalDetails.physics,
clipBehavior: widget.verticalDetails.clipBehavior
?? widget.verticalDetails.decorationClipBehavior
?? Clip.hardEdge,
incrementCalculator: widget.incrementCalculator,
excludeFromSemantics: widget.excludeFromSemantics,
restorationId: 'OuterVerticalTwoDimensionalScrollable',
dragStartBehavior: widget.dragStartBehavior,
diagonalDragBehavior: widget.diagonalDragBehavior,
viewportBuilder: (BuildContext context, ViewportOffset verticalOffset) {
return _HorizontalInnerDimension(
key: _horizontalInnerScrollableKey,
axisDirection: widget.horizontalDetails.direction,
controller: widget.horizontalDetails.controller
?? _horizontalFallbackController!,
physics: widget.horizontalDetails.physics,
clipBehavior: widget.horizontalDetails.clipBehavior
?? widget.horizontalDetails.decorationClipBehavior
?? Clip.hardEdge,
incrementCalculator: widget.incrementCalculator,
excludeFromSemantics: widget.excludeFromSemantics,
restorationId: 'InnerHorizontalTwoDimensionalScrollable',
dragStartBehavior: widget.dragStartBehavior,
diagonalDragBehavior: widget.diagonalDragBehavior,
viewportBuilder: (BuildContext context, ViewportOffset horizontalOffset) {
return widget.viewportBuilder(context, verticalOffset, horizontalOffset);
},
);
}
)
);
// TODO(Piinks): Build scrollbars for 2 dimensions instead of 1,
// https://github.com/flutter/flutter/issues/122348
return _TwoDimensionalScrollableScope(
twoDimensionalScrollable: this,
child: result,
);
}
@override
void dispose() {
_verticalFallbackController?.dispose();
_horizontalFallbackController?.dispose();
super.dispose();
}
}
// Enable TwoDimensionalScrollable.of() to work as if
// TwoDimensionalScrollableState was an inherited widget.
// TwoDimensionalScrollableState.build() always rebuilds its
// _TwoDimensionalScrollableScope.
class _TwoDimensionalScrollableScope extends InheritedWidget {
const _TwoDimensionalScrollableScope({
required this.twoDimensionalScrollable,
required super.child,
});
final TwoDimensionalScrollableState twoDimensionalScrollable;
@override
bool updateShouldNotify(_TwoDimensionalScrollableScope old) => false;
}
// Vertical outer scrollable of 2D scrolling
class _VerticalOuterDimension extends Scrollable {
const _VerticalOuterDimension({
super.key,
required this.horizontalKey,
required super.viewportBuilder,
required super.axisDirection,
super.controller,
super.physics,
super.clipBehavior,
super.incrementCalculator,
super.excludeFromSemantics,
super.dragStartBehavior,
super.restorationId,
this.diagonalDragBehavior = DiagonalDragBehavior.none,
}) : assert(axisDirection == AxisDirection.up || axisDirection == AxisDirection.down);
final DiagonalDragBehavior diagonalDragBehavior;
final GlobalKey<ScrollableState> horizontalKey;
@override
_VerticalOuterDimensionState createState() => _VerticalOuterDimensionState();
}
class _VerticalOuterDimensionState extends ScrollableState {
DiagonalDragBehavior get diagonalDragBehavior => (widget as _VerticalOuterDimension).diagonalDragBehavior;
ScrollableState get horizontalScrollable => (widget as _VerticalOuterDimension).horizontalKey.currentState!;
Axis? lockedAxis;
Offset? lastDragOffset;
// Implemented in the _HorizontalInnerDimension instead.
@override
_EnsureVisibleResults _performEnsureVisible(
RenderObject object, {
double alignment = 0.0,
Duration duration = Duration.zero,
Curve curve = Curves.ease,
ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit,
RenderObject? targetRenderObject,
}) {
assert(
false,
'The _performEnsureVisible method was called for the vertical scrollable '
'of a TwoDimensionalScrollable. This should not happen as the horizontal '
'scrollable handles both axes.'
);
return (<Future<void>>[], this);
}
void _evaluateLockedAxis(Offset offset) {
assert(lastDragOffset != null);
final Offset offsetDelta = lastDragOffset! - offset;
final double axisDifferential = offsetDelta.dx.abs() - offsetDelta.dy.abs();
if (axisDifferential.abs() >= kTouchSlop) {
// We have single axis winner.
lockedAxis = axisDifferential > 0.0 ? Axis.horizontal : Axis.vertical;
} else {
lockedAxis = null;
}
}
@override
void _handleDragDown(DragDownDetails details) {
switch (diagonalDragBehavior) {
case DiagonalDragBehavior.none:
break;
case DiagonalDragBehavior.weightedEvent:
case DiagonalDragBehavior.weightedContinuous:
case DiagonalDragBehavior.free:
// Initiate hold. If one or the other wins the gesture, cancel the
// opposite axis.
horizontalScrollable._handleDragDown(details);
}
super._handleDragDown(details);
}
@override
void _handleDragStart(DragStartDetails details) {
lastDragOffset = details.globalPosition;
switch (diagonalDragBehavior) {
case DiagonalDragBehavior.none:
break;
case DiagonalDragBehavior.free:
// Prepare to scroll both.
// vertical - will call super below after switch.
horizontalScrollable._handleDragStart(details);
case DiagonalDragBehavior.weightedEvent:
case DiagonalDragBehavior.weightedContinuous:
// See if one axis wins the drag.
_evaluateLockedAxis(details.globalPosition);
switch (lockedAxis) {
case null:
// Prepare to scroll both, null means no winner yet.
// vertical - will call super below after switch.
horizontalScrollable._handleDragStart(details);
case Axis.horizontal:
// Prepare to scroll horizontally.
horizontalScrollable._handleDragStart(details);
return;
case Axis.vertical:
// Prepare to scroll vertically - will call super below after switch.
}
}
super._handleDragStart(details);
}
@override
void _handleDragUpdate(DragUpdateDetails details) {
final DragUpdateDetails verticalDragDetails = DragUpdateDetails(
sourceTimeStamp: details.sourceTimeStamp,
delta: Offset(0.0, details.delta.dy),
primaryDelta: details.delta.dy,
globalPosition: details.globalPosition,
localPosition: details.localPosition,
);
final DragUpdateDetails horizontalDragDetails = DragUpdateDetails(
sourceTimeStamp: details.sourceTimeStamp,
delta: Offset(details.delta.dx, 0.0),
primaryDelta: details.delta.dx,
globalPosition: details.globalPosition,
localPosition: details.localPosition,
);
switch (diagonalDragBehavior) {
case DiagonalDragBehavior.none:
// Default gesture handling from super class.
super._handleDragUpdate(verticalDragDetails);
return;
case DiagonalDragBehavior.free:
// Scroll both axes
horizontalScrollable._handleDragUpdate(horizontalDragDetails);
super._handleDragUpdate(verticalDragDetails);
return;
case DiagonalDragBehavior.weightedContinuous:
// Re-evaluate locked axis for every update.
_evaluateLockedAxis(details.globalPosition);
lastDragOffset = details.globalPosition;
case DiagonalDragBehavior.weightedEvent:
// Lock axis only once per gesture.
if (lockedAxis == null && lastDragOffset != null) {
// A winner has not been declared yet.
// See if one axis has won the drag.
_evaluateLockedAxis(details.globalPosition);
}
}
switch (lockedAxis) {
case null:
// Scroll both - vertical after switch
horizontalScrollable._handleDragUpdate(horizontalDragDetails);
case Axis.horizontal:
// Scroll horizontally
horizontalScrollable._handleDragUpdate(horizontalDragDetails);
return;
case Axis.vertical:
// Scroll vertically - after switch
}
super._handleDragUpdate(verticalDragDetails);
}
@override
void _handleDragEnd(DragEndDetails details) {
lastDragOffset = null;
lockedAxis = null;
final double dx = details.velocity.pixelsPerSecond.dx;
final double dy = details.velocity.pixelsPerSecond.dy;
final DragEndDetails verticalDragDetails = DragEndDetails(
velocity: Velocity(pixelsPerSecond: Offset(0.0, dy)),
primaryVelocity: dy,
);
final DragEndDetails horizontalDragDetails = DragEndDetails(
velocity: Velocity(pixelsPerSecond: Offset(dx, 0.0)),
primaryVelocity: dx,
);
switch (diagonalDragBehavior) {
case DiagonalDragBehavior.none:
break;
case DiagonalDragBehavior.weightedEvent:
case DiagonalDragBehavior.weightedContinuous:
case DiagonalDragBehavior.free:
horizontalScrollable._handleDragEnd(horizontalDragDetails);
}
super._handleDragEnd(verticalDragDetails);
}
@override
void _handleDragCancel() {
lastDragOffset = null;
lockedAxis = null;
switch (diagonalDragBehavior) {
case DiagonalDragBehavior.none:
break;
case DiagonalDragBehavior.weightedEvent:
case DiagonalDragBehavior.weightedContinuous:
case DiagonalDragBehavior.free:
horizontalScrollable._handleDragCancel();
}
super._handleDragCancel();
}
@override
void setCanDrag(bool value) {
switch (diagonalDragBehavior) {
case DiagonalDragBehavior.none:
// If we aren't scrolling diagonally, the default drag gesture recognizer
// is used.
super.setCanDrag(value);
return;
case DiagonalDragBehavior.weightedEvent:
case DiagonalDragBehavior.weightedContinuous:
case DiagonalDragBehavior.free:
if (value) {
// Replaces the typical vertical/horizontal drag gesture recognizers
// with a pan gesture recognizer to allow bidirectional scrolling.
// Based on the diagonalDragBehavior, valid horizontal deltas are
// applied to this scrollable, while vertical deltas are routed to
// the vertical scrollable.
_gestureRecognizers = <Type, GestureRecognizerFactory>{
PanGestureRecognizer: GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
() => PanGestureRecognizer(supportedDevices: _configuration.dragDevices),
(PanGestureRecognizer instance) {
instance
..onDown = _handleDragDown
..onStart = _handleDragStart
..onUpdate = _handleDragUpdate
..onEnd = _handleDragEnd
..onCancel = _handleDragCancel
..minFlingDistance = _physics?.minFlingDistance
..minFlingVelocity = _physics?.minFlingVelocity
..maxFlingVelocity = _physics?.maxFlingVelocity
..velocityTrackerBuilder = _configuration.velocityTrackerBuilder(context)
..dragStartBehavior = widget.dragStartBehavior
..gestureSettings = _mediaQueryGestureSettings;
},
),
};
// Cancel the active hold/drag (if any) because the gesture recognizers
// will soon be disposed by our RawGestureDetector, and we won't be
// receiving pointer up events to cancel the hold/drag.
_handleDragCancel();
_lastCanDrag = value;
_lastAxisDirection = widget.axis;
if (_gestureDetectorKey.currentState != null) {
_gestureDetectorKey.currentState!.replaceGestureRecognizers(_gestureRecognizers);
}
}
return;
}
}
@override
Widget _buildChrome(BuildContext context, Widget child) {
final ScrollableDetails details = ScrollableDetails(
direction: widget.axisDirection,
controller: _effectiveScrollController,
clipBehavior: widget.clipBehavior,
);
// Skip building a scrollbar here, the dual scrollbar is added in
// TwoDimensionalScrollableState.
return _configuration.buildOverscrollIndicator(context, child, details);
}
}
// Horizontal inner scrollable of 2D scrolling
class _HorizontalInnerDimension extends Scrollable {
const _HorizontalInnerDimension({
super.key,
required super.viewportBuilder,
required super.axisDirection,
super.controller,
super.physics,
super.clipBehavior,
super.incrementCalculator,
super.excludeFromSemantics,
super.dragStartBehavior,
super.restorationId,
this.diagonalDragBehavior = DiagonalDragBehavior.none,
}) : assert(axisDirection == AxisDirection.left || axisDirection == AxisDirection.right);
final DiagonalDragBehavior diagonalDragBehavior;
@override
_HorizontalInnerDimensionState createState() => _HorizontalInnerDimensionState();
}
class _HorizontalInnerDimensionState extends ScrollableState {
late ScrollableState verticalScrollable;
DiagonalDragBehavior get diagonalDragBehavior => (widget as _HorizontalInnerDimension).diagonalDragBehavior;
@override
void didChangeDependencies() {
verticalScrollable = Scrollable.of(context);
assert(axisDirectionToAxis(verticalScrollable.axisDirection) == Axis.vertical);
super.didChangeDependencies();
}
// Returns the Future from calling ensureVisible for the ScrollPosition, as
// as well as the vertical ScrollableState instance so its context can be
// used to check for other ancestor Scrollables in executing ensureVisible.
@override
_EnsureVisibleResults _performEnsureVisible(
RenderObject object, {
double alignment = 0.0,
Duration duration = Duration.zero,
Curve curve = Curves.ease,
ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit,
RenderObject? targetRenderObject,
}) {
final List<Future<void>> newFutures = <Future<void>>[];
newFutures.add(position.ensureVisible(
object,
alignment: alignment,
duration: duration,
curve: curve,
alignmentPolicy: alignmentPolicy,
));
newFutures.add(verticalScrollable.position.ensureVisible(
object,
alignment: alignment,
duration: duration,
curve: curve,
alignmentPolicy: alignmentPolicy,
));
return (newFutures, verticalScrollable);
}
@override
void setCanDrag(bool value) {
switch (diagonalDragBehavior) {
case DiagonalDragBehavior.none:
// If we aren't scrolling diagonally, the default drag gesture
// recognizer is used.
super.setCanDrag(value);
return;
case DiagonalDragBehavior.weightedEvent:
case DiagonalDragBehavior.weightedContinuous:
case DiagonalDragBehavior.free:
if (value) {
// If a type of diagonal scrolling is enabled, a panning gesture
// recognizer will be created for the _InnerDimension. So in this
// case, the _OuterDimension does not require a gesture recognizer.
_gestureRecognizers = const <Type, GestureRecognizerFactory>{};
// Cancel the active hold/drag (if any) because the gesture recognizers
// will soon be disposed by our RawGestureDetector, and we won't be
// receiving pointer up events to cancel the hold/drag.
_handleDragCancel();
_lastCanDrag = value;
_lastAxisDirection = widget.axis;
if (_gestureDetectorKey.currentState != null) {
_gestureDetectorKey.currentState!.replaceGestureRecognizers(_gestureRecognizers);
}
}
return;
}
}
@override
Widget _buildChrome(BuildContext context, Widget child) {
final ScrollableDetails details = ScrollableDetails(
direction: widget.axisDirection,
controller: _effectiveScrollController,
clipBehavior: widget.clipBehavior,
);
// Skip building a scrollbar here, the dual scrollbar is added in
// TwoDimensionalScrollableState.
return _configuration.buildOverscrollIndicator(context, child, details);
}
}
| flutter/packages/flutter/lib/src/widgets/scrollable.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/scrollable.dart",
"repo_id": "flutter",
"token_count": 30915
} | 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 'package:flutter/rendering.dart';
import 'framework.dart';
import 'scroll_delegate.dart';
import 'sliver.dart';
/// A sliver that places its box children in a linear array and constrains them
/// to have the corresponding extent returned by [itemExtentBuilder].
///
/// _To learn more about slivers, see [CustomScrollView.slivers]._
///
/// [SliverVariedExtentList] arranges its children in a line along
/// the main axis starting at offset zero and without gaps. Each child is
/// constrained to the corresponding extent along the main axis
/// and the [SliverConstraints.crossAxisExtent] along the cross axis.
///
/// [SliverVariedExtentList] is more efficient than [SliverList] because
/// [SliverVariedExtentList] does not need to lay out its children to obtain
/// their extent along the main axis. It's a little more flexible than
/// [SliverFixedExtentList] because this allow the children to have different extents.
///
/// See also:
///
/// * [SliverFixedExtentList], whose children are forced to a given pixel
/// extent.
/// * [SliverPrototypeExtentList], which is similar to [SliverFixedExtentList]
/// except that it uses a prototype list item instead of a pixel value to define
/// the main axis extent of each item.
/// * [SliverList], which does not require its children to have the same
/// extent in the main axis.
/// * [SliverFillViewport], which sizes its children based on the
/// size of the viewport, regardless of what else is in the scroll view.
class SliverVariedExtentList extends SliverMultiBoxAdaptorWidget {
/// Creates a sliver that places box children with the same main axis extent
/// in a linear array.
const SliverVariedExtentList({
super.key,
required super.delegate,
required this.itemExtentBuilder,
});
/// A sliver that places multiple box children in a linear array along the main
/// axis.
///
/// [SliverVariedExtentList] places its children in a linear array along the main
/// axis starting at offset zero and without gaps. Each child is forced to have
/// the returned extent of [itemExtentBuilder] in the main axis and the
/// [SliverConstraints.crossAxisExtent] in the cross axis.
///
/// This constructor is appropriate for sliver lists with a large (or
/// infinite) number of children whose extent is already determined.
///
/// Providing a non-null `itemCount` improves the ability of the [SliverGrid]
/// to estimate the maximum scroll extent.
SliverVariedExtentList.builder({
super.key,
required NullableIndexedWidgetBuilder itemBuilder,
required this.itemExtentBuilder,
ChildIndexGetter? findChildIndexCallback,
int? itemCount,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
}) : super(delegate: SliverChildBuilderDelegate(
itemBuilder,
findChildIndexCallback: findChildIndexCallback,
childCount: itemCount,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
));
/// A sliver that places multiple box children in a linear array along the main
/// axis.
///
/// [SliverVariedExtentList] places its children in a linear array along the main
/// axis starting at offset zero and without gaps. Each child is forced to have
/// the returned extent of [itemExtentBuilder] in the main axis and the
/// [SliverConstraints.crossAxisExtent] in the cross axis.
///
/// This constructor uses a list of [Widget]s to build the sliver.
SliverVariedExtentList.list({
super.key,
required List<Widget> children,
required this.itemExtentBuilder,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
}) : super(delegate: SliverChildListDelegate(
children,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
));
/// The children extent builder.
///
/// Should return null if asked to build an item extent with a greater index than
/// exists.
final ItemExtentBuilder itemExtentBuilder;
@override
RenderSliverVariedExtentList createRenderObject(BuildContext context) {
final SliverMultiBoxAdaptorElement element = context as SliverMultiBoxAdaptorElement;
return RenderSliverVariedExtentList(childManager: element, itemExtentBuilder: itemExtentBuilder);
}
@override
void updateRenderObject(BuildContext context, RenderSliverVariedExtentList renderObject) {
renderObject.itemExtentBuilder = itemExtentBuilder;
}
}
/// A sliver that places multiple box children with the corresponding main axis extent in
/// a linear array.
class RenderSliverVariedExtentList extends RenderSliverFixedExtentBoxAdaptor {
/// Creates a sliver that contains multiple box children that have a explicit
/// extent in the main axis.
RenderSliverVariedExtentList({
required super.childManager,
required ItemExtentBuilder itemExtentBuilder,
}) : _itemExtentBuilder = itemExtentBuilder;
@override
ItemExtentBuilder get itemExtentBuilder => _itemExtentBuilder;
ItemExtentBuilder _itemExtentBuilder;
set itemExtentBuilder(ItemExtentBuilder value) {
if (_itemExtentBuilder == value) {
return;
}
_itemExtentBuilder = value;
markNeedsLayout();
}
@override
double? get itemExtent => null;
}
| flutter/packages/flutter/lib/src/widgets/sliver_varied_extent_list.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/sliver_varied_extent_list.dart",
"repo_id": "flutter",
"token_count": 1630
} | 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.
import 'dart:math' as math;
import 'package:flutter/rendering.dart';
import 'basic.dart';
import 'container.dart';
import 'framework.dart';
import 'text.dart';
export 'package:flutter/rendering.dart' show RelativeRect;
/// A widget that rebuilds when the given [Listenable] changes value.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=LKKgYpC-EPQ}
///
/// [AnimatedWidget] is most commonly used with [Animation] objects, which are
/// [Listenable], but it can be used with any [Listenable], including
/// [ChangeNotifier] and [ValueNotifier].
///
/// [AnimatedWidget] is most useful for widgets that are otherwise stateless. To
/// use [AnimatedWidget], subclass it and implement the build function.
///
/// {@tool dartpad}
/// This code defines a widget called `Spinner` that spins a green square
/// continually. It is built with an [AnimatedWidget].
///
/// ** See code in examples/api/lib/widgets/transitions/animated_widget.0.dart **
/// {@end-tool}
///
/// For more complex case involving additional state, consider using
/// [AnimatedBuilder] or [ListenableBuilder].
///
/// ## Relationship to [ImplicitlyAnimatedWidget]s
///
/// [AnimatedWidget]s (and their subclasses) take an explicit [Listenable] as
/// argument, which is usually an [Animation] derived from an
/// [AnimationController]. In most cases, the lifecycle of that
/// [AnimationController] has to be managed manually by the developer.
/// In contrast to that, [ImplicitlyAnimatedWidget]s (and their subclasses)
/// automatically manage their own internal [AnimationController] making those
/// classes easier to use as no external [Animation] has to be provided by the
/// developer. If you only need to set a target value for the animation and
/// configure its duration/curve, consider using (a subclass of)
/// [ImplicitlyAnimatedWidget]s instead of (a subclass of) this class.
///
/// ## Common animated widgets
///
/// A number of animated widgets ship with the framework. They are usually named
/// `FooTransition`, where `Foo` is the name of the non-animated
/// version of that widget. The subclasses of this class should not be confused
/// with subclasses of [ImplicitlyAnimatedWidget] (see above), which are usually
/// named `AnimatedFoo`. Commonly used animated widgets include:
///
/// * [ListenableBuilder], which uses a builder pattern that is useful for
/// complex [Listenable] use cases.
/// * [AnimatedBuilder], which uses a builder pattern that is useful for
/// complex [Animation] use cases.
/// * [AlignTransition], which is an animated version of [Align].
/// * [DecoratedBoxTransition], which is an animated version of [DecoratedBox].
/// * [DefaultTextStyleTransition], which is an animated version of
/// [DefaultTextStyle].
/// * [PositionedTransition], which is an animated version of [Positioned].
/// * [RelativePositionedTransition], which is an animated version of
/// [Positioned].
/// * [RotationTransition], which animates the rotation of a widget.
/// * [ScaleTransition], which animates the scale of a widget.
/// * [SizeTransition], which animates its own size.
/// * [SlideTransition], which animates the position of a widget relative to
/// its normal position.
/// * [FadeTransition], which is an animated version of [Opacity].
/// * [AnimatedModalBarrier], which is an animated version of [ModalBarrier].
abstract class AnimatedWidget extends StatefulWidget {
/// Creates a widget that rebuilds when the given listenable changes.
///
/// The [listenable] argument is required.
const AnimatedWidget({
super.key,
required this.listenable,
});
/// The [Listenable] to which this widget is listening.
///
/// Commonly an [Animation] or a [ChangeNotifier].
final Listenable listenable;
/// Override this method to build widgets that depend on the state of the
/// listenable (e.g., the current value of the animation).
@protected
Widget build(BuildContext context);
/// Subclasses typically do not override this method.
@override
State<AnimatedWidget> createState() => _AnimatedState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Listenable>('listenable', listenable));
}
}
class _AnimatedState extends State<AnimatedWidget> {
@override
void initState() {
super.initState();
widget.listenable.addListener(_handleChange);
}
@override
void didUpdateWidget(AnimatedWidget oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.listenable != oldWidget.listenable) {
oldWidget.listenable.removeListener(_handleChange);
widget.listenable.addListener(_handleChange);
}
}
@override
void dispose() {
widget.listenable.removeListener(_handleChange);
super.dispose();
}
void _handleChange() {
setState(() {
// The listenable's state is our build state, and it changed already.
});
}
@override
Widget build(BuildContext context) => widget.build(context);
}
/// Animates the position of a widget relative to its normal position.
///
/// The translation is expressed as an [Offset] scaled to the child's size. For
/// example, an [Offset] with a `dx` of 0.25 will result in a horizontal
/// translation of one quarter the width of the child.
///
/// By default, the offsets are applied in the coordinate system of the canvas
/// (so positive x offsets move the child towards the right). If a
/// [textDirection] is provided, then the offsets are applied in the reading
/// direction, so in right-to-left text, positive x offsets move towards the
/// left, and in left-to-right text, positive x offsets move towards the right.
///
/// Here's an illustration of the [SlideTransition] widget, with its [position]
/// animated by a [CurvedAnimation] set to [Curves.elasticIn]:
/// {@animation 300 378 https://flutter.github.io/assets-for-api-docs/assets/widgets/slide_transition.mp4}
///
/// {@tool dartpad}
/// The following code implements the [SlideTransition] as seen in the video
/// above:
///
/// ** See code in examples/api/lib/widgets/transitions/slide_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AlignTransition], an animated version of an [Align] that animates its
/// [Align.alignment] property.
/// * [PositionedTransition], a widget that animates its child from a start
/// position to an end position over the lifetime of the animation.
/// * [RelativePositionedTransition], a widget that transitions its child's
/// position based on the value of a rectangle relative to a bounding box.
class SlideTransition extends AnimatedWidget {
/// Creates a fractional translation transition.
const SlideTransition({
super.key,
required Animation<Offset> position,
this.transformHitTests = true,
this.textDirection,
this.child,
}) : super(listenable: position);
/// The animation that controls the position of the child.
///
/// If the current value of the position animation is `(dx, dy)`, the child
/// will be translated horizontally by `width * dx` and vertically by
/// `height * dy`, after applying the [textDirection] if available.
Animation<Offset> get position => listenable as Animation<Offset>;
/// The direction to use for the x offset described by the [position].
///
/// If [textDirection] is null, the x offset is applied in the coordinate
/// system of the canvas (so positive x offsets move the child towards the
/// right).
///
/// If [textDirection] is [TextDirection.rtl], the x offset is applied in the
/// reading direction such that x offsets move the child towards the left.
///
/// If [textDirection] is [TextDirection.ltr], the x offset is applied in the
/// reading direction such that x offsets move the child towards the right.
final TextDirection? textDirection;
/// Whether hit testing should be affected by the slide animation.
///
/// If false, hit testing will proceed as if the child was not translated at
/// all. Setting this value to false is useful for fast animations where you
/// expect the user to commonly interact with the child widget in its final
/// location and you want the user to benefit from "muscle memory".
final bool transformHitTests;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
@override
Widget build(BuildContext context) {
Offset offset = position.value;
if (textDirection == TextDirection.rtl) {
offset = Offset(-offset.dx, offset.dy);
}
return FractionalTranslation(
translation: offset,
transformHitTests: transformHitTests,
child: child,
);
}
}
/// Signature for the callback to [MatrixTransition.onTransform].
///
/// Computes a [Matrix4] to be used in the [MatrixTransition] transformed widget
/// from the [MatrixTransition.animation] value.
typedef TransformCallback = Matrix4 Function(double animationValue);
/// Animates the [Matrix4] of a transformed widget.
///
/// The [onTransform] callback computes a [Matrix4] from the animated value, it
/// is called every time the [animation] changes its value.
///
/// {@tool dartpad}
/// The following example implements a [MatrixTransition] with a rotation around
/// the Y axis, with a 3D perspective skew.
///
/// ** See code in examples/api/lib/widgets/transitions/matrix_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ScaleTransition], which animates the scale of a widget, by providing a
/// matrix which scales along the X and Y axis.
/// * [RotationTransition], which animates the rotation of a widget, by
/// providing a matrix which rotates along the Z axis.
class MatrixTransition extends AnimatedWidget {
/// Creates a matrix transition.
///
/// The [alignment] argument defaults to [Alignment.center].
const MatrixTransition({
super.key,
required Animation<double> animation,
required this.onTransform,
this.alignment = Alignment.center,
this.filterQuality,
this.child,
}) : super(listenable: animation);
/// The callback to compute a [Matrix4] from the [animation]. It's called
/// every time [animation] changes its value.
final TransformCallback onTransform;
/// The animation that controls the matrix of the child.
///
/// The matrix will be computed from the animation with the [onTransform]
/// callback.
Animation<double> get animation => listenable as Animation<double>;
/// The alignment of the origin of the coordinate system in which the
/// transform takes place, relative to the size of the box.
///
/// For example, to set the origin of the transform to bottom middle, you can
/// use an alignment of (0.0, 1.0).
final Alignment alignment;
/// The filter quality with which to apply the transform as a bitmap operation.
///
/// When the animation is stopped (either in [AnimationStatus.dismissed] or
/// [AnimationStatus.completed]), the filter quality argument will be ignored.
///
/// {@macro flutter.widgets.Transform.optional.FilterQuality}
final FilterQuality? filterQuality;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
@override
Widget build(BuildContext context) {
// The ImageFilter layer created by setting filterQuality will introduce
// a saveLayer call. This is usually worthwhile when animating the layer,
// but leaving it in the layer tree before the animation has started or after
// it has finished significantly hurts performance.
return Transform(
transform: onTransform(animation.value),
alignment: alignment,
filterQuality: switch (animation.status) {
AnimationStatus.forward || AnimationStatus.reverse => filterQuality,
AnimationStatus.dismissed || AnimationStatus.completed => null,
},
child: child,
);
}
}
/// Animates the scale of a transformed widget.
///
/// Here's an illustration of the [ScaleTransition] widget, with it's [scale]
/// animated by a [CurvedAnimation] set to [Curves.fastOutSlowIn]:
/// {@animation 300 378 https://flutter.github.io/assets-for-api-docs/assets/widgets/scale_transition.mp4}
///
/// {@tool dartpad}
/// The following code implements the [ScaleTransition] as seen in the video
/// above:
///
/// ** See code in examples/api/lib/widgets/transitions/scale_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [PositionedTransition], a widget that animates its child from a start
/// position to an end position over the lifetime of the animation.
/// * [RelativePositionedTransition], a widget that transitions its child's
/// position based on the value of a rectangle relative to a bounding box.
/// * [SizeTransition], a widget that animates its own size and clips and
/// aligns its child.
class ScaleTransition extends MatrixTransition {
/// Creates a scale transition.
///
/// The [alignment] argument defaults to [Alignment.center].
const ScaleTransition({
super.key,
required Animation<double> scale,
super.alignment = Alignment.center,
super.filterQuality,
super.child,
}) : super(animation: scale, onTransform: _handleScaleMatrix);
/// The animation that controls the scale of the child.
Animation<double> get scale => animation;
/// The callback that controls the scale of the child.
///
/// If the current value of the animation is v, the child will be
/// painted v times its normal size.
static Matrix4 _handleScaleMatrix(double value) => Matrix4.diagonal3Values(value, value, 1.0);
}
/// Animates the rotation of a widget.
///
/// Here's an illustration of the [RotationTransition] widget, with it's [turns]
/// animated by a [CurvedAnimation] set to [Curves.elasticOut]:
/// {@animation 300 378 https://flutter.github.io/assets-for-api-docs/assets/widgets/rotation_transition.mp4}
///
/// {@tool dartpad}
/// The following code implements the [RotationTransition] as seen in the video
/// above:
///
/// ** See code in examples/api/lib/widgets/transitions/rotation_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ScaleTransition], a widget that animates the scale of a transformed
/// widget.
/// * [SizeTransition], a widget that animates its own size and clips and
/// aligns its child.
class RotationTransition extends MatrixTransition {
/// Creates a rotation transition.
const RotationTransition({
super.key,
required Animation<double> turns,
super.alignment = Alignment.center,
super.filterQuality,
super.child,
}) : super(animation: turns, onTransform: _handleTurnsMatrix);
/// The animation that controls the rotation of the child.
Animation<double> get turns => animation;
/// The callback that controls the rotation of the child.
///
/// If the current value of the animation is v, the child will be rotated
/// v * 2 * pi radians before being painted.
static Matrix4 _handleTurnsMatrix(double value) => Matrix4.rotationZ(value * math.pi * 2.0);
}
/// Animates its own size and clips and aligns its child.
///
/// [SizeTransition] acts as a [ClipRect] that animates either its width or its
/// height, depending upon the value of [axis]. The alignment of the child along
/// the [axis] is specified by the [axisAlignment].
///
/// Like most widgets, [SizeTransition] will conform to the constraints it is
/// given, so be sure to put it in a context where it can change size. For
/// instance, if you place it into a [Container] with a fixed size, then the
/// [SizeTransition] will not be able to change size, and will appear to do
/// nothing.
///
/// Here's an illustration of the [SizeTransition] widget, with it's [sizeFactor]
/// animated by a [CurvedAnimation] set to [Curves.fastOutSlowIn]:
/// {@animation 300 378 https://flutter.github.io/assets-for-api-docs/assets/widgets/size_transition.mp4}
///
/// {@tool dartpad}
/// This code defines a widget that uses [SizeTransition] to change the size
/// of [FlutterLogo] continually. It is built with a [Scaffold]
/// where the internal widget has space to change its size.
///
/// ** See code in examples/api/lib/widgets/transitions/size_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AnimatedCrossFade], for a widget that automatically animates between
/// the sizes of two children, fading between them.
/// * [ScaleTransition], a widget that scales the size of the child instead of
/// clipping it.
/// * [PositionedTransition], a widget that animates its child from a start
/// position to an end position over the lifetime of the animation.
/// * [RelativePositionedTransition], a widget that transitions its child's
/// position based on the value of a rectangle relative to a bounding box.
class SizeTransition extends AnimatedWidget {
/// Creates a size transition.
///
/// The [axis] argument defaults to [Axis.vertical]. The [axisAlignment]
/// defaults to zero, which centers the child along the main axis during the
/// transition.
const SizeTransition({
super.key,
this.axis = Axis.vertical,
required Animation<double> sizeFactor,
this.axisAlignment = 0.0,
this.fixedCrossAxisSizeFactor,
this.child,
}) : assert(fixedCrossAxisSizeFactor == null || fixedCrossAxisSizeFactor >= 0.0),
super(listenable: sizeFactor);
/// [Axis.horizontal] if [sizeFactor] modifies the width, otherwise
/// [Axis.vertical].
final Axis axis;
/// The animation that controls the (clipped) size of the child.
///
/// The width or height (depending on the [axis] value) of this widget will be
/// its intrinsic width or height multiplied by [sizeFactor]'s value at the
/// current point in the animation.
///
/// If the value of [sizeFactor] is less than one, the child will be clipped
/// in the appropriate axis.
Animation<double> get sizeFactor => listenable as Animation<double>;
/// Describes how to align the child along the axis that [sizeFactor] is
/// modifying.
///
/// A value of -1.0 indicates the top when [axis] is [Axis.vertical], and the
/// start when [axis] is [Axis.horizontal]. The start is on the left when the
/// text direction in effect is [TextDirection.ltr] and on the right when it
/// is [TextDirection.rtl].
///
/// A value of 1.0 indicates the bottom or end, depending upon the [axis].
///
/// A value of 0.0 (the default) indicates the center for either [axis] value.
final double axisAlignment;
/// The factor by which to multiply the cross axis size of the child.
///
/// If the value of [fixedCrossAxisSizeFactor] is less than one, the child
/// will be clipped along the appropriate axis.
///
/// If `null` (the default), the cross axis size is as large as the parent.
final double? fixedCrossAxisSizeFactor;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
@override
Widget build(BuildContext context) {
final AlignmentDirectional alignment;
if (axis == Axis.vertical) {
alignment = AlignmentDirectional(-1.0, axisAlignment);
} else {
alignment = AlignmentDirectional(axisAlignment, -1.0);
}
return ClipRect(
child: Align(
alignment: alignment,
heightFactor: axis == Axis.vertical ? math.max(sizeFactor.value, 0.0) : fixedCrossAxisSizeFactor,
widthFactor: axis == Axis.horizontal ? math.max(sizeFactor.value, 0.0) : fixedCrossAxisSizeFactor,
child: child,
),
);
}
}
/// Animates the opacity of a widget.
///
/// For a widget that automatically animates between the sizes of two children,
/// fading between them, see [AnimatedCrossFade].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=rLwWVbv3xDQ}
///
/// Here's an illustration of the [FadeTransition] widget, with it's [opacity]
/// animated by a [CurvedAnimation] set to [Curves.fastOutSlowIn]:
///
/// {@tool dartpad}
/// The following code implements the [FadeTransition] using
/// the Flutter logo:
///
/// ** See code in examples/api/lib/widgets/transitions/fade_transition.0.dart **
/// {@end-tool}
///
/// ## Hit testing
///
/// Setting the [opacity] to zero does not prevent hit testing from being
/// applied to the descendants of the [FadeTransition] widget. This can be
/// confusing for the user, who may not see anything, and may believe the area
/// of the interface where the [FadeTransition] is hiding a widget to be
/// non-interactive.
///
/// With certain widgets, such as [Flow], that compute their positions only when
/// they are painted, this can actually lead to bugs (from unexpected geometry
/// to exceptions), because those widgets are not painted by the [FadeTransition]
/// widget at all when the [opacity] animation reaches zero.
///
/// To avoid such problems, it is generally a good idea to combine this widget
/// with an [IgnorePointer] that one enables when the [opacity] animation
/// reaches zero. This prevents interactions with any children in the subtree
/// when the [child] is not visible. For performance reasons, when implementing
/// this, care should be taken not to rebuild the relevant widget (e.g. by
/// calling [State.setState]) except at the transition point.
///
/// See also:
///
/// * [Opacity], which does not animate changes in opacity.
/// * [AnimatedOpacity], which animates changes in opacity without taking an
/// explicit [Animation] argument.
/// * [SliverFadeTransition], the sliver version of this widget.
class FadeTransition extends SingleChildRenderObjectWidget {
/// Creates an opacity transition.
const FadeTransition({
super.key,
required this.opacity,
this.alwaysIncludeSemantics = false,
super.child,
});
/// The animation that controls the opacity of the child.
///
/// If the current value of the opacity animation is v, the child will be
/// painted with an opacity of v. For example, if v is 0.5, the child will be
/// blended 50% with its background. Similarly, if v is 0.0, the child will be
/// completely transparent.
final Animation<double> opacity;
/// Whether the semantic information of the children is always included.
///
/// Defaults to false.
///
/// When true, regardless of the opacity settings the child semantic
/// information is exposed as if the widget were fully visible. This is
/// useful in cases where labels may be hidden during animations that
/// would otherwise contribute relevant semantics.
final bool alwaysIncludeSemantics;
@override
RenderAnimatedOpacity createRenderObject(BuildContext context) {
return RenderAnimatedOpacity(
opacity: opacity,
alwaysIncludeSemantics: alwaysIncludeSemantics,
);
}
@override
void updateRenderObject(BuildContext context, RenderAnimatedOpacity renderObject) {
renderObject
..opacity = opacity
..alwaysIncludeSemantics = alwaysIncludeSemantics;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Animation<double>>('opacity', opacity));
properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics'));
}
}
/// Animates the opacity of a sliver widget.
///
/// {@tool dartpad}
/// Creates a [CustomScrollView] with a [SliverFixedExtentList] that uses a
/// [SliverFadeTransition] to fade the list in and out.
///
/// ** See code in examples/api/lib/widgets/transitions/sliver_fade_transition.0.dart **
/// {@end-tool}
///
/// Here's an illustration of the [FadeTransition] widget, the [RenderBox]
/// equivalent widget, with it's [opacity] animated by a [CurvedAnimation] set
/// to [Curves.fastOutSlowIn]:
///
/// {@animation 300 378 https://flutter.github.io/assets-for-api-docs/assets/widgets/fade_transition.mp4}
///
/// ## Hit testing
///
/// Setting the [opacity] to zero does not prevent hit testing from being
/// applied to the descendants of the [SliverFadeTransition] widget. This can be
/// confusing for the user, who may not see anything, and may believe the area
/// of the interface where the [SliverFadeTransition] is hiding a widget to be
/// non-interactive.
///
/// With certain widgets, such as [Flow], that compute their positions only when
/// they are painted, this can actually lead to bugs (from unexpected geometry
/// to exceptions), because those widgets are not painted by the
/// [SliverFadeTransition] widget at all when the [opacity] animation reaches
/// zero.
///
/// To avoid such problems, it is generally a good idea to combine this widget
/// with a [SliverIgnorePointer] that one enables when the [opacity] animation
/// reaches zero. This prevents interactions with any children in the subtree
/// when the [sliver] is not visible. For performance reasons, when implementing
/// this, care should be taken not to rebuild the relevant widget (e.g. by
/// calling [State.setState]) except at the transition point.
///
/// See also:
///
/// * [SliverOpacity], which does not animate changes in opacity.
/// * [FadeTransition], the box version of this widget.
class SliverFadeTransition extends SingleChildRenderObjectWidget {
/// Creates an opacity transition.
const SliverFadeTransition({
super.key,
required this.opacity,
this.alwaysIncludeSemantics = false,
Widget? sliver,
}) : super(child: sliver);
/// The animation that controls the opacity of the sliver child.
///
/// If the current value of the opacity animation is v, the child will be
/// painted with an opacity of v. For example, if v is 0.5, the child will be
/// blended 50% with its background. Similarly, if v is 0.0, the child will be
/// completely transparent.
final Animation<double> opacity;
/// Whether the semantic information of the sliver child is always included.
///
/// Defaults to false.
///
/// When true, regardless of the opacity settings the sliver child's semantic
/// information is exposed as if the widget were fully visible. This is
/// useful in cases where labels may be hidden during animations that
/// would otherwise contribute relevant semantics.
final bool alwaysIncludeSemantics;
@override
RenderSliverAnimatedOpacity createRenderObject(BuildContext context) {
return RenderSliverAnimatedOpacity(
opacity: opacity,
alwaysIncludeSemantics: alwaysIncludeSemantics,
);
}
@override
void updateRenderObject(BuildContext context, RenderSliverAnimatedOpacity renderObject) {
renderObject
..opacity = opacity
..alwaysIncludeSemantics = alwaysIncludeSemantics;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Animation<double>>('opacity', opacity));
properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics'));
}
}
/// An interpolation between two relative rects.
///
/// This class specializes the interpolation of [Tween<RelativeRect>] to
/// use [RelativeRect.lerp].
///
/// See [Tween] for a discussion on how to use interpolation objects.
class RelativeRectTween extends Tween<RelativeRect> {
/// Creates a [RelativeRect] tween.
///
/// The [begin] and [end] properties may be null; the null value
/// is treated as [RelativeRect.fill].
RelativeRectTween({ super.begin, super.end });
/// Returns the value this variable has at the given animation clock value.
@override
RelativeRect lerp(double t) => RelativeRect.lerp(begin, end, t)!;
}
/// Animated version of [Positioned] which takes a specific
/// [Animation<RelativeRect>] to transition the child's position from a start
/// position to an end position over the lifetime of the animation.
///
/// Only works if it's the child of a [Stack].
///
/// Here's an illustration of the [PositionedTransition] widget, with it's [rect]
/// animated by a [CurvedAnimation] set to [Curves.elasticInOut]:
/// {@animation 300 378 https://flutter.github.io/assets-for-api-docs/assets/widgets/positioned_transition.mp4}
///
/// {@tool dartpad}
/// The following code implements the [PositionedTransition] as seen in the video
/// above:
///
/// ** See code in examples/api/lib/widgets/transitions/positioned_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AnimatedPositioned], which transitions a child's position without
/// taking an explicit [Animation] argument.
/// * [RelativePositionedTransition], a widget that transitions its child's
/// position based on the value of a rectangle relative to a bounding box.
/// * [SlideTransition], a widget that animates the position of a widget
/// relative to its normal position.
/// * [AlignTransition], an animated version of an [Align] that animates its
/// [Align.alignment] property.
/// * [ScaleTransition], a widget that animates the scale of a transformed
/// widget.
/// * [SizeTransition], a widget that animates its own size and clips and
/// aligns its child.
class PositionedTransition extends AnimatedWidget {
/// Creates a transition for [Positioned].
const PositionedTransition({
super.key,
required Animation<RelativeRect> rect,
required this.child,
}) : super(listenable: rect);
/// The animation that controls the child's size and position.
Animation<RelativeRect> get rect => listenable as Animation<RelativeRect>;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
Widget build(BuildContext context) {
return Positioned.fromRelativeRect(
rect: rect.value,
child: child,
);
}
}
/// Animated version of [Positioned] which transitions the child's position
/// based on the value of [rect] relative to a bounding box with the
/// specified [size].
///
/// Only works if it's the child of a [Stack].
///
/// Here's an illustration of the [RelativePositionedTransition] widget, with it's [rect]
/// animated by a [CurvedAnimation] set to [Curves.elasticInOut]:
/// {@animation 300 378 https://flutter.github.io/assets-for-api-docs/assets/widgets/relative_positioned_transition.mp4}
///
/// {@tool dartpad}
/// The following code implements the [RelativePositionedTransition] as seen in the video
/// above:
///
/// ** See code in examples/api/lib/widgets/transitions/relative_positioned_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [PositionedTransition], a widget that animates its child from a start
/// position to an end position over the lifetime of the animation.
/// * [AlignTransition], an animated version of an [Align] that animates its
/// [Align.alignment] property.
/// * [ScaleTransition], a widget that animates the scale of a transformed
/// widget.
/// * [SizeTransition], a widget that animates its own size and clips and
/// aligns its child.
/// * [SlideTransition], a widget that animates the position of a widget
/// relative to its normal position.
class RelativePositionedTransition extends AnimatedWidget {
/// Create an animated version of [Positioned].
///
/// Each frame, the [Positioned] widget will be configured to represent the
/// current value of the [rect] argument assuming that the stack has the given
/// [size].
const RelativePositionedTransition({
super.key,
required Animation<Rect?> rect,
required this.size,
required this.child,
}) : super(listenable: rect);
/// The animation that controls the child's size and position.
///
/// If the animation returns a null [Rect], the rect is assumed to be [Rect.zero].
///
/// See also:
///
/// * [size], which gets the size of the box that the [Positioned] widget's
/// offsets are relative to.
Animation<Rect?> get rect => listenable as Animation<Rect?>;
/// The [Positioned] widget's offsets are relative to a box of this
/// size whose origin is 0,0.
final Size size;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
Widget build(BuildContext context) {
final RelativeRect offsets = RelativeRect.fromSize(rect.value ?? Rect.zero, size);
return Positioned(
top: offsets.top,
right: offsets.right,
bottom: offsets.bottom,
left: offsets.left,
child: child,
);
}
}
/// Animated version of a [DecoratedBox] that animates the different properties
/// of its [Decoration].
///
/// Here's an illustration of the [DecoratedBoxTransition] widget, with it's
/// [decoration] animated by a [CurvedAnimation] set to [Curves.decelerate]:
/// {@animation 300 378 https://flutter.github.io/assets-for-api-docs/assets/widgets/decorated_box_transition.mp4}
///
/// {@tool dartpad}
/// The following code implements the [DecoratedBoxTransition] as seen in the video
/// above:
///
/// ** See code in examples/api/lib/widgets/transitions/decorated_box_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [DecoratedBox], which also draws a [Decoration] but is not animated.
/// * [AnimatedContainer], a more full-featured container that also animates on
/// decoration using an internal animation.
class DecoratedBoxTransition extends AnimatedWidget {
/// Creates an animated [DecoratedBox] whose [Decoration] animation updates
/// the widget.
///
/// See also:
///
/// * [DecoratedBox.new]
const DecoratedBoxTransition({
super.key,
required this.decoration,
this.position = DecorationPosition.background,
required this.child,
}) : super(listenable: decoration);
/// Animation of the decoration to paint.
///
/// Can be created using a [DecorationTween] interpolating typically between
/// two [BoxDecoration].
final Animation<Decoration> decoration;
/// Whether to paint the box decoration behind or in front of the child.
final DecorationPosition position;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: decoration.value,
position: position,
child: child,
);
}
}
/// Animated version of an [Align] that animates its [Align.alignment] property.
///
/// Here's an illustration of the [DecoratedBoxTransition] widget, with it's
/// [DecoratedBoxTransition.decoration] animated by a [CurvedAnimation] set to
/// [Curves.decelerate]:
///
/// {@animation 300 378 https://flutter.github.io/assets-for-api-docs/assets/widgets/align_transition.mp4}
///
/// {@tool dartpad}
/// The following code implements the [AlignTransition] as seen in the video
/// above:
///
/// ** See code in examples/api/lib/widgets/transitions/align_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AnimatedAlign], which animates changes to the [alignment] without
/// taking an explicit [Animation] argument.
/// * [PositionedTransition], a widget that animates its child from a start
/// position to an end position over the lifetime of the animation.
/// * [RelativePositionedTransition], a widget that transitions its child's
/// position based on the value of a rectangle relative to a bounding box.
/// * [SizeTransition], a widget that animates its own size and clips and
/// aligns its child.
/// * [SlideTransition], a widget that animates the position of a widget
/// relative to its normal position.
class AlignTransition extends AnimatedWidget {
/// Creates an animated [Align] whose [AlignmentGeometry] animation updates
/// the widget.
///
/// See also:
///
/// * [Align.new].
const AlignTransition({
super.key,
required Animation<AlignmentGeometry> alignment,
required this.child,
this.widthFactor,
this.heightFactor,
}) : super(listenable: alignment);
/// The animation that controls the child's alignment.
Animation<AlignmentGeometry> get alignment => listenable as Animation<AlignmentGeometry>;
/// If non-null, the child's width factor, see [Align.widthFactor].
final double? widthFactor;
/// If non-null, the child's height factor, see [Align.heightFactor].
final double? heightFactor;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
Widget build(BuildContext context) {
return Align(
alignment: alignment.value,
widthFactor: widthFactor,
heightFactor: heightFactor,
child: child,
);
}
}
/// Animated version of a [DefaultTextStyle] that animates the different properties
/// of its [TextStyle].
///
/// {@tool dartpad}
/// The following code implements the [DefaultTextStyleTransition] that shows
/// a transition between thick blue font and thin red font.
///
/// ** See code in examples/api/lib/widgets/transitions/default_text_style_transition.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AnimatedDefaultTextStyle], which animates changes in text style without
/// taking an explicit [Animation] argument.
/// * [DefaultTextStyle], which also defines a [TextStyle] for its descendants
/// but is not animated.
class DefaultTextStyleTransition extends AnimatedWidget {
/// Creates an animated [DefaultTextStyle] whose [TextStyle] animation updates
/// the widget.
const DefaultTextStyleTransition({
super.key,
required Animation<TextStyle> style,
required this.child,
this.textAlign,
this.softWrap = true,
this.overflow = TextOverflow.clip,
this.maxLines,
}) : super(listenable: style);
/// The animation that controls the descendants' text style.
Animation<TextStyle> get style => listenable as Animation<TextStyle>;
/// How the text should be aligned horizontally.
final TextAlign? textAlign;
/// Whether the text should break at soft line breaks.
///
/// See [DefaultTextStyle.softWrap] for more details.
final bool softWrap;
/// How visual overflow should be handled.
///
final TextOverflow overflow;
/// An optional maximum number of lines for the text to span, wrapping if necessary.
///
/// See [DefaultTextStyle.maxLines] for more details.
final int? maxLines;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: style.value,
textAlign: textAlign,
softWrap: softWrap,
overflow: overflow,
maxLines: maxLines,
child: child,
);
}
}
/// A general-purpose widget for building a widget subtree when a [Listenable]
/// changes.
///
/// [ListenableBuilder] is useful for more complex widgets that wish to listen
/// to changes in other objects as part of a larger build function. To use
/// [ListenableBuilder], construct the widget and pass it a [builder]
/// function.
///
/// Any subtype of [Listenable] (such as a [ChangeNotifier], [ValueNotifier], or
/// [Animation]) can be used with a [ListenableBuilder] to rebuild only certain
/// parts of a widget when the [Listenable] notifies its listeners. Although
/// they have identical implementations, if an [Animation] is being listened to,
/// consider using an [AnimatedBuilder] instead for better readability.
///
/// {@tool dartpad}
/// The following example uses a subclass of [ChangeNotifier] to hold the
/// application model's state, in this case, a counter. A [ListenableBuilder] is
/// then used to update the rendering (a [Text] widget) whenever the model changes.
///
/// ** See code in examples/api/lib/widgets/transitions/listenable_builder.2.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This version is identical, but using a [ValueNotifier] instead of a
/// dedicated subclass of [ChangeNotifier]. This works well when there is only a
/// single immutable value to be tracked.
///
/// ** See code in examples/api/lib/widgets/transitions/listenable_builder.1.dart **
/// {@end-tool}
///
/// ## Performance optimizations
///
/// {@template flutter.widgets.transitions.ListenableBuilder.optimizations}
/// If the [builder] function contains a subtree that does not depend on the
/// [listenable], it is more efficient to build that subtree once instead
/// of rebuilding it on every change of the [listenable].
///
/// Performance is therefore improved by specifying any widgets that don't need
/// to change using the prebuilt [child] attribute. The [ListenableBuilder]
/// passes this [child] back to the [builder] callback so that it can be
/// incorporated into the build.
///
/// Using this pre-built [child] is entirely optional, but can improve
/// performance significantly in some cases and is therefore a good practice.
/// {@endtemplate}
///
/// {@tool dartpad}
/// This example shows how a [ListenableBuilder] can be used to listen to a
/// [FocusNode] (which is also a [ChangeNotifier]) to see when a subtree has
/// focus, and modify a decoration when its focus state changes. Only the
/// [Container] is rebuilt when the [FocusNode] changes; the rest of the tree
/// (notably the [Focus] widget) remain unchanged from frame to frame.
///
/// ** See code in examples/api/lib/widgets/transitions/listenable_builder.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AnimatedBuilder], which has the same functionality, but is named more
/// appropriately for a builder triggered by [Animation]s.
/// * [ValueListenableBuilder], which is specialized for [ValueNotifier]s and
/// reports the new value in its builder callback.
class ListenableBuilder extends AnimatedWidget {
/// Creates a builder that responds to changes in [listenable].
const ListenableBuilder({
super.key,
required super.listenable,
required this.builder,
this.child,
});
/// The [Listenable] supplied to the constructor.
///
/// {@tool dartpad}
/// In this example, the [listenable] is a [ChangeNotifier] subclass that
/// encapsulates a list. The [ListenableBuilder] is rebuilt each time an item
/// is added to the list.
///
/// ** See code in examples/api/lib/widgets/transitions/listenable_builder.3.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AnimatedBuilder], a widget with identical functionality commonly
/// used with [Animation] [Listenable]s for better readability.
//
// Overridden getter to replace with documentation tailored to
// ListenableBuilder.
@override
Listenable get listenable => super.listenable;
/// Called every time the [listenable] notifies about a change.
///
/// The child given to the builder should typically be part of the returned
/// widget tree.
final TransitionBuilder builder;
/// The child widget to pass to the [builder].
///
/// {@macro flutter.widgets.transitions.ListenableBuilder.optimizations}
final Widget? child;
@override
Widget build(BuildContext context) => builder(context, child);
}
/// A general-purpose widget for building animations.
///
/// [AnimatedBuilder] is useful for more complex widgets that wish to include
/// an animation as part of a larger build function. To use [AnimatedBuilder],
/// construct the widget and pass it a builder function.
///
/// For simple cases without additional state, consider using
/// [AnimatedWidget].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=N-RiyZlv8v8}
///
/// Despite the name, [AnimatedBuilder] is not limited to [Animation]s, any
/// subtype of [Listenable] (such as [ChangeNotifier] or [ValueNotifier]) can be
/// used to trigger rebuilds. Although they have identical implementations, if
/// an [Animation] is not being listened to, consider using a
/// [ListenableBuilder] for better readability.
///
/// ## Performance optimizations
///
/// {@template flutter.widgets.transitions.AnimatedBuilder.optimizations}
/// If the [builder] function contains a subtree that does not depend on the
/// animation passed to the constructor, it's more efficient to build that
/// subtree once instead of rebuilding it on every animation tick.
///
/// If a pre-built subtree is passed as the [child] parameter, the
/// [AnimatedBuilder] will pass it back to the [builder] function so that it can
/// be incorporated into the build.
///
/// Using this pre-built child is entirely optional, but can improve
/// performance significantly in some cases and is therefore a good practice.
/// {@endtemplate}
///
/// {@tool dartpad}
/// This code defines a widget that spins a green square continually. It is
/// built with an [AnimatedBuilder] and makes use of the [child] feature to
/// avoid having to rebuild the [Container] each time.
///
/// ** See code in examples/api/lib/widgets/transitions/animated_builder.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ListenableBuilder], a widget with similar functionality, but named
/// more appropriately for a builder triggered on changes in [Listenable]s
/// that aren't [Animation]s.
/// * [TweenAnimationBuilder], which animates a property to a target value
/// without requiring manual management of an [AnimationController].
class AnimatedBuilder extends ListenableBuilder {
/// Creates an animated builder.
///
/// The [animation] and [builder] arguments are required.
const AnimatedBuilder({
super.key,
required Listenable animation,
required super.builder,
super.child,
}) : super(listenable: animation);
/// The [Listenable] supplied to the constructor (typically an [Animation]).
///
/// Also accessible through the [listenable] getter.
///
/// See also:
///
/// * [ListenableBuilder], a widget with similar functionality commonly used
/// with [Listenable]s (such as [ChangeNotifier]) for better readability
/// when the [animation] isn't an [Animation].
Listenable get animation => super.listenable;
/// The [Listenable] supplied to the constructor (typically an [Animation]).
///
/// Also accessible through the [animation] getter.
///
/// See also:
///
/// * [ListenableBuilder], a widget with identical functionality commonly
/// used with non-animation [Listenable]s for readability.
//
// Overridden getter to replace with documentation tailored to
// ListenableBuilder.
@override
Listenable get listenable => super.listenable;
/// Called every time the [animation] notifies about a change.
///
/// The child given to the builder should typically be part of the returned
/// widget tree.
//
// Overridden getter to replace with documentation tailored to
// AnimatedBuilder.
@override
TransitionBuilder get builder => super.builder;
}
| flutter/packages/flutter/lib/src/widgets/transitions.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/transitions.dart",
"repo_id": "flutter",
"token_count": 13430
} | 651 |
name: flutter
description: A framework for writing Flutter applications
homepage: https://flutter.dev
environment:
sdk: '>=3.3.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
characters: 1.3.0
collection: 1.18.0
material_color_utilities: 0.8.0
meta: 1.12.0
vector_math: 2.1.4
sky_engine:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter_goldens:
sdk: flutter
fake_async: 1.3.1
# To track memory leaks.
leak_tracker_flutter_testing: 3.0.3
leak_tracker_testing: 3.0.1
leak_tracker: 10.0.4
web: 0.5.1
async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
crypto: 3.0.3 # 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"
matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
path: 1.9.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"
process: 5.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_api: 0.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vm_service: 14.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
# PUBSPEC CHECKSUM: 1f15
| flutter/packages/flutter/pubspec.yaml/0 | {
"file_path": "flutter/packages/flutter/pubspec.yaml",
"repo_id": "flutter",
"token_count": 911
} | 652 |
# Tests for the Cupertino package
Avoid importing the Material 'package:flutter/material.dart' in these tests as
we're trying to test the Cupertino package in standalone scenarios.
The 'material' subdirectory contains tests for cross-interactions of Material
Cupertino widgets in hybridized apps.
Some tests may also be replicated in the Material tests when Material reuses
Cupertino components on iOS such as page transitions and text editing.
| flutter/packages/flutter/test/cupertino/README.md/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/README.md",
"repo_id": "flutter",
"token_count": 103
} | 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Shows prefix', (WidgetTester tester) async {
const Widget prefix = Text('Enter Value');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoFormRow(
prefix: prefix,
child: CupertinoTextField(),
),
),
),
);
expect(prefix, tester.widget(find.byType(Text)));
});
testWidgets('Shows child', (WidgetTester tester) async {
const Widget child = CupertinoTextField();
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoFormRow(
child: child,
),
),
),
);
expect(child, tester.widget(find.byType(CupertinoTextField)));
});
testWidgets('RTL puts prefix after child', (WidgetTester tester) async {
const Widget prefix = Text('Enter Value');
const Widget child = CupertinoTextField();
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.rtl,
child: CupertinoFormRow(
prefix: prefix,
child: child,
),
),
),
),
);
expect(tester.getTopLeft(find.byType(Text)).dx > tester.getTopLeft(find.byType(CupertinoTextField)).dx, true);
});
testWidgets('LTR puts child after prefix', (WidgetTester tester) async {
const Widget prefix = Text('Enter Value');
const Widget child = CupertinoTextField();
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: CupertinoFormRow(
prefix: prefix,
child: child,
),
),
),
),
);
expect(tester.getTopLeft(find.byType(Text)).dx > tester.getTopLeft(find.byType(CupertinoTextField)).dx, false);
});
testWidgets('Shows error widget', (WidgetTester tester) async {
const Widget error = Text('Error');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoFormRow(
error: error,
child: CupertinoTextField(),
),
),
),
);
expect(error, tester.widget(find.byType(Text)));
});
testWidgets('Shows helper widget', (WidgetTester tester) async {
const Widget helper = Text('Helper');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoFormRow(
helper: helper,
child: CupertinoTextField(),
),
),
),
);
expect(helper, tester.widget(find.byType(Text)));
});
testWidgets('Shows helper text above error text', (WidgetTester tester) async {
const Widget helper = Text('Helper');
const Widget error = CupertinoActivityIndicator();
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoFormRow(
helper: helper,
error: error,
child: CupertinoTextField(),
),
),
),
);
expect(
tester.getTopLeft(find.byType(CupertinoActivityIndicator)).dy > tester.getTopLeft(find.byType(Text)).dy,
true,
);
});
testWidgets('Shows helper in label color and error text in red color', (WidgetTester tester) async {
const Widget helper = Text('Helper');
const Widget error = Text('Error');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoFormRow(
helper: helper,
error: error,
child: CupertinoTextField(),
),
),
),
);
final DefaultTextStyle helperTextStyle =
tester.widget(find.byType(DefaultTextStyle).first);
expect(helperTextStyle.style.color, CupertinoColors.label);
final DefaultTextStyle errorTextStyle =
tester.widget(find.byType(DefaultTextStyle).last);
expect(errorTextStyle.style.color, CupertinoColors.destructiveRed);
});
testWidgets('CupertinoFormRow adapts to MaterialApp dark mode', (WidgetTester tester) async {
const Widget prefix = Text('Prefix');
const Widget helper = Text('Helper');
Widget buildFormRow(Brightness brightness) {
return MaterialApp(
theme: ThemeData(brightness: brightness),
home: const Center(
child: CupertinoFormRow(
prefix: prefix,
helper: helper,
child: CupertinoTextField(),
),
),
);
}
// CupertinoFormRow with light theme.
await tester.pumpWidget(buildFormRow(Brightness.light));
RenderParagraph helperParagraph = tester.renderObject(find.text('Helper'));
expect(helperParagraph.text.style!.color, CupertinoColors.label);
// Text style should not return unresolved color.
expect(helperParagraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse);
RenderParagraph prefixParagraph = tester.renderObject(find.text('Prefix'));
expect(prefixParagraph.text.style!.color, CupertinoColors.label);
// Text style should not return unresolved color.
expect(prefixParagraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse);
// CupertinoFormRow with light theme.
await tester.pumpWidget(buildFormRow(Brightness.dark));
helperParagraph = tester.renderObject(find.text('Helper'));
expect(helperParagraph.text.style!.color, CupertinoColors.label);
// Text style should not return unresolved color.
expect(helperParagraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse);
prefixParagraph = tester.renderObject(find.text('Prefix'));
expect(prefixParagraph.text.style!.color, CupertinoColors.label);
// Text style should not return unresolved color.
expect(prefixParagraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse);
});
}
| flutter/packages/flutter/test/cupertino/form_row_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/form_row_test.dart",
"repo_id": "flutter",
"token_count": 2590
} | 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.
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import '../image_data.dart';
/// Integration tests testing both [CupertinoPageScaffold] and [CupertinoTabScaffold].
void main() {
testWidgets('Contents are behind translucent bar', (WidgetTester tester) async {
await tester.pumpWidget(
const CupertinoApp(
home: CupertinoPageScaffold(
// Default nav bar is translucent.
navigationBar: CupertinoNavigationBar(
middle: Text('Title'),
),
child: Center(),
),
),
);
expect(tester.getTopLeft(find.byType(Center)), Offset.zero);
});
testWidgets('Opaque bar pushes contents down', (WidgetTester tester) async {
late BuildContext childContext;
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(viewInsets: EdgeInsets.only(top: 20)),
child: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Opaque'),
backgroundColor: Color(0xFFF8F8F8),
),
child: Builder(
builder: (BuildContext context) {
childContext = context;
return Container();
},
),
),
),
));
expect(MediaQuery.of(childContext).padding.top, 0);
// The top of the [Container] is 44 px from the top of the screen because
// it's pushed down by the opaque navigation bar whose height is 44 px,
// and the 20 px [MediaQuery] top padding is fully absorbed by the navigation bar.
expect(tester.getRect(find.byType(Container)), const Rect.fromLTRB(0, 44, 800, 600));
});
testWidgets('dark mode and obstruction work', (WidgetTester tester) async {
const Color dynamicColor = CupertinoDynamicColor.withBrightness(
color: Color(0xFFF8F8F8),
darkColor: Color(0xEE333333),
);
const CupertinoDynamicColor backgroundColor = CupertinoDynamicColor.withBrightness(
color: Color(0xFFFFFFFF),
darkColor: Color(0xFF000000),
);
late BuildContext childContext;
Widget scaffoldWithBrightness(Brightness brightness) {
return Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData(
platformBrightness: brightness,
viewInsets: const EdgeInsets.only(top: 20),
),
child: CupertinoPageScaffold(
backgroundColor: backgroundColor,
navigationBar: const CupertinoNavigationBar(
middle: Text('Title'),
backgroundColor: dynamicColor,
),
child: Builder(
builder: (BuildContext context) {
childContext = context;
return Container();
},
),
),
),
);
}
await tester.pumpWidget(scaffoldWithBrightness(Brightness.light));
expect(MediaQuery.of(childContext).padding.top, 0);
expect(find.byType(CupertinoPageScaffold), paints..rect(color: backgroundColor.color));
await tester.pumpWidget(scaffoldWithBrightness(Brightness.dark));
expect(MediaQuery.of(childContext).padding.top, greaterThan(0));
expect(find.byType(CupertinoPageScaffold), paints..rect(color: backgroundColor.darkColor));
});
testWidgets('Contents padding from viewInsets', (WidgetTester tester) async {
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(viewInsets: EdgeInsets.only(bottom: 100.0)),
child: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Opaque'),
backgroundColor: Color(0xFFF8F8F8),
),
child: Container(),
),
),
));
expect(tester.getSize(find.byType(Container)).height, 600.0 - 44.0 - 100.0);
late BuildContext childContext;
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(viewInsets: EdgeInsets.only(bottom: 100.0)),
child: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Transparent'),
),
child: Builder(
builder: (BuildContext context) {
childContext = context;
return Container();
},
),
),
),
));
expect(tester.getSize(find.byType(Container)).height, 600.0 - 100.0);
// The shouldn't see a media query view inset because it was consumed by
// the scaffold.
expect(MediaQuery.of(childContext).viewInsets.bottom, 0);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(viewInsets: EdgeInsets.only(bottom: 100.0)),
child: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Title'),
),
resizeToAvoidBottomInset: false,
child: Container(),
),
),
));
expect(tester.getSize(find.byType(Container)).height, 600.0);
});
testWidgets('Contents bottom padding are not consumed by viewInsets when resizeToAvoidBottomInset overridden', (WidgetTester tester) async {
const Widget child = CupertinoPageScaffold(
resizeToAvoidBottomInset: false,
navigationBar: CupertinoNavigationBar(
middle: Text('Opaque'),
backgroundColor: Color(0xFFF8F8F8),
),
child: Placeholder(),
);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData(viewInsets: EdgeInsets.only(bottom: 20.0)),
child: child,
),
),
);
final Offset initialPoint = tester.getCenter(find.byType(Placeholder));
// Consume bottom padding - as if by the keyboard opening
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData(
viewPadding: EdgeInsets.only(bottom: 20),
viewInsets: EdgeInsets.only(bottom: 300),
),
child: child,
),
),
);
final Offset finalPoint = tester.getCenter(find.byType(Placeholder));
expect(initialPoint, finalPoint);
});
testWidgets('Contents are between opaque bars', (WidgetTester tester) async {
const Center page1Center = Center();
await tester.pumpWidget(
CupertinoApp(
home: CupertinoTabScaffold(
tabBar: CupertinoTabBar(
backgroundColor: CupertinoColors.white,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))),
label: 'Tab 1',
),
BottomNavigationBarItem(
icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))),
label: 'Tab 2',
),
],
),
tabBuilder: (BuildContext context, int index) {
return index == 0
? const CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
backgroundColor: CupertinoColors.white,
middle: Text('Title'),
),
child: page1Center,
)
: const Stack();
},
),
),
);
expect(tester.getSize(find.byWidget(page1Center)).height, 600.0 - 44.0 - 50.0);
});
testWidgets('Contents have automatic sliver padding between translucent bars', (WidgetTester tester) async {
const SizedBox content = SizedBox(height: 600.0, width: 600.0);
await tester.pumpWidget(
CupertinoApp(
home: MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.symmetric(vertical: 20.0),
),
child: CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))),
label: 'Tab 1',
),
BottomNavigationBarItem(
icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))),
label: 'Tab 2',
),
],
),
tabBuilder: (BuildContext context, int index) {
return index == 0
? CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Title'),
),
child: ListView(
children: const <Widget>[
content,
],
),
)
: const Stack();
},
),
),
),
);
// List content automatically padded by nav bar and top media query padding.
expect(tester.getTopLeft(find.byWidget(content)).dy, 20.0 + 44.0);
// Overscroll to the bottom.
await tester.drag(find.byWidget(content), const Offset(0.0, -400.0), warnIfMissed: false); // can't be hit (it's empty) but we're aiming for the list really so it doesn't matter
// Let it bounce back.
await tester.pump();
await tester.pump(const Duration(seconds: 1));
// List content automatically padded by tab bar and bottom media query padding.
expect(tester.getBottomLeft(find.byWidget(content)).dy, 600 - 20.0 - 50.0);
});
testWidgets('iOS independent tab navigation', (WidgetTester tester) async {
// A full on iOS information architecture app with 2 tabs, and 2 pages
// in each with independent navigation states.
await tester.pumpWidget(
CupertinoApp(
home: CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))),
label: 'Tab 1',
),
BottomNavigationBarItem(
icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))),
label: 'Tab 2',
),
],
),
tabBuilder: (BuildContext context, int index) {
// For 1-indexed readability.
++index;
return CupertinoTabView(
builder: (BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Page 1 of tab $index'),
),
child: Center(
child: CupertinoButton(
child: const Text('Next'),
onPressed: () {
Navigator.of(context).push(
CupertinoPageRoute<void>(
builder: (BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Page 2 of tab $index'),
),
child: Center(
child: CupertinoButton(
child: const Text('Back'),
onPressed: () {
Navigator.of(context).pop();
},
),
),
);
},
),
);
},
),
),
);
},
);
},
),
),
);
expect(find.text('Page 1 of tab 1'), findsOneWidget);
expect(find.text('Page 1 of tab 2'), findsNothing); // Lazy building so not built yet.
await tester.tap(find.text('Tab 2'));
await tester.pump();
expect(find.text('Page 1 of tab 1'), findsNothing); // It's offstage now.
expect(find.text('Page 1 of tab 1', skipOffstage: false), findsOneWidget);
expect(find.text('Page 1 of tab 2'), findsOneWidget);
// Navigate in tab 2.
await tester.tap(find.text('Next'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
expect(find.text('Page 2 of tab 2'), isOnstage);
expect(find.text('Page 1 of tab 1', skipOffstage: false), isOffstage);
await tester.tap(find.text('Tab 1'));
await tester.pump();
// Independent navigation stacks.
expect(find.text('Page 1 of tab 1'), isOnstage);
expect(find.text('Page 2 of tab 2', skipOffstage: false), isOffstage);
// Navigate in tab 1.
await tester.tap(find.text('Next'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
expect(find.text('Page 2 of tab 1'), isOnstage);
expect(find.text('Page 2 of tab 2', skipOffstage: false), isOffstage);
await tester.tap(find.text('Tab 2'));
await tester.pump();
expect(find.text('Page 2 of tab 2'), isOnstage);
expect(find.text('Page 2 of tab 1', skipOffstage: false), isOffstage);
// Pop in tab 2
await tester.tap(find.text('Back'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 600));
expect(find.text('Page 1 of tab 2'), isOnstage);
expect(find.text('Page 2 of tab 1', skipOffstage: false), isOffstage);
});
testWidgets('Decorated with white background by default', (WidgetTester tester) async {
await tester.pumpWidget(
const CupertinoApp(
home: CupertinoPageScaffold(
child: Center(),
),
),
);
final DecoratedBox decoratedBox = tester.widgetList(find.byType(DecoratedBox)).elementAt(1) as DecoratedBox;
expect(decoratedBox.decoration.runtimeType, BoxDecoration);
final BoxDecoration decoration = decoratedBox.decoration as BoxDecoration;
expect(decoration.color, isSameColorAs(CupertinoColors.white));
});
testWidgets('Overrides background color', (WidgetTester tester) async {
await tester.pumpWidget(
const CupertinoApp(
home: CupertinoPageScaffold(
backgroundColor: Color(0xFF010203),
child: Center(),
),
),
);
final DecoratedBox decoratedBox = tester.widgetList(find.byType(DecoratedBox)).elementAt(1) as DecoratedBox;
expect(decoratedBox.decoration.runtimeType, BoxDecoration);
final BoxDecoration decoration = decoratedBox.decoration as BoxDecoration;
expect(decoration.color, const Color(0xFF010203));
});
testWidgets('Lists in CupertinoPageScaffold scroll to the top when status bar tapped', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
builder: (BuildContext context, Widget? child) {
// Acts as a 20px status bar at the root of the app.
return MediaQuery(
data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(top: 20)),
child: child!,
);
},
home: CupertinoPageScaffold(
// Default nav bar is translucent.
navigationBar: const CupertinoNavigationBar(
middle: Text('Title'),
),
child: ListView.builder(
itemExtent: 50,
itemBuilder: (BuildContext context, int index) => Text(index.toString()),
),
),
),
);
// Top media query padding 20 + translucent nav bar 44.
expect(tester.getTopLeft(find.text('0')).dy, 64);
expect(tester.getTopLeft(find.text('6')).dy, 364);
await tester.fling(
find.text('5'), // Find some random text on the screen.
const Offset(0, -200),
20,
);
await tester.pumpAndSettle();
expect(tester.getTopLeft(find.text('6')).dy, moreOrLessEquals(166.833, epsilon: 0.1));
expect(tester.getTopLeft(find.text('12')).dy, moreOrLessEquals(466.8333333333334, epsilon: 0.1));
// The media query top padding is 20. Tapping at 20 should do nothing.
await tester.tapAt(const Offset(400, 20));
await tester.pumpAndSettle();
expect(tester.getTopLeft(find.text('6')).dy, moreOrLessEquals(166.833, epsilon: 0.1));
expect(tester.getTopLeft(find.text('12')).dy, moreOrLessEquals(466.8333333333334, epsilon: 0.1));
// Tap 1 pixel higher.
await tester.tapAt(const Offset(400, 19));
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getTopLeft(find.text('0')).dy, 64);
expect(tester.getTopLeft(find.text('6')).dy, 364);
expect(find.text('12'), findsNothing);
});
testWidgets('resizeToAvoidBottomInset is supported even when no navigationBar', (WidgetTester tester) async {
Widget buildFrame(bool showNavigationBar, bool showKeyboard) {
return CupertinoApp(
home: MediaQuery(
data: MediaQueryData(
viewPadding: const EdgeInsets.only(bottom: 20),
viewInsets: EdgeInsets.only(bottom: showKeyboard ? 300 : 20),
),
child: CupertinoPageScaffold(
navigationBar: showNavigationBar ? const CupertinoNavigationBar(
middle: Text('Title'),
) : null,
child: Builder(
builder: (BuildContext context) => Center(
child: CupertinoTextField(
placeholder: MediaQuery.viewInsetsOf(context).toString(),
),
),
),
),
),
);
}
// CupertinoPageScaffold should consume the viewInsets in all cases
final String expectedViewInsets = EdgeInsets.zero.toString();
// When there is a nav bar and no keyboard.
await tester.pumpWidget(buildFrame(true, false));
final Offset positionNoInsetWithNavBar = tester.getTopLeft(find.byType(CupertinoTextField));
expect((find.byType(CupertinoTextField).evaluate().first.widget as CupertinoTextField).placeholder, expectedViewInsets);
// When there is a nav bar and keyboard, the CupertinoTextField moves up.
await tester.pumpWidget(buildFrame(true, true));
await tester.pumpAndSettle();
final Offset positionWithInsetWithNavBar = tester.getTopLeft(find.byType(CupertinoTextField));
expect(positionWithInsetWithNavBar.dy, lessThan(positionNoInsetWithNavBar.dy));
expect((find.byType(CupertinoTextField).evaluate().first.widget as CupertinoTextField).placeholder, expectedViewInsets);
// When there is no nav bar and no keyboard, the CupertinoTextField is still
// centered.
await tester.pumpWidget(buildFrame(false, false));
final Offset positionNoInsetNoNavBar = tester.getTopLeft(find.byType(CupertinoTextField));
expect(positionNoInsetNoNavBar, equals(positionNoInsetWithNavBar));
expect((find.byType(CupertinoTextField).evaluate().first.widget as CupertinoTextField).placeholder, expectedViewInsets);
// When there is a keyboard but no nav bar, the CupertinoTextField also
// moves up to the same position as when there is a keyboard and nav bar.
await tester.pumpWidget(buildFrame(false, true));
await tester.pumpAndSettle();
final Offset positionWithInsetNoNavBar = tester.getTopLeft(find.byType(CupertinoTextField));
expect(positionWithInsetNoNavBar.dy, lessThan(positionNoInsetNoNavBar.dy));
expect(positionWithInsetNoNavBar, equals(positionWithInsetWithNavBar));
expect((find.byType(CupertinoTextField).evaluate().first.widget as CupertinoTextField).placeholder, expectedViewInsets);
});
testWidgets('textScaleFactor is set to 1.0', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: Builder(builder: (BuildContext context) {
return MediaQuery.withClampedTextScaling(
minScaleFactor: 99,
maxScaleFactor: 99,
child: const CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('middle'),
leading: Text('leading'),
trailing: Text('trailing'),
),
child: Text('content'),
),
);
}),
),
);
final Iterable<RichText> richTextList = tester.widgetList<RichText>(
find.descendant(of: find.byType(CupertinoNavigationBar), matching: find.byType(RichText)),
);
expect(richTextList.length, greaterThan(0));
expect(richTextList.any((RichText text) => text.textScaleFactor != 1), isFalse);
expect(tester.widget<RichText>(find.descendant(of: find.text('content'), matching: find.byType(RichText))).textScaler, const TextScaler.linear(99.0));
});
}
| flutter/packages/flutter/test/cupertino/scaffold_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/scaffold_test.dart",
"repo_id": "flutter",
"token_count": 9433
} | 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/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
testWidgets('can press', (WidgetTester tester) async {
bool pressed = false;
await tester.pumpWidget(
CupertinoApp(
home: Center(
child: CupertinoTextSelectionToolbarButton(
child: const Text('Tap me'),
onPressed: () {
pressed = true;
},
),
),
),
);
expect(pressed, false);
await tester.tap(find.byType(CupertinoTextSelectionToolbarButton));
expect(pressed, true);
});
testWidgets('background darkens when pressed', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: Center(
child: CupertinoTextSelectionToolbarButton(
child: const Text('Tap me'),
onPressed: () { },
),
),
),
);
// Original with transparent background.
DecoratedBox decoratedBox = tester.widget(find.descendant(
of: find.byType(CupertinoButton),
matching: find.byType(DecoratedBox),
));
BoxDecoration boxDecoration = decoratedBox.decoration as BoxDecoration;
expect(boxDecoration.color, const Color(0x00000000));
// Make a "down" gesture on the button.
final Offset center = tester.getCenter(find.byType(CupertinoTextSelectionToolbarButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pumpAndSettle();
// When pressed, the background darkens.
decoratedBox = tester.widget(find.descendant(
of: find.byType(CupertinoTextSelectionToolbarButton),
matching: find.byType(DecoratedBox),
));
boxDecoration = decoratedBox.decoration as BoxDecoration;
expect(boxDecoration.color!.value, const Color(0x10000000).value);
// Release the down gesture.
await gesture.up();
await tester.pumpAndSettle();
// Color is back to transparent.
decoratedBox = tester.widget(find.descendant(
of: find.byType(CupertinoTextSelectionToolbarButton),
matching: find.byType(DecoratedBox),
));
boxDecoration = decoratedBox.decoration as BoxDecoration;
expect(boxDecoration.color, const Color(0x00000000));
});
testWidgets('passing null to onPressed disables the button', (WidgetTester tester) async {
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoTextSelectionToolbarButton(
child: Text('Tap me'),
),
),
),
);
expect(find.byType(CupertinoButton), findsOneWidget);
final CupertinoButton button = tester.widget(find.byType(CupertinoButton));
expect(button.enabled, isFalse);
});
}
| flutter/packages/flutter/test/cupertino/text_selection_toolbar_button_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/text_selection_toolbar_button_test.dart",
"repo_id": "flutter",
"token_count": 1139
} | 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 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
// ignore: unused_field
enum _TestEnum { a, b, c, d, e, f, g, h }
void main() {
test('BitField control test', () {
final BitField<_TestEnum> field = BitField<_TestEnum>(8);
expect(field[_TestEnum.d], isFalse);
field[_TestEnum.d] = true;
field[_TestEnum.e] = true;
expect(field[_TestEnum.c], isFalse);
expect(field[_TestEnum.d], isTrue);
expect(field[_TestEnum.e], isTrue);
field[_TestEnum.e] = false;
expect(field[_TestEnum.c], isFalse);
expect(field[_TestEnum.d], isTrue);
expect(field[_TestEnum.e], isFalse);
field.reset();
expect(field[_TestEnum.c], isFalse);
expect(field[_TestEnum.d], isFalse);
expect(field[_TestEnum.e], isFalse);
field.reset(true);
expect(field[_TestEnum.c], isTrue);
expect(field[_TestEnum.d], isTrue);
expect(field[_TestEnum.e], isTrue);
}, skip: isBrowser); // [intended] BitField is not supported when compiled to Javascript.
test('BitField.filed control test', () {
final BitField<_TestEnum> field1 = BitField<_TestEnum>.filled(8, true);
expect(field1[_TestEnum.d], isTrue);
final BitField<_TestEnum> field2 = BitField<_TestEnum>.filled(8, false);
expect(field2[_TestEnum.d], isFalse);
}, skip: isBrowser); // [intended] BitField is not supported when compiled to Javascript.
}
| flutter/packages/flutter/test/foundation/bit_field_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/bit_field_test.dart",
"repo_id": "flutter",
"token_count": 588
} | 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 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
class PrintOverrideTestBinding extends AutomatedTestWidgetsFlutterBinding {
@override
DebugPrintCallback get debugPrintOverride => _enablePrint ? debugPrint : _emptyPrint;
static void _emptyPrint(String? message, { int? wrapWidth }) {}
static bool _enablePrint = true;
static void runWithDebugPrintDisabled(void Function() f) {
try {
_enablePrint = false;
f();
} finally {
_enablePrint = true;
}
}
}
void main() {
// LeakTesting is turned off because it adds subscriptions to
// [FlutterMemoryAllocations], that may interfere with the tests.
LeakTesting.settings = LeakTesting.settings.withIgnoredAll();
final FlutterMemoryAllocations ma = FlutterMemoryAllocations.instance;
PrintOverrideTestBinding();
setUp(() {
assert(!ma.hasListeners);
_checkSdkHandlersNotSet();
});
test('addListener and removeListener add and remove listeners.', () {
final ObjectEvent event = ObjectDisposed(object: 'object');
ObjectEvent? receivedEvent;
void listener(ObjectEvent event) => receivedEvent = event;
expect(ma.hasListeners, isFalse);
ma.addListener(listener);
_checkSdkHandlersSet();
ma.dispatchObjectEvent(event);
expect(receivedEvent, equals(event));
expect(ma.hasListeners, isTrue);
receivedEvent = null;
ma.removeListener(listener);
ma.dispatchObjectEvent(event);
expect(receivedEvent, isNull);
expect(ma.hasListeners, isFalse);
_checkSdkHandlersNotSet();
});
testWidgets('dispatchObjectEvent handles bad listeners', (WidgetTester tester) async {
final ObjectEvent event = ObjectDisposed(object: 'object');
final List<String> log = <String>[];
void badListener1(ObjectEvent event) {
log.add('badListener1');
throw ArgumentError();
}
void listener1(ObjectEvent event) => log.add('listener1');
void badListener2(ObjectEvent event) {
log.add('badListener2');
throw ArgumentError();
}
void listener2(ObjectEvent event) => log.add('listener2');
ma.addListener(badListener1);
_checkSdkHandlersSet();
ma.addListener(listener1);
ma.addListener(badListener2);
ma.addListener(listener2);
PrintOverrideTestBinding.runWithDebugPrintDisabled(
() => ma.dispatchObjectEvent(event)
);
expect(log, <String>['badListener1', 'listener1', 'badListener2','listener2']);
expect(tester.takeException(), contains('Multiple exceptions (2)'));
ma.removeListener(badListener1);
_checkSdkHandlersSet();
ma.removeListener(listener1);
ma.removeListener(badListener2);
ma.removeListener(listener2);
_checkSdkHandlersNotSet();
log.clear();
expect(ma.hasListeners, isFalse);
ma.dispatchObjectEvent(event);
expect(log, <String>[]);
});
test('dispatchObjectEvent does not invoke concurrently added listeners', () {
final ObjectEvent event = ObjectDisposed(object: 'object');
final List<String> log = <String>[];
void listener2(ObjectEvent event) => log.add('listener2');
void listener1(ObjectEvent event) {
log.add('listener1');
ma.addListener(listener2);
}
ma.addListener(listener1);
_checkSdkHandlersSet();
ma.dispatchObjectEvent(event);
expect(log, <String>['listener1']);
log.clear();
ma.dispatchObjectEvent(event);
expect(log, <String>['listener1','listener2']);
log.clear();
ma.removeListener(listener1);
ma.removeListener(listener2);
_checkSdkHandlersNotSet();
expect(ma.hasListeners, isFalse);
ma.dispatchObjectEvent(event);
expect(log, <String>[]);
});
test('dispatchObjectEvent does not invoke concurrently removed listeners', () {
final ObjectEvent event = ObjectDisposed(object: 'object');
final List<String> log = <String>[];
void listener2(ObjectEvent event) => log.add('listener2');
void listener1(ObjectEvent event) {
log.add('listener1');
ma.removeListener(listener2);
expect(ma.hasListeners, isFalse);
}
ma.addListener(listener1);
ma.addListener(listener2);
ma.dispatchObjectEvent(event);
expect(log, <String>['listener1']);
log.clear();
ma.removeListener(listener1);
_checkSdkHandlersNotSet();
expect(ma.hasListeners, isFalse);
});
test('last removeListener unsubscribes from Flutter SDK events', () {
void listener1(ObjectEvent event) {}
void listener2(ObjectEvent event) {}
ma.addListener(listener1);
_checkSdkHandlersSet();
ma.addListener(listener2);
_checkSdkHandlersSet();
ma.removeListener(listener1);
_checkSdkHandlersSet();
ma.removeListener(listener2);
_checkSdkHandlersNotSet();
});
test('kFlutterMemoryAllocationsEnabled is true in debug mode.', () {
expect(kFlutterMemoryAllocationsEnabled, isTrue);
});
test('publishers in Flutter dispatch events in debug mode', () async {
int eventCount = 0;
void listener(ObjectEvent event) => eventCount++;
ma.addListener(listener);
final int expectedEventCount = await _activateFlutterObjectsAndReturnCountOfEvents();
expect(eventCount, expectedEventCount);
ma.removeListener(listener);
_checkSdkHandlersNotSet();
expect(ma.hasListeners, isFalse);
});
}
void _checkSdkHandlersSet() {
expect(Image.onCreate, isNotNull);
expect(Picture.onCreate, isNotNull);
expect(Image.onDispose, isNotNull);
expect(Picture.onDispose, isNotNull);
}
void _checkSdkHandlersNotSet() {
expect(Image.onCreate, isNull);
expect(Picture.onCreate, isNull);
expect(Image.onDispose, isNull);
expect(Picture.onDispose, isNull);
}
/// Create and dispose Flutter objects to fire memory allocation events.
Future<int> _activateFlutterObjectsAndReturnCountOfEvents() async {
int count = 0;
final ValueNotifier<bool> valueNotifier = ValueNotifier<bool>(true); count++;
final ChangeNotifier changeNotifier = ChangeNotifier()..addListener(() {}); count++;
final Picture picture = _createPicture(); count++;
valueNotifier.dispose(); count++;
changeNotifier.dispose(); count++;
picture.dispose(); count++;
final Image image = await _createImage(); count++; count++; count++;
image.dispose(); count++;
return count;
}
Future<Image> _createImage() async {
final Picture picture = _createPicture();
final Image result = await picture.toImage(10, 10);
picture.dispose();
return result;
}
Picture _createPicture() {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0);
canvas.clipRect(rect);
return recorder.endRecording();
}
| flutter/packages/flutter/test/foundation/memory_allocations_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/memory_allocations_test.dart",
"repo_id": "flutter",
"token_count": 2368
} | 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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'gesture_tester.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
testGesture('A force press can be recognized', (GestureTester tester) {
// Device specific constants that represent those from the iPhone X
const double pressureMin = 0;
const double pressureMax = 6.66;
int started = 0;
int peaked = 0;
int updated = 0;
int ended = 0;
Offset? startGlobalPosition;
void onStart(ForcePressDetails details) {
startGlobalPosition = details.globalPosition;
started += 1;
}
final ForcePressGestureRecognizer force = ForcePressGestureRecognizer();
addTearDown(force.dispose);
force.onStart = onStart;
force.onPeak = (ForcePressDetails details) => peaked += 1;
force.onUpdate = (ForcePressDetails details) => updated += 1;
force.onEnd = (ForcePressDetails details) => ended += 1;
const int pointerValue = 1;
final TestPointer pointer = TestPointer();
const PointerDownEvent down = PointerDownEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 0, pressureMin: pressureMin, pressureMax: pressureMax);
pointer.setDownInfo(down, const Offset(10.0, 10.0));
force.addPointer(down);
tester.closeArena(pointerValue);
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
// Pressure fed into the test environment simulates the values received directly from the device.
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 2.5, pressureMin: pressureMin, pressureMax: pressureMax));
// We have not hit the start pressure, so no events should be true.
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 2.8, pressureMin: pressureMin, pressureMax: pressureMax));
// We have just hit the start pressure so just the start event should be triggered and one update call should have occurred.
expect(started, 1);
expect(peaked, 0);
expect(updated, 1);
expect(ended, 0);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 3.3, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 4.0, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 5.0, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressureMin: pressureMin, pressureMax: pressureMax));
// We have exceeded the start pressure so update should be greater than 0.
expect(started, 1);
expect(updated, 5);
expect(peaked, 0);
expect(ended, 0);
expect(startGlobalPosition, const Offset(10.0, 10.0));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 6.0, pressureMin: pressureMin, pressureMax: pressureMax));
// We have exceeded the peak pressure so peak pressure should be true.
expect(started, 1);
expect(updated, 6);
expect(peaked, 1);
expect(ended, 0);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 3.3, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 4.0, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 5.0, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressureMin: pressureMin, pressureMax: pressureMax));
// Update is still called.
expect(started, 1);
expect(updated, 10);
expect(peaked, 1);
expect(ended, 0);
tester.route(pointer.up());
// We have ended the gesture so ended should be true.
expect(started, 1);
expect(updated, 10);
expect(peaked, 1);
expect(ended, 1);
});
testGesture('Invalid pressure ranges capabilities are not recognized', (GestureTester tester) {
void testGestureWithMaxPressure(double pressureMax) {
int started = 0;
int peaked = 0;
int updated = 0;
int ended = 0;
final ForcePressGestureRecognizer force = ForcePressGestureRecognizer();
addTearDown(force.dispose);
force.onStart = (ForcePressDetails details) => started += 1;
force.onPeak = (ForcePressDetails details) => peaked += 1;
force.onUpdate = (ForcePressDetails details) => updated += 1;
force.onEnd = (ForcePressDetails details) => ended += 1;
const int pointerValue = 1;
final TestPointer pointer = TestPointer();
final PointerDownEvent down = PointerDownEvent(pointer: pointerValue, position: const Offset(10.0, 10.0), pressure: 0, pressureMin: 0, pressureMax: pressureMax);
pointer.setDownInfo(down, const Offset(10.0, 10.0));
force.addPointer(down);
tester.closeArena(pointerValue);
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
// Pressure fed into the test environment simulates the values received directly from the device.
tester.route(PointerMoveEvent(pointer: pointerValue, position: const Offset(10.0, 10.0), pressure: 10, pressureMin: 0, pressureMax: pressureMax));
// Regardless of current pressure, this recognizer shouldn't participate or
// trigger any callbacks.
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
tester.route(pointer.up());
// There should still be no callbacks.
expect(started, 0);
expect(updated, 0);
expect(peaked, 0);
expect(ended, 0);
}
testGestureWithMaxPressure(0);
testGestureWithMaxPressure(1);
testGestureWithMaxPressure(-1);
testGestureWithMaxPressure(0.5);
});
testGesture('If minimum pressure is not reached, start and end callbacks are not called', (GestureTester tester) {
// Device specific constants that represent those from the iPhone X
const double pressureMin = 0;
const double pressureMax = 6.66;
int started = 0;
int peaked = 0;
int updated = 0;
int ended = 0;
final ForcePressGestureRecognizer force = ForcePressGestureRecognizer();
addTearDown(force.dispose);
force.onStart = (_) => started += 1;
force.onPeak = (_) => peaked += 1;
force.onUpdate = (_) => updated += 1;
force.onEnd = (_) => ended += 1;
const int pointerValue = 1;
final TestPointer pointer = TestPointer();
const PointerDownEvent down = PointerDownEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 0, pressureMin: pressureMin, pressureMax: pressureMax);
pointer.setDownInfo(down, const Offset(10.0, 10.0));
force.addPointer(down);
tester.closeArena(1);
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
// Pressure fed into the test environment simulates the values received directly from the device.
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 2.5, pressureMin: pressureMin, pressureMax: pressureMax));
// We have not hit the start pressure, so no events should be true.
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
tester.route(pointer.up());
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
});
testGesture('Should recognize drag and not force touch if there is a drag recognizer', (GestureTester tester) {
final PanGestureRecognizer drag = PanGestureRecognizer();
addTearDown(drag.dispose);
// Device specific constants that represent those from the iPhone X
const double pressureMin = 0;
const double pressureMax = 6.66;
int started = 0;
int peaked = 0;
int updated = 0;
int ended = 0;
final ForcePressGestureRecognizer force = ForcePressGestureRecognizer();
addTearDown(force.dispose);
force.onStart = (_) => started += 1;
force.onPeak = (_) => peaked += 1;
force.onUpdate = (_) => updated += 1;
force.onEnd = (_) => ended += 1;
int didStartPan = 0;
drag.onStart = (_) => didStartPan += 1;
const int pointerValue = 1;
final TestPointer pointer = TestPointer();
const PointerDownEvent down = PointerDownEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressureMin: pressureMin, pressureMax: pressureMax);
pointer.setDownInfo(down, const Offset(10.0, 10.0));
force.addPointer(down);
drag.addPointer(down);
tester.closeArena(1);
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
expect(didStartPan, 0);
tester.route(pointer.move(const Offset(30.0, 30.0))); // moved 20 horizontally and 20 vertically which is 28 total
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
expect(didStartPan, 1);
// Pressure fed into the test environment simulates the values received directly from the device.
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 2.5, pressureMin: pressureMin, pressureMax: pressureMax));
// We have not hit the start pressure, so no events should be true.
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
expect(didStartPan, 1);
// We don't expect any events from the force press recognizer.
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 4.0, pressureMin: pressureMin, pressureMax: pressureMax));
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
expect(didStartPan, 1);
tester.route(pointer.up());
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
expect(didStartPan, 1);
});
testGesture('Should not call ended on pointer up if the gesture was never accepted', (GestureTester tester) {
final PanGestureRecognizer drag = PanGestureRecognizer();
addTearDown(drag.dispose);
// Device specific constants that represent those from the iPhone X
const double pressureMin = 0;
const double pressureMax = 6.66;
int started = 0;
int peaked = 0;
int updated = 0;
int ended = 0;
final ForcePressGestureRecognizer force = ForcePressGestureRecognizer();
addTearDown(force.dispose);
force.onStart = (_) => started += 1;
force.onPeak = (_) => peaked += 1;
force.onUpdate = (_) => updated += 1;
force.onEnd = (_) => ended += 1;
int didStartPan = 0;
drag.onStart = (_) => didStartPan += 1;
const int pointerValue = 1;
final TestPointer pointer = TestPointer();
const PointerDownEvent down = PointerDownEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressureMin: pressureMin, pressureMax: pressureMax);
pointer.setDownInfo(down, const Offset(10.0, 10.0));
force.addPointer(down);
drag.addPointer(down);
tester.closeArena(1);
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
expect(didStartPan, 0);
tester.route(pointer.up());
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
expect(didStartPan, 0);
});
testGesture('Should call start only once if there is a competing gesture recognizer', (GestureTester tester) {
final PanGestureRecognizer drag = PanGestureRecognizer();
addTearDown(drag.dispose);
// Device specific constants that represent those from the iPhone X
const double pressureMin = 0;
const double pressureMax = 6.66;
int started = 0;
int peaked = 0;
int updated = 0;
int ended = 0;
final ForcePressGestureRecognizer force = ForcePressGestureRecognizer();
addTearDown(force.dispose);
force.onStart = (_) => started += 1;
force.onPeak = (_) => peaked += 1;
force.onUpdate = (_) => updated += 1;
force.onEnd = (_) => ended += 1;
int didStartPan = 0;
drag.onStart = (_) => didStartPan += 1;
const int pointerValue = 1;
final TestPointer pointer = TestPointer();
const PointerDownEvent down = PointerDownEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressureMin: pressureMin, pressureMax: pressureMax);
pointer.setDownInfo(down, const Offset(10.0, 10.0));
force.addPointer(down);
drag.addPointer(down);
tester.closeArena(1);
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
expect(didStartPan, 0);
// Pressure fed into the test environment simulates the values received directly from the device.
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 3.0, pressureMin: pressureMin, pressureMax: pressureMax));
// We have not hit the start pressure, so no events should be true.
expect(started, 1);
expect(peaked, 0);
expect(updated, 1);
expect(ended, 0);
expect(didStartPan, 0);
tester.route(pointer.up());
expect(started, 1);
expect(peaked, 0);
expect(updated, 1);
expect(ended, 1);
expect(didStartPan, 0);
});
testGesture('A force press can be recognized with a custom interpolation function', (GestureTester tester) {
// Device specific constants that represent those from the iPhone X
const double pressureMin = 0;
const double pressureMax = 6.66;
int started = 0;
int peaked = 0;
int updated = 0;
int ended = 0;
Offset? startGlobalPosition;
void onStart(ForcePressDetails details) {
startGlobalPosition = details.globalPosition;
started += 1;
}
double interpolateWithEasing(double min, double max, double t) {
final double lerp = (t - min) / (max - min);
return Curves.easeIn.transform(lerp);
}
final ForcePressGestureRecognizer force = ForcePressGestureRecognizer(interpolation: interpolateWithEasing);
addTearDown(force.dispose);
force.onStart = onStart;
force.onPeak = (ForcePressDetails details) => peaked += 1;
force.onUpdate = (ForcePressDetails details) => updated += 1;
force.onEnd = (ForcePressDetails details) => ended += 1;
const int pointerValue = 1;
final TestPointer pointer = TestPointer();
const PointerDownEvent down = PointerDownEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 0, pressureMin: pressureMin, pressureMax: pressureMax);
pointer.setDownInfo(down, const Offset(10.0, 10.0));
force.addPointer(down);
tester.closeArena(pointerValue);
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
// Pressure fed into the test environment simulates the values received directly from the device.
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 2.5, pressureMin: pressureMin, pressureMax: pressureMax));
// We have not hit the start pressure, so no events should be true.
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 2.8, pressureMin: pressureMin, pressureMax: pressureMax));
// We have just hit the start pressure so just the start event should be triggered and one update call should have occurred.
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 3.3, pressureMin: pressureMin, pressureMax: pressureMax));
expect(started, 0);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 4.0, pressureMin: pressureMin, pressureMax: pressureMax));
expect(started, 1);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 5.0, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressureMin: pressureMin, pressureMax: pressureMax));
// We have exceeded the start pressure so update should be greater than 0.
expect(started, 1);
expect(updated, 3);
expect(peaked, 0);
expect(ended, 0);
expect(startGlobalPosition, const Offset(10.0, 10.0));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 6.0, pressureMin: pressureMin, pressureMax: pressureMax));
// We have exceeded the peak pressure so peak pressure should be true.
expect(started, 1);
expect(updated, 4);
expect(peaked, 0);
expect(ended, 0);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 3.3, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 4.0, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 6.5, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressureMin: pressureMin, pressureMax: pressureMax));
// Update is still called.
expect(started, 1);
expect(updated, 8);
expect(peaked, 1);
expect(ended, 0);
tester.route(pointer.up());
// We have ended the gesture so ended should be true.
expect(started, 1);
expect(updated, 8);
expect(peaked, 1);
expect(ended, 1);
});
testGesture('A pressure outside of the device reported min and max pressure will not give an error', (GestureTester tester) {
// Device specific constants that represent those from the iPhone X
const double pressureMin = 0;
const double pressureMax = 6.66;
int started = 0;
int peaked = 0;
int updated = 0;
int ended = 0;
final ForcePressGestureRecognizer force = ForcePressGestureRecognizer();
addTearDown(force.dispose);
force.onStart = (_) => started += 1;
force.onPeak = (_) => peaked += 1;
force.onUpdate = (_) => updated += 1;
force.onEnd = (_) => ended += 1;
const int pointerValue = 1;
final TestPointer pointer = TestPointer();
const PointerDownEvent down = PointerDownEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 0, pressureMin: pressureMin, pressureMax: pressureMax);
pointer.setDownInfo(down, const Offset(10.0, 10.0));
force.addPointer(down);
tester.closeArena(1);
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
// Pressure fed into the test environment simulates the values received directly from the device.
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 2.5, pressureMin: pressureMin, pressureMax: pressureMax));
// We have not hit the start pressure, so no events should be true.
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
// If the case where the pressure is greater than the max pressure were not handled correctly, this move event would throw an error.
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 8.0, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(pointer.up());
expect(started, 1);
expect(peaked, 1);
expect(updated, 1);
expect(ended, 1);
});
testGesture('A pressure of NAN will not give an error', (GestureTester tester) {
// Device specific constants that represent those from the iPhone X
const double pressureMin = 0;
const double pressureMax = 6.66;
int started = 0;
int peaked = 0;
int updated = 0;
int ended = 0;
final ForcePressGestureRecognizer force = ForcePressGestureRecognizer();
addTearDown(force.dispose);
force.onStart = (_) => started += 1;
force.onPeak = (_) => peaked += 1;
force.onUpdate = (_) => updated += 1;
force.onEnd = (_) => ended += 1;
const int pointerValue = 1;
final TestPointer pointer = TestPointer();
const PointerDownEvent down = PointerDownEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 0, pressureMin: pressureMin, pressureMax: pressureMax);
pointer.setDownInfo(down, const Offset(10.0, 10.0));
force.addPointer(down);
tester.closeArena(1);
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
// Pressure fed into the test environment simulates the values received directly from the device.
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 2.5, pressureMin: pressureMin, pressureMax: pressureMax));
// We have not hit the start pressure, so no events should be true.
expect(started, 0);
expect(peaked, 0);
expect(updated, 0);
expect(ended, 0);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 6.0, pressureMin: pressureMin, pressureMax: pressureMax));
expect(peaked, 1);
tester.route(const PointerMoveEvent(pointer: pointerValue, position: Offset(10.0, 10.0), pressure: 0.0 / 0.0, pressureMin: pressureMin, pressureMax: pressureMax));
tester.route(pointer.up());
expect(started, 1);
expect(peaked, 1);
expect(updated, 1);
expect(ended, 1);
});
}
| flutter/packages/flutter/test/gestures/force_press_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/force_press_test.dart",
"repo_id": "flutter",
"token_count": 7708
} | 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/gestures.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
PointerEvent createSimulatedPointerAddedEvent(
int timeStampUs,
double x,
double y,
) {
return PointerAddedEvent(
timeStamp: Duration(microseconds: timeStampUs),
position: Offset(x, y),
);
}
PointerEvent createSimulatedPointerRemovedEvent(
int timeStampUs,
double x,
double y,
) {
return PointerRemovedEvent(
timeStamp: Duration(microseconds: timeStampUs),
position: Offset(x, y),
);
}
PointerEvent createSimulatedPointerDownEvent(
int timeStampUs,
double x,
double y,
) {
return PointerDownEvent(
timeStamp: Duration(microseconds: timeStampUs),
position: Offset(x, y),
);
}
PointerEvent createSimulatedPointerMoveEvent(
int timeStampUs,
double x,
double y,
double deltaX,
double deltaY,
) {
return PointerMoveEvent(
timeStamp: Duration(microseconds: timeStampUs),
position: Offset(x, y),
delta: Offset(deltaX, deltaY),
);
}
PointerEvent createSimulatedPointerHoverEvent(
int timeStampUs,
double x,
double y,
double deltaX,
double deltaY,
) {
return PointerHoverEvent(
timeStamp: Duration(microseconds: timeStampUs),
position: Offset(x, y),
delta: Offset(deltaX, deltaY),
);
}
PointerEvent createSimulatedPointerUpEvent(
int timeStampUs,
double x,
double y,
) {
return PointerUpEvent(
timeStamp: Duration(microseconds: timeStampUs),
position: Offset(x, y),
);
}
test('basic', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 50.0);
final PointerEvent event1 = createSimulatedPointerHoverEvent(2000, 10.0, 40.0, 10.0, -10.0);
final PointerEvent event2 = createSimulatedPointerDownEvent(2000, 10.0, 40.0);
final PointerEvent event3 = createSimulatedPointerMoveEvent(3000, 20.0, 30.0, 10.0, -10.0);
final PointerEvent event4 = createSimulatedPointerMoveEvent(4000, 30.0, 20.0, 10.0, -10.0);
final PointerEvent event5 = createSimulatedPointerUpEvent(4000, 30.0, 20.0);
final PointerEvent event6 = createSimulatedPointerHoverEvent(5000, 40.0, 10.0, 10.0, -10.0);
final PointerEvent event7 = createSimulatedPointerHoverEvent(6000, 50.0, 0.0, 10.0, -10.0);
final PointerEvent event8 = createSimulatedPointerRemovedEvent(6000, 50.0, 0.0);
resampler
..addEvent(event0)
..addEvent(event1)
..addEvent(event2)
..addEvent(event3)
..addEvent(event4)
..addEvent(event5)
..addEvent(event6)
..addEvent(event7)
..addEvent(event8);
final List<PointerEvent> result = <PointerEvent>[];
resampler.sample(const Duration(microseconds: 500), Duration.zero, result.add);
// No pointer event should have been returned yet.
expect(result.isEmpty, true);
resampler.sample(const Duration(microseconds: 1500), Duration.zero, result.add);
// Add pointer event should have been returned.
expect(result.length, 1);
expect(result[0].timeStamp, const Duration(microseconds: 1500));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 5.0);
expect(result[0].position.dy, 45.0);
resampler.sample(const Duration(microseconds: 2500), Duration.zero, result.add);
// Hover and down pointer events should have been returned.
expect(result.length, 3);
expect(result[1].timeStamp, const Duration(microseconds: 2500));
expect(result[1] is PointerHoverEvent, true);
expect(result[1].position.dx, 15.0);
expect(result[1].position.dy, 35.0);
expect(result[1].delta.dx, 10.0);
expect(result[1].delta.dy, -10.0);
expect(result[2].timeStamp, const Duration(microseconds: 2500));
expect(result[2] is PointerDownEvent, true);
expect(result[2].position.dx, 15.0);
expect(result[2].position.dy, 35.0);
resampler.sample(const Duration(microseconds: 3500), Duration.zero, result.add);
// Move pointer event should have been returned.
expect(result.length, 4);
expect(result[3].timeStamp, const Duration(microseconds: 3500));
expect(result[3] is PointerMoveEvent, true);
expect(result[3].position.dx, 25.0);
expect(result[3].position.dy, 25.0);
expect(result[3].delta.dx, 10.0);
expect(result[3].delta.dy, -10.0);
resampler.sample(const Duration(microseconds: 4500), Duration.zero, result.add);
// Move and up pointer events should have been returned.
expect(result.length, 6);
expect(result[4].timeStamp, const Duration(microseconds: 4500));
expect(result[4] is PointerMoveEvent, true);
expect(result[4].position.dx, 35.0);
expect(result[4].position.dy, 15.0);
expect(result[4].delta.dx, 10.0);
expect(result[4].delta.dy, -10.0);
// buttons field needs to be a valid value
expect(result[4].buttons, kPrimaryButton);
expect(result[5].timeStamp, const Duration(microseconds: 4500));
expect(result[5] is PointerUpEvent, true);
expect(result[5].position.dx, 35.0);
expect(result[5].position.dy, 15.0);
resampler.sample(const Duration(microseconds: 5500), Duration.zero, result.add);
// Hover pointer event should have been returned.
expect(result.length, 7);
expect(result[6].timeStamp, const Duration(microseconds: 5500));
expect(result[6] is PointerHoverEvent, true);
expect(result[6].position.dx, 45.0);
expect(result[6].position.dy, 5.0);
expect(result[6].delta.dx, 10.0);
expect(result[6].delta.dy, -10.0);
resampler.sample(const Duration(microseconds: 6500), Duration.zero, result.add);
// Hover and removed pointer events should have been returned.
expect(result.length, 9);
expect(result[7].timeStamp, const Duration(microseconds: 6500));
expect(result[7] is PointerHoverEvent, true);
expect(result[7].position.dx, 50.0);
expect(result[7].position.dy, 0.0);
expect(result[7].delta.dx, 5.0);
expect(result[7].delta.dy, -5.0);
expect(result[8].timeStamp, const Duration(microseconds: 6500));
expect(result[8] is PointerRemovedEvent, true);
expect(result[8].position.dx, 50.0);
expect(result[8].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 7500), Duration.zero, result.add);
// No pointer event should have been returned.
expect(result.length, 9);
});
test('stream', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 50.0);
final PointerEvent event1 = createSimulatedPointerHoverEvent(2000, 10.0, 40.0, 10.0, -10.0);
final PointerEvent event2 = createSimulatedPointerDownEvent(2000, 10.0, 40.0);
final PointerEvent event3 = createSimulatedPointerMoveEvent(3000, 20.0, 30.0, 10.0, -10.0);
final PointerEvent event4 = createSimulatedPointerMoveEvent(4000, 30.0, 20.0, 10.0, -10.0);
final PointerEvent event5 = createSimulatedPointerUpEvent(4000, 30.0, 20.0);
final PointerEvent event6 = createSimulatedPointerHoverEvent(5000, 40.0, 10.0, 10.0, -10.0);
final PointerEvent event7 = createSimulatedPointerHoverEvent(6000, 50.0, 0.0, 10.0, -10.0);
final PointerEvent event8 = createSimulatedPointerRemovedEvent(6000, 50.0, 0.0);
resampler.addEvent(event0);
//
// Initial sample time a 0.5 ms.
//
final List<PointerEvent> result = <PointerEvent>[];
resampler.sample(const Duration(microseconds: 500), Duration.zero, result.add);
// No pointer event should have been returned yet.
expect(result.isEmpty, true);
resampler
..addEvent(event1)
..addEvent(event2);
resampler.sample(const Duration(microseconds: 500), Duration.zero, result.add);
// No pointer event should have been returned yet.
expect(result.isEmpty, true);
//
// Advance sample time to 1.5 ms.
//
resampler.sample(const Duration(microseconds: 1500), Duration.zero, result.add);
// Added pointer event should have been returned.
expect(result.length, 1);
expect(result[0].timeStamp, const Duration(microseconds: 1500));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 5.0);
expect(result[0].position.dy, 45.0);
resampler.addEvent(event3);
resampler.sample(const Duration(microseconds: 1500), Duration.zero, result.add);
// No more pointer events should have been returned.
expect(result.length, 1);
//
// Advance sample time to 2.5 ms.
//
resampler.sample(const Duration(microseconds: 2500), Duration.zero, result.add);
// Hover and down pointer events should have been returned.
expect(result.length, 3);
expect(result[1].timeStamp, const Duration(microseconds: 2500));
expect(result[1] is PointerHoverEvent, true);
expect(result[1].position.dx, 15.0);
expect(result[1].position.dy, 35.0);
expect(result[1].delta.dx, 10.0);
expect(result[1].delta.dy, -10.0);
expect(result[2].timeStamp, const Duration(microseconds: 2500));
expect(result[2] is PointerDownEvent, true);
expect(result[2].position.dx, 15.0);
expect(result[2].position.dy, 35.0);
resampler
..addEvent(event4)
..addEvent(event5);
resampler.sample(const Duration(microseconds: 2500), Duration.zero, result.add);
// No more pointer events should have been returned.
expect(result.length, 3);
//
// Advance sample time to 3.5 ms.
//
resampler.sample(const Duration(microseconds: 3500), Duration.zero, result.add);
// Move pointer event should have been returned.
expect(result.length, 4);
expect(result[3].timeStamp, const Duration(microseconds: 3500));
expect(result[3] is PointerMoveEvent, true);
expect(result[3].position.dx, 25.0);
expect(result[3].position.dy, 25.0);
expect(result[3].delta.dx, 10.0);
expect(result[3].delta.dy, -10.0);
resampler.addEvent(event6);
resampler.sample(const Duration(microseconds: 3500), Duration.zero, result.add);
// No more pointer events should have been returned.
expect(result.length, 4);
//
// Advance sample time to 4.5 ms.
//
resampler.sample(const Duration(microseconds: 4500), Duration.zero, result.add);
// Move and up pointer events should have been returned.
expect(result.length, 6);
expect(result[4].timeStamp, const Duration(microseconds: 4500));
expect(result[4] is PointerMoveEvent, true);
expect(result[4].position.dx, 35.0);
expect(result[4].position.dy, 15.0);
expect(result[4].delta.dx, 10.0);
expect(result[4].delta.dy, -10.0);
expect(result[5].timeStamp, const Duration(microseconds: 4500));
expect(result[5] is PointerUpEvent, true);
expect(result[5].position.dx, 35.0);
expect(result[5].position.dy, 15.0);
resampler
..addEvent(event7)
..addEvent(event8);
resampler.sample(const Duration(microseconds: 4500), Duration.zero, result.add);
// No more pointer events should have been returned.
expect(result.length, 6);
//
// Advance sample time to 5.5 ms.
//
resampler.sample(const Duration(microseconds: 5500), Duration.zero, result.add);
// Hover pointer event should have been returned.
expect(result.length, 7);
expect(result[6].timeStamp, const Duration(microseconds: 5500));
expect(result[6] is PointerHoverEvent, true);
expect(result[6].position.dx, 45.0);
expect(result[6].position.dy, 5.0);
expect(result[6].delta.dx, 10.0);
expect(result[6].delta.dy, -10.0);
//
// Advance sample time to 6.5 ms.
//
resampler.sample(const Duration(microseconds: 6500), Duration.zero, result.add);
// Hover and removed pointer event should have been returned.
expect(result.length, 9);
expect(result[7].timeStamp, const Duration(microseconds: 6500));
expect(result[7] is PointerHoverEvent, true);
expect(result[7].position.dx, 50.0);
expect(result[7].position.dy, 0.0);
expect(result[7].delta.dx, 5.0);
expect(result[7].delta.dy, -5.0);
expect(result[8].timeStamp, const Duration(microseconds: 6500));
expect(result[8] is PointerRemovedEvent, true);
expect(result[8].position.dx, 50.0);
expect(result[8].position.dy, 0.0);
//
// Advance sample time to 7.5 ms.
//
resampler.sample(const Duration(microseconds: 7500), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.length, 9);
});
test('quick tap', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 0.0);
final PointerEvent event1 = createSimulatedPointerDownEvent(1000, 0.0, 0.0);
final PointerEvent event2 = createSimulatedPointerUpEvent(1000, 0.0, 0.0);
final PointerEvent event3 = createSimulatedPointerRemovedEvent(1000, 0.0, 0.0);
resampler
..addEvent(event0)
..addEvent(event1)
..addEvent(event2)
..addEvent(event3);
final List<PointerEvent> result = <PointerEvent>[];
resampler.sample(const Duration(microseconds: 1500), Duration.zero, result.add);
// All pointer events should have been returned.
expect(result.length, 4);
expect(result[0].timeStamp, const Duration(microseconds: 1500));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 0.0);
expect(result[0].position.dy, 0.0);
expect(result[1].timeStamp, const Duration(microseconds: 1500));
expect(result[1] is PointerDownEvent, true);
expect(result[1].position.dx, 0.0);
expect(result[1].position.dy, 0.0);
expect(result[2].timeStamp, const Duration(microseconds: 1500));
expect(result[2] is PointerUpEvent, true);
expect(result[2].position.dx, 0.0);
expect(result[2].position.dy, 0.0);
expect(result[3].timeStamp, const Duration(microseconds: 1500));
expect(result[3] is PointerRemovedEvent, true);
expect(result[3].position.dx, 0.0);
expect(result[3].position.dy, 0.0);
});
test('advance slowly', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 0.0);
final PointerEvent event1 = createSimulatedPointerDownEvent(1000, 0.0, 0.0);
final PointerEvent event2 = createSimulatedPointerMoveEvent(2000, 10.0, 0.0, 10.0, 0.0);
final PointerEvent event3 = createSimulatedPointerMoveEvent(3000, 20.0, 0.0, 10.0, 0.0);
final PointerEvent event4 = createSimulatedPointerUpEvent(3000, 20.0, 0.0);
final PointerEvent event5 = createSimulatedPointerRemovedEvent(3000, 20.0, 0.0);
resampler
..addEvent(event0)
..addEvent(event1)
..addEvent(event2)
..addEvent(event3)
..addEvent(event4)
..addEvent(event5);
final List<PointerEvent> result = <PointerEvent>[];
resampler.sample(const Duration(microseconds: 1500), Duration.zero, result.add);
// Added and down pointer events should have been returned.
expect(result.length, 2);
expect(result[0].timeStamp, const Duration(microseconds: 1500));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 5.0);
expect(result[0].position.dy, 0.0);
expect(result[1].timeStamp, const Duration(microseconds: 1500));
expect(result[1] is PointerDownEvent, true);
expect(result[1].position.dx, 5.0);
expect(result[1].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 1500), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.length, 2);
resampler.sample(const Duration(microseconds: 1750), Duration.zero, result.add);
// Move pointer event should have been returned.
expect(result.length, 3);
expect(result[2].timeStamp, const Duration(microseconds: 1750));
expect(result[2] is PointerMoveEvent, true);
expect(result[2].position.dx, 7.5);
expect(result[2].position.dy, 0.0);
expect(result[2].delta.dx, 2.5);
expect(result[2].delta.dy, 0.0);
resampler.sample(const Duration(microseconds: 2000), Duration.zero, result.add);
// Another move pointer event should have been returned.
expect(result.length, 4);
expect(result[3].timeStamp, const Duration(microseconds: 2000));
expect(result[3] is PointerMoveEvent, true);
expect(result[3].position.dx, 10.0);
expect(result[3].position.dy, 0.0);
expect(result[3].delta.dx, 2.5);
expect(result[3].delta.dy, 0.0);
resampler.sample(const Duration(microseconds: 3000), Duration.zero, result.add);
// Move, up and removed pointer events should have been returned.
expect(result.length, 7);
expect(result[4].timeStamp, const Duration(microseconds: 3000));
expect(result[4] is PointerMoveEvent, true);
expect(result[4].position.dx, 20.0);
expect(result[4].position.dy, 0.0);
expect(result[4].delta.dx, 10.0);
expect(result[4].delta.dy, 0.0);
expect(result[5].timeStamp, const Duration(microseconds: 3000));
expect(result[5] is PointerUpEvent, true);
expect(result[5].position.dx, 20.0);
expect(result[5].position.dy, 0.0);
expect(result[6].timeStamp, const Duration(microseconds: 3000));
expect(result[6] is PointerRemovedEvent, true);
expect(result[6].position.dx, 20.0);
expect(result[6].position.dy, 0.0);
});
test('advance fast', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 0.0);
final PointerEvent event1 = createSimulatedPointerDownEvent(1000, 0.0, 0.0);
final PointerEvent event2 = createSimulatedPointerMoveEvent(2000, 5.0, 0.0, 5.0, 0.0);
final PointerEvent event3 = createSimulatedPointerMoveEvent(3000, 20.0, 0.0, 15.0, 0.0);
final PointerEvent event4 = createSimulatedPointerUpEvent(4000, 30.0, 0.0);
final PointerEvent event5 = createSimulatedPointerRemovedEvent(4000, 30.0, 0.0);
resampler
..addEvent(event0)
..addEvent(event1)
..addEvent(event2)
..addEvent(event3)
..addEvent(event4)
..addEvent(event5);
final List<PointerEvent> result = <PointerEvent>[];
resampler.sample(const Duration(microseconds: 2500), Duration.zero, result.add);
// Added and down pointer events should have been returned.
expect(result.length, 2);
expect(result[0].timeStamp, const Duration(microseconds: 2500));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 12.5);
expect(result[0].position.dy, 0.0);
expect(result[1].timeStamp, const Duration(microseconds: 2500));
expect(result[1] is PointerDownEvent, true);
expect(result[1].position.dx, 12.5);
expect(result[1].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 5500), Duration.zero, result.add);
// Move, up and removed pointer events should have been returned.
expect(result.length, 5);
expect(result[2].timeStamp, const Duration(microseconds: 5500));
expect(result[2] is PointerMoveEvent, true);
expect(result[2].position.dx, 30.0);
expect(result[2].position.dy, 0.0);
expect(result[2].delta.dx, 17.5);
expect(result[2].delta.dy, 0.0);
expect(result[3].timeStamp, const Duration(microseconds: 5500));
expect(result[3] is PointerUpEvent, true);
expect(result[3].position.dx, 30.0);
expect(result[3].position.dy, 0.0);
expect(result[4].timeStamp, const Duration(microseconds: 5500));
expect(result[4] is PointerRemovedEvent, true);
expect(result[4].position.dx, 30.0);
expect(result[4].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 6500), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.length, 5);
});
test('skip', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 0.0);
final PointerEvent event1 = createSimulatedPointerDownEvent(1000, 0.0, 0.0);
final PointerEvent event2 = createSimulatedPointerMoveEvent(2000, 10.0, 0.0, 10.0, 0.0);
final PointerEvent event3 = createSimulatedPointerUpEvent(3000, 10.0, 0.0);
final PointerEvent event4 = createSimulatedPointerHoverEvent(4000, 20.0, 0.0, 10.0, 0.0);
final PointerEvent event5 = createSimulatedPointerDownEvent(4000, 20.0, 0.0);
final PointerEvent event6 = createSimulatedPointerMoveEvent(5000, 30.0, 0.0, 10.0, 0.0);
final PointerEvent event7 = createSimulatedPointerUpEvent(5000, 30.0, 0.0);
final PointerEvent event8 = createSimulatedPointerRemovedEvent(5000, 30.0, 0.0);
resampler
..addEvent(event0)
..addEvent(event1)
..addEvent(event2)
..addEvent(event3)
..addEvent(event4)
..addEvent(event5)
..addEvent(event6)
..addEvent(event7)
..addEvent(event8);
final List<PointerEvent> result = <PointerEvent>[];
resampler.sample(const Duration(microseconds: 1500), Duration.zero, result.add);
// Added and down pointer events should have been returned.
expect(result.length, 2);
expect(result[0].timeStamp, const Duration(microseconds: 1500));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 5.0);
expect(result[0].position.dy, 0.0);
expect(result[1].timeStamp, const Duration(microseconds: 1500));
expect(result[1] is PointerDownEvent, true);
expect(result[1].position.dx, 5.0);
expect(result[1].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 5500), Duration.zero, result.add);
// All remaining pointer events should have been returned.
expect(result.length, 7);
expect(result[2].timeStamp, const Duration(microseconds: 5500));
expect(result[2] is PointerMoveEvent, true);
expect(result[2].position.dx, 30.0);
expect(result[2].position.dy, 0.0);
expect(result[2].delta.dx, 25.0);
expect(result[2].delta.dy, 0.0);
expect(result[3].timeStamp, const Duration(microseconds: 5500));
expect(result[3] is PointerUpEvent, true);
expect(result[3].position.dx, 30.0);
expect(result[3].position.dy, 0.0);
expect(result[4].timeStamp, const Duration(microseconds: 5500));
expect(result[4] is PointerDownEvent, true);
expect(result[4].position.dx, 30.0);
expect(result[4].position.dy, 0.0);
expect(result[5].timeStamp, const Duration(microseconds: 5500));
expect(result[5] is PointerUpEvent, true);
expect(result[5].position.dx, 30.0);
expect(result[5].position.dy, 0.0);
expect(result[6].timeStamp, const Duration(microseconds: 5500));
expect(result[6] is PointerRemovedEvent, true);
expect(result[6].position.dx, 30.0);
expect(result[6].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 6500), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.length, 7);
});
test('skip all', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 0.0);
final PointerEvent event1 = createSimulatedPointerDownEvent(1000, 0.0, 0.0);
final PointerEvent event2 = createSimulatedPointerMoveEvent(4000, 30.0, 0.0, 30.0, 0.0);
final PointerEvent event3 = createSimulatedPointerUpEvent(4000, 30.0, 0.0);
final PointerEvent event4 = createSimulatedPointerRemovedEvent(4000, 30.0, 0.0);
resampler
..addEvent(event0)
..addEvent(event1)
..addEvent(event2)
..addEvent(event3)
..addEvent(event4);
final List<PointerEvent> result = <PointerEvent>[];
resampler.sample(const Duration(microseconds: 500), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.isEmpty, true);
resampler.sample(const Duration(microseconds: 5500), Duration.zero, result.add);
// All remaining pointer events should have been returned.
expect(result.length, 4);
expect(result[0].timeStamp, const Duration(microseconds: 5500));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 30.0);
expect(result[0].position.dy, 0.0);
expect(result[1].timeStamp, const Duration(microseconds: 5500));
expect(result[1] is PointerDownEvent, true);
expect(result[1].position.dx, 30.0);
expect(result[1].position.dy, 0.0);
expect(result[2].timeStamp, const Duration(microseconds: 5500));
expect(result[2] is PointerUpEvent, true);
expect(result[2].position.dx, 30.0);
expect(result[2].position.dy, 0.0);
expect(result[3].timeStamp, const Duration(microseconds: 5500));
expect(result[3] is PointerRemovedEvent, true);
expect(result[3].position.dx, 30.0);
expect(result[3].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 6500), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.length, 4);
});
test('stop', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 0.0);
final PointerEvent event1 = createSimulatedPointerDownEvent(2000, 0.0, 0.0);
final PointerEvent event2 = createSimulatedPointerMoveEvent(3000, 10.0, 0.0, 10.0, 0.0);
final PointerEvent event3 = createSimulatedPointerMoveEvent(4000, 20.0, 0.0, 10.0, 0.0);
final PointerEvent event4 = createSimulatedPointerUpEvent(4000, 20.0, 0.0);
final PointerEvent event5 = createSimulatedPointerRemovedEvent(5000, 20.0, 0.0);
resampler
..addEvent(event0)
..addEvent(event1)
..addEvent(event2)
..addEvent(event3)
..addEvent(event4)
..addEvent(event5);
final List<PointerEvent> result = <PointerEvent>[];
resampler.sample(const Duration(microseconds: 500), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.isEmpty, true);
resampler.stop(result.add);
// All pointer events should have been returned with original
// time stamps and positions.
expect(result.length, 6);
expect(result[0].timeStamp, const Duration(microseconds: 1000));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 0.0);
expect(result[0].position.dy, 0.0);
expect(result[1].timeStamp, const Duration(microseconds: 2000));
expect(result[1] is PointerDownEvent, true);
expect(result[1].position.dx, 0.0);
expect(result[1].position.dy, 0.0);
expect(result[2].timeStamp, const Duration(microseconds: 3000));
expect(result[2] is PointerMoveEvent, true);
expect(result[2].position.dx, 10.0);
expect(result[2].position.dy, 0.0);
expect(result[2].delta.dx, 10.0);
expect(result[2].delta.dy, 0.0);
expect(result[3].timeStamp, const Duration(microseconds: 4000));
expect(result[3] is PointerMoveEvent, true);
expect(result[3].position.dx, 20.0);
expect(result[3].position.dy, 0.0);
expect(result[3].delta.dx, 10.0);
expect(result[3].delta.dy, 0.0);
expect(result[4].timeStamp, const Duration(microseconds: 4000));
expect(result[4] is PointerUpEvent, true);
expect(result[4].position.dx, 20.0);
expect(result[4].position.dy, 0.0);
expect(result[5].timeStamp, const Duration(microseconds: 5000));
expect(result[5] is PointerRemovedEvent, true);
expect(result[5].position.dx, 20.0);
expect(result[5].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 10000), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.length, 6);
});
test('synthetic move', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 0.0);
final PointerEvent event1 = createSimulatedPointerDownEvent(2000, 0.0, 0.0);
final PointerEvent event2 = createSimulatedPointerMoveEvent(3000, 10.0, 0.0, 10.0, 0.0);
final PointerEvent event3 = createSimulatedPointerUpEvent(4000, 10.0, 0.0);
final PointerEvent event4 = createSimulatedPointerRemovedEvent(5000, 10.0, 0.0);
resampler
..addEvent(event0)
..addEvent(event1)
..addEvent(event2)
..addEvent(event3)
..addEvent(event4);
final List<PointerEvent> result = <PointerEvent>[];
resampler.sample(const Duration(microseconds: 500), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.isEmpty, true);
resampler.sample(const Duration(microseconds: 2000), Duration.zero, result.add);
// Added and down pointer events should have been returned.
expect(result.length, 2);
expect(result[0].timeStamp, const Duration(microseconds: 2000));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 0.0);
expect(result[0].position.dy, 0.0);
expect(result[1].timeStamp, const Duration(microseconds: 2000));
expect(result[1] is PointerDownEvent, true);
expect(result[1].position.dx, 0.0);
expect(result[1].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 5000), Duration.zero, result.add);
// All remaining pointer events and a synthetic move event should
// have been returned.
expect(result.length, 5);
expect(result[2].timeStamp, const Duration(microseconds: 5000));
expect(result[2] is PointerMoveEvent, true);
expect(result[2].position.dx, 10.0);
expect(result[2].position.dy, 0.0);
expect(result[2].delta.dx, 10.0);
expect(result[2].delta.dy, 0.0);
expect(result[3].timeStamp, const Duration(microseconds: 5000));
expect(result[3] is PointerUpEvent, true);
expect(result[3].position.dx, 10.0);
expect(result[3].position.dy, 0.0);
expect(result[4].timeStamp, const Duration(microseconds: 5000));
expect(result[4] is PointerRemovedEvent, true);
expect(result[4].position.dx, 10.0);
expect(result[4].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 10000), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.length, 5);
});
test('next sample time', () {
final PointerEventResampler resampler = PointerEventResampler();
final PointerEvent event0 = createSimulatedPointerAddedEvent(1000, 0.0, 0.0);
final PointerEvent event1 = createSimulatedPointerDownEvent(1000, 0.0, 0.0);
final PointerEvent event2 = createSimulatedPointerMoveEvent(2000, 10.0, 0.0, 10.0, 0.0);
final PointerEvent event3 = createSimulatedPointerMoveEvent(3000, 20.0, 0.0, 10.0, 0.0);
final PointerEvent event4 = createSimulatedPointerUpEvent(3000, 20.0, 0.0);
final PointerEvent event5 = createSimulatedPointerHoverEvent(4000, 30.0, 0.0, 10.0, 0.0);
final PointerEvent event6 = createSimulatedPointerRemovedEvent(4000, 30.0, 0.0);
resampler
..addEvent(event0)
..addEvent(event1)
..addEvent(event2)
..addEvent(event3)
..addEvent(event4)
..addEvent(event5)
..addEvent(event6);
final List<PointerEvent> result = <PointerEvent>[];
Duration sampleTime = const Duration(microseconds: 500);
Duration nextSampleTime = const Duration(microseconds: 1500);
resampler.sample(sampleTime, nextSampleTime, result.add);
// No pointer events should have been returned.
expect(result.isEmpty, true);
sampleTime = nextSampleTime;
nextSampleTime = const Duration(microseconds: 2500);
resampler.sample(sampleTime, nextSampleTime, result.add);
// Added and down pointer events should have been returned.
expect(result.length, 2);
expect(result[0].timeStamp, const Duration(microseconds: 1500));
expect(result[0] is PointerAddedEvent, true);
expect(result[0].position.dx, 5.0);
expect(result[0].position.dy, 0.0);
expect(result[1].timeStamp, const Duration(microseconds: 1500));
expect(result[1] is PointerDownEvent, true);
expect(result[1].position.dx, 5.0);
expect(result[1].position.dy, 0.0);
sampleTime = nextSampleTime;
nextSampleTime = const Duration(microseconds: 3500);
resampler.sample(sampleTime, nextSampleTime, result.add);
// Move and up pointer events should have been returned.
expect(result.length, 4);
expect(result[2].timeStamp, const Duration(microseconds: 2500));
expect(result[2] is PointerMoveEvent, true);
expect(result[2].position.dx, 15.0);
expect(result[2].position.dy, 0.0);
expect(result[2].delta.dx, 10.0);
expect(result[2].delta.dy, 0.0);
expect(result[3].timeStamp, const Duration(microseconds: 2500));
expect(result[3] is PointerUpEvent, true);
expect(result[3].position.dx, 15.0);
expect(result[3].position.dy, 0.0);
sampleTime = nextSampleTime;
nextSampleTime = const Duration(microseconds: 4500);
resampler.sample(sampleTime, nextSampleTime, result.add);
// All remaining pointer events should have been returned.
expect(result.length, 6);
expect(result[4].timeStamp, const Duration(microseconds: 3500));
expect(result[4] is PointerHoverEvent, true);
expect(result[4].position.dx, 25.0);
expect(result[4].position.dy, 0.0);
expect(result[4].delta.dx, 10.0);
expect(result[4].delta.dy, 0.0);
expect(result[5].timeStamp, const Duration(microseconds: 3500));
expect(result[5] is PointerRemovedEvent, true);
expect(result[5].position.dx, 25.0);
expect(result[5].position.dy, 0.0);
resampler.sample(const Duration(microseconds: 10000), Duration.zero, result.add);
// No pointer events should have been returned.
expect(result.length, 6);
});
}
| flutter/packages/flutter/test/gestures/resampler_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/resampler_test.dart",
"repo_id": "flutter",
"token_count": 12749
} | 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 'dart:async';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
tearDown(() {
LicenseRegistry.reset();
});
testWidgets('Material3 has sentence case labels', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true),
builder: (BuildContext context, Widget? child) {
return MediaQuery(
// Display has a vertical hinge down the middle
data: const MediaQueryData(
size: Size(800, 600),
displayFeatures: <DisplayFeature>[
DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
],
),
child: child!,
);
},
home: Builder(
builder: (BuildContext context) => ElevatedButton(
onPressed: () {
showAboutDialog(
context: context,
useRootNavigator: false,
applicationName: 'A',
);
},
child: const Text('Show About Dialog'),
),
),
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.text('Close'), findsOneWidget);
expect(find.text('View licenses'), findsOneWidget);
});
testWidgets('Material2 - AboutListTile control test', (WidgetTester tester) async {
const FlutterLogo logo = FlutterLogo();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
title: 'Pirate app',
home: Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
drawer: Drawer(
child: ListView(
children: const <Widget>[
AboutListTile(
applicationVersion: '0.1.2',
applicationIcon: logo,
applicationLegalese: 'I am the very model of a modern major general.',
aboutBoxChildren: <Widget>[
Text('About box'),
],
),
],
),
),
),
),
);
expect(find.text('About Pirate app'), findsNothing);
expect(find.text('0.1.2'), findsNothing);
expect(find.byWidget(logo), findsNothing);
expect(
find.text('I am the very model of a modern major general.'),
findsNothing,
);
expect(find.text('About box'), findsNothing);
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.text('About Pirate app'), findsOneWidget);
expect(find.text('0.1.2'), findsNothing);
expect(find.byWidget(logo), findsNothing);
expect(
find.text('I am the very model of a modern major general.'),
findsNothing,
);
expect(find.text('About box'), findsNothing);
await tester.tap(find.text('About Pirate app'));
await tester.pumpAndSettle();
expect(find.text('About Pirate app'), findsOneWidget);
expect(find.text('0.1.2'), findsOneWidget);
expect(find.byWidget(logo), findsOneWidget);
expect(
find.text('I am the very model of a modern major general.'),
findsOneWidget,
);
expect(find.text('About box'), findsOneWidget);
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['Pirate package '], 'Pirate license'),
]);
});
await tester.tap(find.text('VIEW LICENSES'));
await tester.pumpAndSettle();
expect(find.text('Pirate app'), findsOneWidget);
expect(find.text('0.1.2'), findsOneWidget);
expect(find.byWidget(logo), findsOneWidget);
expect(
find.text('I am the very model of a modern major general.'),
findsOneWidget,
);
await tester.tap(find.text('Pirate package '));
await tester.pumpAndSettle();
expect(find.text('Pirate license'), findsOneWidget);
});
testWidgets('Material3 - AboutListTile control test', (WidgetTester tester) async {
const FlutterLogo logo = FlutterLogo();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
title: 'Pirate app',
home: Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
drawer: Drawer(
child: ListView(
children: const <Widget>[
AboutListTile(
applicationVersion: '0.1.2',
applicationIcon: logo,
applicationLegalese: 'I am the very model of a modern major general.',
aboutBoxChildren: <Widget>[
Text('About box'),
],
),
],
),
),
),
),
);
expect(find.text('About Pirate app'), findsNothing);
expect(find.text('0.1.2'), findsNothing);
expect(find.byWidget(logo), findsNothing);
expect(
find.text('I am the very model of a modern major general.'),
findsNothing,
);
expect(find.text('About box'), findsNothing);
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(find.text('About Pirate app'), findsOneWidget);
expect(find.text('0.1.2'), findsNothing);
expect(find.byWidget(logo), findsNothing);
expect(
find.text('I am the very model of a modern major general.'),
findsNothing,
);
expect(find.text('About box'), findsNothing);
await tester.tap(find.text('About Pirate app'));
await tester.pumpAndSettle();
expect(find.text('About Pirate app'), findsOneWidget);
expect(find.text('0.1.2'), findsOneWidget);
expect(find.byWidget(logo), findsOneWidget);
expect(
find.text('I am the very model of a modern major general.'),
findsOneWidget,
);
expect(find.text('About box'), findsOneWidget);
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['Pirate package '], 'Pirate license'),
]);
});
await tester.tap(find.text('View licenses'));
await tester.pumpAndSettle();
expect(find.text('Pirate app'), findsOneWidget);
expect(find.text('0.1.2'), findsOneWidget);
expect(find.byWidget(logo), findsOneWidget);
expect(
find.text('I am the very model of a modern major general.'),
findsOneWidget,
);
await tester.tap(find.text('Pirate package '));
await tester.pumpAndSettle();
expect(find.text('Pirate license'), findsOneWidget);
});
testWidgets('About box logic defaults to executable name for app name', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
title: 'flutter_tester',
home: Material(child: AboutListTile()),
),
);
expect(find.text('About flutter_tester'), findsOneWidget);
});
testWidgets('LicensePage control test', (WidgetTester tester) async {
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['AAA'], 'BBB'),
]);
});
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(
<String>['Another package'],
'Another license',
),
]);
});
await tester.pumpWidget(
const MaterialApp(
home: Center(
child: LicensePage(),
),
),
);
expect(find.text('AAA'), findsNothing);
expect(find.text('BBB'), findsNothing);
expect(find.text('Another package'), findsNothing);
expect(find.text('Another license'), findsNothing);
await tester.pumpAndSettle();
// Check for packages.
expect(find.text('AAA'), findsOneWidget);
expect(find.text('Another package'), findsOneWidget);
// Check license is displayed after entering into license page for 'AAA'.
await tester.tap(find.text('AAA'));
await tester.pumpAndSettle();
expect(find.text('BBB'), findsOneWidget);
/// Go back to list of packages.
await tester.pageBack();
await tester.pumpAndSettle();
/// Check license is displayed after entering into license page for
/// 'Another package'.
await tester.tap(find.text('Another package'));
await tester.pumpAndSettle();
expect(find.text('Another license'), findsOneWidget);
});
testWidgets('LicensePage control test with all properties', (WidgetTester tester) async {
const FlutterLogo logo = FlutterLogo();
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['AAA'], 'BBB'),
]);
});
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(
<String>['Another package'],
'Another license',
),
]);
});
await tester.pumpWidget(
const MaterialApp(
title: 'Pirate app',
home: Center(
child: LicensePage(
applicationName: 'LicensePage test app',
applicationVersion: '0.1.2',
applicationIcon: logo,
applicationLegalese: 'I am the very model of a modern major general.',
),
),
),
);
expect(find.text('Pirate app'), findsNothing);
expect(find.text('LicensePage test app'), findsOneWidget);
expect(find.text('0.1.2'), findsOneWidget);
expect(find.byWidget(logo), findsOneWidget);
expect(
find.text('I am the very model of a modern major general.'),
findsOneWidget,
);
expect(find.text('AAA'), findsNothing);
expect(find.text('BBB'), findsNothing);
expect(find.text('Another package'), findsNothing);
expect(find.text('Another license'), findsNothing);
await tester.pumpAndSettle();
expect(find.text('Pirate app'), findsNothing);
expect(find.text('LicensePage test app'), findsOneWidget);
expect(find.text('0.1.2'), findsOneWidget);
expect(find.byWidget(logo), findsOneWidget);
expect(
find.text('I am the very model of a modern major general.'),
findsOneWidget,
);
// Check for packages.
expect(find.text('AAA'), findsOneWidget);
expect(find.text('Another package'), findsOneWidget);
// Check license is displayed after entering into license page for 'AAA'.
await tester.tap(find.text('AAA'));
await tester.pumpAndSettle();
expect(find.text('BBB'), findsOneWidget);
/// Go back to list of packages.
await tester.pageBack();
await tester.pumpAndSettle();
/// Check license is displayed after entering into license page for
/// 'Another package'.
await tester.tap(find.text('Another package'));
await tester.pumpAndSettle();
expect(find.text('Another license'), findsOneWidget);
});
testWidgets('Material2 - _PackageLicensePage title style without AppBarTheme', (WidgetTester tester) async {
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['AAA'], 'BBB'),
]);
});
const TextStyle titleTextStyle = TextStyle(
fontSize: 20,
color: Colors.black,
inherit: false,
);
const TextStyle subtitleTextStyle = TextStyle(
fontSize: 15,
color: Colors.red,
inherit: false,
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: false,
primaryTextTheme: const TextTheme(
titleLarge: titleTextStyle,
titleSmall: subtitleTextStyle,
),
),
home: const Center(
child: LicensePage(),
),
),
);
await tester.pumpAndSettle();
// Check for packages.
expect(find.text('AAA'), findsOneWidget);
// Check license is displayed after entering into license page for 'AAA'.
await tester.tap(find.text('AAA'));
await tester.pumpAndSettle();
// Check for titles style.
final Text title = tester.widget(find.text('AAA'));
expect(title.style, titleTextStyle);
final Text subtitle = tester.widget(find.text('1 license.'));
expect(subtitle.style, subtitleTextStyle);
});
testWidgets('Material3 - _PackageLicensePage title style without AppBarTheme', (WidgetTester tester) async {
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['AAA'], 'BBB'),
]);
});
const TextStyle titleTextStyle = TextStyle(
fontSize: 20,
color: Colors.black,
inherit: false,
);
const TextStyle subtitleTextStyle = TextStyle(
fontSize: 15,
color: Colors.red,
inherit: false,
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: true,
textTheme: const TextTheme(
titleLarge: titleTextStyle,
titleSmall: subtitleTextStyle,
),
),
home: const Center(
child: LicensePage(),
),
),
);
await tester.pumpAndSettle();
// Check for packages.
expect(find.text('AAA'), findsOneWidget);
// Check license is displayed after entering into license page for 'AAA'.
await tester.tap(find.text('AAA'));
await tester.pumpAndSettle();
// Check for titles style.
final Text title = tester.widget(find.text('AAA'));
expect(title.style, titleTextStyle);
final Text subtitle = tester.widget(find.text('1 license.'));
expect(subtitle.style, subtitleTextStyle);
});
testWidgets('_PackageLicensePage title style with AppBarTheme', (WidgetTester tester) async {
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['AAA'], 'BBB'),
]);
});
const TextStyle titleTextStyle = TextStyle(
fontSize: 20,
color: Colors.indigo,
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
// Not used because appBarTheme is prioritized.
primaryTextTheme: const TextTheme(
titleLarge: TextStyle(
fontSize: 12,
color: Colors.grey,
),
titleSmall: TextStyle(
fontSize: 10,
color: Colors.grey,
),
),
appBarTheme: const AppBarTheme(
titleTextStyle: titleTextStyle,
foregroundColor: Colors.indigo,
),
),
home: const Center(
child: LicensePage(),
),
),
);
await tester.pumpAndSettle();
// Check for packages.
expect(find.text('AAA'), findsOneWidget);
// Check license is displayed after entering into license page for 'AAA'.
await tester.tap(find.text('AAA'));
await tester.pumpAndSettle();
// Check for titles style.
final Text title = tester.widget(find.text('AAA'));
expect(title.style, titleTextStyle);
});
testWidgets('Material2 - LicensePage respects the notch', (WidgetTester tester) async {
const double safeareaPadding = 27.0;
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['ABC'], 'DEF'),
]);
});
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: const MediaQuery(
data: MediaQueryData(
padding: EdgeInsets.all(safeareaPadding),
),
child: LicensePage(),
),
),
);
await tester.pumpAndSettle();
// The position of the top left of app bar title should indicate whether
// the safe area is sufficiently respected.
expect(
tester.getTopLeft(find.text('Licenses')),
const Offset(16.0 + safeareaPadding, 18.0 + safeareaPadding),
);
});
testWidgets('Material3 - LicensePage respects the notch', (WidgetTester tester) async {
const double safeareaPadding = 27.0;
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['ABC'], 'DEF'),
]);
});
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const MediaQuery(
data: MediaQueryData(
padding: EdgeInsets.all(safeareaPadding),
),
child: LicensePage(),
),
),
);
await tester.pumpAndSettle();
// The position of the top left of app bar title should indicate whether
// the safe area is sufficiently respected.
expect(
tester.getTopLeft(find.text('Licenses')),
const Offset(16.0 + safeareaPadding, 14.0 + safeareaPadding),
);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('LicensePage returns early if unmounted', (WidgetTester tester) async {
final Completer<LicenseEntry> licenseCompleter = Completer<LicenseEntry>();
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromFuture(licenseCompleter.future);
});
await tester.pumpWidget(
const MaterialApp(
home: LicensePage(),
),
);
await tester.pump();
await tester.pumpWidget(
const MaterialApp(
home: Placeholder(),
),
);
await tester.pumpAndSettle();
final FakeLicenseEntry licenseEntry = FakeLicenseEntry();
licenseCompleter.complete(licenseEntry);
expect(licenseEntry.packagesCalled, false);
});
testWidgets('LicensePage returns late if unmounted', (WidgetTester tester) async {
final Completer<LicenseEntry> licenseCompleter = Completer<LicenseEntry>();
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromFuture(licenseCompleter.future);
});
await tester.pumpWidget(
const MaterialApp(
home: LicensePage(),
),
);
await tester.pump();
final FakeLicenseEntry licenseEntry = FakeLicenseEntry();
licenseCompleter.complete(licenseEntry);
await tester.pumpWidget(
const MaterialApp(
home: Placeholder(),
),
);
await tester.pumpAndSettle();
expect(licenseEntry.packagesCalled, true);
});
testWidgets('LicensePage logic defaults to executable name for app name', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
title: 'flutter_tester',
home: Material(child: LicensePage()),
),
);
expect(find.text('flutter_tester'), findsOneWidget);
});
testWidgets('AboutListTile dense property is applied', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Material(child: Center(child: AboutListTile())),
));
Rect tileRect = tester.getRect(find.byType(AboutListTile));
expect(tileRect.height, 56.0);
await tester.pumpWidget(const MaterialApp(
home: Material(child: Center(child: AboutListTile(dense: false))),
));
tileRect = tester.getRect(find.byType(AboutListTile));
expect(tileRect.height, 56.0);
await tester.pumpWidget(const MaterialApp(
home: Material(child: Center(child: AboutListTile(dense: true))),
));
tileRect = tester.getRect(find.byType(AboutListTile));
expect(tileRect.height, 48.0);
});
testWidgets('showLicensePage uses nested navigator by default', (WidgetTester tester) async {
final LicensePageObserver rootObserver = LicensePageObserver();
final LicensePageObserver nestedObserver = LicensePageObserver();
await tester.pumpWidget(MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
initialRoute: '/',
onGenerateRoute: (_) {
return PageRouteBuilder<dynamic>(
pageBuilder: (_, __, ___) => Navigator(
observers: <NavigatorObserver>[nestedObserver],
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<dynamic>(
pageBuilder: (BuildContext context, _, __) {
return ElevatedButton(
onPressed: () {
showLicensePage(
context: context,
applicationName: 'A',
);
},
child: const Text('Show License Page'),
);
},
);
},
),
);
},
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
expect(rootObserver.licensePageCount, 0);
expect(nestedObserver.licensePageCount, 1);
});
testWidgets('showLicensePage uses root navigator if useRootNavigator is true', (WidgetTester tester) async {
final LicensePageObserver rootObserver = LicensePageObserver();
final LicensePageObserver nestedObserver = LicensePageObserver();
await tester.pumpWidget(MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
initialRoute: '/',
onGenerateRoute: (_) {
return PageRouteBuilder<dynamic>(
pageBuilder: (_, __, ___) => Navigator(
observers: <NavigatorObserver>[nestedObserver],
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<dynamic>(
pageBuilder: (BuildContext context, _, __) {
return ElevatedButton(
onPressed: () {
showLicensePage(
context: context,
useRootNavigator: true,
applicationName: 'A',
);
},
child: const Text('Show License Page'),
);
},
);
},
),
);
},
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
expect(rootObserver.licensePageCount, 1);
expect(nestedObserver.licensePageCount, 0);
});
group('Barrier dismissible', () {
late AboutDialogObserver rootObserver;
setUp(() {
rootObserver = AboutDialogObserver();
});
testWidgets('Barrier is dismissible with default parameter', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () => showAboutDialog(
context: context,
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(rootObserver.dialogCount, 1);
// Tap on the barrier.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle();
expect(rootObserver.dialogCount, 0);
});
testWidgets('Barrier is not dismissible with barrierDismissible is false', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () => showAboutDialog(
context: context,
barrierDismissible: false
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(rootObserver.dialogCount, 1);
// Tap on the barrier, which shouldn't do anything this time.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle();
expect(rootObserver.dialogCount, 1);
});
});
testWidgets('Barrier color', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () => showAboutDialog(
context: context,
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).color, Colors.black54);
// Dismiss the dialog.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () => showAboutDialog(
context: context,
barrierColor: Colors.pink,
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).color, Colors.pink);
});
testWidgets('Barrier Label', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () => showAboutDialog(
context: context,
barrierLabel: 'Custom Label',
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).semanticsLabel, 'Custom Label');
});
testWidgets('showAboutDialog uses root navigator by default', (WidgetTester tester) async {
final AboutDialogObserver rootObserver = AboutDialogObserver();
final AboutDialogObserver nestedObserver = AboutDialogObserver();
await tester.pumpWidget(MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Navigator(
observers: <NavigatorObserver>[nestedObserver],
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return ElevatedButton(
onPressed: () {
showAboutDialog(
context: context,
applicationName: 'A',
);
},
child: const Text('Show About Dialog'),
);
},
);
},
),
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
expect(rootObserver.dialogCount, 1);
expect(nestedObserver.dialogCount, 0);
});
testWidgets('showAboutDialog uses nested navigator if useRootNavigator is false', (WidgetTester tester) async {
final AboutDialogObserver rootObserver = AboutDialogObserver();
final AboutDialogObserver nestedObserver = AboutDialogObserver();
await tester.pumpWidget(MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Navigator(
observers: <NavigatorObserver>[nestedObserver],
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return ElevatedButton(
onPressed: () {
showAboutDialog(
context: context,
useRootNavigator: false,
applicationName: 'A',
);
},
child: const Text('Show About Dialog'),
);
},
);
},
),
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
expect(rootObserver.dialogCount, 0);
expect(nestedObserver.dialogCount, 1);
});
group('showAboutDialog avoids overlapping display features', () {
testWidgets('default positioning', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
builder: (BuildContext context, Widget? child) {
return MediaQuery(
// Display has a vertical hinge down the middle
data: const MediaQueryData(
size: Size(800, 600),
displayFeatures: <DisplayFeature>[
DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
],
),
child: child!,
);
},
home: Builder(
builder: (BuildContext context) => ElevatedButton(
onPressed: () {
showAboutDialog(
context: context,
useRootNavigator: false,
applicationName: 'A',
);
},
child: const Text('Show About Dialog'),
),
),
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// By default it should place the dialog on the left screen
expect(tester.getTopLeft(find.byType(AboutDialog)), Offset.zero);
expect(tester.getBottomRight(find.byType(AboutDialog)), const Offset(390.0, 600.0));
});
testWidgets('positioning using anchorPoint', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
builder: (BuildContext context, Widget? child) {
return MediaQuery(
// Display has a vertical hinge down the middle
data: const MediaQueryData(
size: Size(800, 600),
displayFeatures: <DisplayFeature>[
DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
],
),
child: child!,
);
},
home: Builder(
builder: (BuildContext context) => ElevatedButton(
onPressed: () {
showAboutDialog(
context: context,
useRootNavigator: false,
applicationName: 'A',
anchorPoint: const Offset(1000, 0),
);
},
child: const Text('Show About Dialog'),
),
),
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// The anchorPoint hits the right side of the display
expect(tester.getTopLeft(find.byType(AboutDialog)), const Offset(410.0, 0.0));
expect(tester.getBottomRight(find.byType(AboutDialog)), const Offset(800.0, 600.0));
});
testWidgets('positioning using Directionality', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
builder: (BuildContext context, Widget? child) {
return MediaQuery(
// Display has a vertical hinge down the middle
data: const MediaQueryData(
size: Size(800, 600),
displayFeatures: <DisplayFeature>[
DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
],
),
child: Directionality(
textDirection: TextDirection.rtl,
child: child!,
),
);
},
home: Builder(
builder: (BuildContext context) => ElevatedButton(
onPressed: () {
showAboutDialog(
context: context,
useRootNavigator: false,
applicationName: 'A',
);
},
child: const Text('Show About Dialog'),
),
),
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
// Since this is rtl, the first screen is the on the right
expect(tester.getTopLeft(find.byType(AboutDialog)), const Offset(410.0, 0.0));
expect(tester.getBottomRight(find.byType(AboutDialog)), const Offset(800.0, 600.0));
});
});
testWidgets("AboutListTile's child should not be offset when the icon is not specified.", (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: AboutListTile(
child: Text('About'),
),
),
),
);
expect(
find.descendant(
of: find.byType(AboutListTile),
matching: find.byType(Icon),
),
findsNothing,
);
});
testWidgets("AboutDialog's contents are scrollable", (WidgetTester tester) async {
final Key contentKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
home: Navigator(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return ElevatedButton(
onPressed: () {
showAboutDialog(
context: context,
useRootNavigator: false,
applicationName: 'A',
children: <Widget>[
Container(
key: contentKey,
color: Colors.orange,
height: 500,
),
],
);
},
child: const Text('Show About Dialog'),
);
},
);
},
),
));
await tester.tap(find.text('Show About Dialog'));
await tester.pumpAndSettle();
// Try dragging by the [AboutDialog]'s title.
RenderBox box = tester.renderObject(find.text('A'));
Offset originalOffset = box.localToGlobal(Offset.zero);
await tester.drag(find.byKey(contentKey), const Offset(0.0, -20.0));
expect(box.localToGlobal(Offset.zero), equals(originalOffset.translate(0.0, -20.0)));
// Try dragging by the additional children in contents.
box = tester.renderObject(find.byKey(contentKey));
originalOffset = box.localToGlobal(Offset.zero);
await tester.drag(find.byKey(contentKey), const Offset(0.0, -20.0));
expect(box.localToGlobal(Offset.zero), equals(originalOffset.translate(0.0, -20.0)));
});
testWidgets("Material2 - LicensePage's color must be same whether loading or done", (WidgetTester tester) async {
const Color scaffoldColor = Color(0xFF123456);
const Color cardColor = Color(0xFF654321);
await tester.pumpWidget(MaterialApp(
theme: ThemeData.light(useMaterial3: false).copyWith(
scaffoldBackgroundColor: scaffoldColor,
cardColor: cardColor,
),
home: Scaffold(
body: Center(
child: Builder(
builder: (BuildContext context) => GestureDetector(
child: const Text('Show licenses'),
onTap: () {
showLicensePage(
context: context,
applicationName: 'MyApp',
applicationVersion: '1.0.0',
);
},
),
),
),
),
));
await tester.tap(find.text('Show licenses'));
await tester.pump();
await tester.pump();
// Check color when loading.
final List<Material> materialLoadings = tester.widgetList<Material>(find.byType(Material)).toList();
expect(materialLoadings.length, equals(4));
expect(materialLoadings[1].color, scaffoldColor);
expect(materialLoadings[2].color, cardColor);
await tester.pumpAndSettle();
// Check color when done.
expect(find.byKey(const ValueKey<ConnectionState>(ConnectionState.done)), findsOneWidget);
final List<Material> materialDones = tester.widgetList<Material>(find.byType(Material)).toList();
expect(materialDones.length, equals(3));
expect(materialDones[0].color, scaffoldColor);
expect(materialDones[1].color, cardColor);
});
testWidgets("Material3 - LicensePage's color must be same whether loading or done", (WidgetTester tester) async {
const Color scaffoldColor = Color(0xFF123456);
const Color cardColor = Color(0xFF654321);
await tester.pumpWidget(MaterialApp(
theme: ThemeData.light(useMaterial3: true).copyWith(
scaffoldBackgroundColor: scaffoldColor,
cardColor: cardColor,
),
home: Scaffold(
body: Center(
child: Builder(
builder: (BuildContext context) => GestureDetector(
child: const Text('Show licenses'),
onTap: () {
showLicensePage(
context: context,
applicationName: 'MyApp',
applicationVersion: '1.0.0',
);
},
),
),
),
),
));
await tester.tap(find.text('Show licenses'));
await tester.pump();
await tester.pump();
// Check color when loading.
final List<Material> materialLoadings = tester.widgetList<Material>(find.byType(Material)).toList();
expect(materialLoadings.length, equals(5));
expect(materialLoadings[1].color, scaffoldColor);
expect(materialLoadings[2].color, cardColor);
await tester.pumpAndSettle();
// Check color when done.
expect(find.byKey(const ValueKey<ConnectionState>(ConnectionState.done)), findsOneWidget);
final List<Material> materialDones = tester.widgetList<Material>(find.byType(Material)).toList();
expect(materialDones.length, equals(4));
expect(materialDones[0].color, scaffoldColor);
expect(materialDones[1].color, cardColor);
});
testWidgets('Conflicting scrollbars are not applied by ScrollBehavior to _PackageLicensePage', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/83819
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['AAA'], 'BBB'),
]);
});
await tester.pumpWidget(
const MaterialApp(
home: Center(
child: LicensePage(),
),
),
);
await tester.pumpAndSettle();
// Check for packages.
expect(find.text('AAA'), findsOneWidget);
// Check license is displayed after entering into license page for 'AAA'.
await tester.tap(find.text('AAA'));
await tester.pumpAndSettle();
// The inherited ScrollBehavior should not apply Scrollbars since they are
// already built in to the widget.
switch (debugDefaultTargetPlatformOverride) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
expect(find.byType(CupertinoScrollbar), findsNothing);
case TargetPlatform.iOS:
expect(find.byType(CupertinoScrollbar), findsOneWidget);
case null:
break;
}
expect(find.byType(Scrollbar), findsOneWidget);
expect(find.byType(RawScrollbar), findsNothing);
}, variant: TargetPlatformVariant.all());
testWidgets('ListView of license entries is primary', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/120710
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
LicenseEntryWithLineBreaks(
<String>['AAA'],
// Add enough content to scroll
List<String>.generate(500, (int index) => 'BBBB').join('\n'),
),
]);
});
await tester.pumpWidget(
MaterialApp(
title: 'Flutter Code Sample',
home: Scaffold(
body: Builder(
builder: (BuildContext context) => TextButton(
child: const Text('Show License Page'),
onPressed: () {
showLicensePage(context: context);
},
),
),
),
)
);
await tester.pumpAndSettle();
expect(find.text('Show License Page'), findsOneWidget);
await tester.tap(find.text('Show License Page'));
await tester.pumpAndSettle();
// Check for packages.
expect(find.text('AAA'), findsOneWidget);
// Check license is displayed after entering into license page for 'AAA'.
await tester.tap(find.text('AAA'));
await tester.pumpAndSettle();
// The inherited ScrollBehavior should not apply Scrollbars since they are
// already built in to the widget.
switch (debugDefaultTargetPlatformOverride) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
expect(find.byType(CupertinoScrollbar), findsNothing);
case TargetPlatform.iOS:
expect(find.byType(CupertinoScrollbar), findsOneWidget);
case null:
break;
}
expect(find.byType(Scrollbar), findsOneWidget);
expect(find.byType(RawScrollbar), findsNothing);
await tester.drag(find.byType(ListView), const Offset(0.0, 20.0));
await tester.pumpAndSettle(); // No exception triggered.
}, variant: TargetPlatformVariant.all());
testWidgets('LicensePage padding', (WidgetTester tester) async {
const FlutterLogo logo = FlutterLogo();
await tester.pumpWidget(
const MaterialApp(
title: 'Pirate app',
home: Center(
child: LicensePage(
applicationName: 'LicensePage test app',
applicationIcon: logo,
applicationVersion: '0.1.2',
applicationLegalese: 'I am the very model of a modern major general.',
),
),
),
);
final Finder appName = find.text('LicensePage test app');
final Finder appIcon = find.byType(FlutterLogo);
final Finder appVersion = find.text('0.1.2');
final Finder appLegalese = find.text('I am the very model of a modern major general.');
final Finder appPowered = find.text('Powered by Flutter');
expect(appName, findsOneWidget);
expect(appIcon, findsOneWidget);
expect(appVersion, findsOneWidget);
expect(appLegalese, findsOneWidget);
expect(appPowered, findsOneWidget);
// Bottom padding is applied to the app version and app legalese text.
final double appNameBottomPadding = tester.getTopLeft(appIcon).dy - tester.getBottomLeft(appName).dy;
expect(appNameBottomPadding, 0.0);
final double appIconBottomPadding = tester.getTopLeft(appVersion).dy - tester.getBottomLeft(appIcon).dy;
expect(appIconBottomPadding, 0.0);
final double appVersionBottomPadding = tester.getTopLeft(appLegalese).dy - tester.getBottomLeft(appVersion).dy;
expect(appVersionBottomPadding, 18.0);
final double appLegaleseBottomPadding = tester.getTopLeft(appPowered).dy - tester.getBottomLeft(appLegalese).dy;
expect(appLegaleseBottomPadding, 18.0);
});
testWidgets('LicensePage has no extra padding between app icon and app powered text', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/99559
const FlutterLogo logo = FlutterLogo();
await tester.pumpWidget(
const MaterialApp(
title: 'Pirate app',
home: Center(
child: LicensePage(
applicationIcon: logo,
),
),
),
);
final Finder appName = find.text('LicensePage test app');
final Finder appIcon = find.byType(FlutterLogo);
final Finder appVersion = find.text('0.1.2');
final Finder appLegalese = find.text('I am the very model of a modern major general.');
final Finder appPowered = find.text('Powered by Flutter');
expect(appName, findsNothing);
expect(appIcon, findsOneWidget);
expect(appVersion, findsNothing);
expect(appLegalese, findsNothing);
expect(appPowered, findsOneWidget);
// Padding between app icon and app powered text.
final double appIconBottomPadding = tester.getTopLeft(appPowered).dy - tester.getBottomLeft(appIcon).dy;
expect(appIconBottomPadding, 18.0);
});
testWidgets('Material2 - Error handling test', (WidgetTester tester) async {
LicenseRegistry.addLicense(() => Stream<LicenseEntry>.error(Exception('Injected failure')));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: const Material(child: AboutListTile())
)
);
await tester.tap(find.byType(ListTile));
await tester.pump();
await tester.pump(const Duration(seconds: 2));
await tester.tap(find.text('VIEW LICENSES'));
await tester.pump();
await tester.pump(const Duration(seconds: 2));
final Finder finder = find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_PackagesView');
// force the stream to complete (has to be done in a runAsync block since it's areal async process)
await tester.runAsync(() => (tester.firstState(finder) as dynamic).licenses as Future<dynamic>);
expect(tester.takeException().toString(), 'Exception: Injected failure');
await tester.pumpAndSettle();
expect(tester.takeException().toString(), 'Exception: Injected failure');
expect(find.text('Exception: Injected failure'), findsOneWidget);
});
testWidgets('Material3 - Error handling test', (WidgetTester tester) async {
LicenseRegistry.addLicense(() => Stream<LicenseEntry>.error(Exception('Injected failure')));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const Material(child: AboutListTile())
)
);
await tester.tap(find.byType(ListTile));
await tester.pump();
await tester.pump(const Duration(seconds: 2));
await tester.tap(find.text('View licenses'));
await tester.pump();
await tester.pump(const Duration(seconds: 2));
final Finder finder = find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_PackagesView');
// force the stream to complete (has to be done in a runAsync block since it's areal async process)
await tester.runAsync(() => (tester.firstState(finder) as dynamic).licenses as Future<dynamic>);
expect(tester.takeException().toString(), 'Exception: Injected failure');
await tester.pumpAndSettle();
expect(tester.takeException().toString(), 'Exception: Injected failure');
expect(find.text('Exception: Injected failure'), findsOneWidget);
});
testWidgets('Material2 - LicensePage master view layout position - ltr', (WidgetTester tester) async {
const TextDirection textDirection = TextDirection.ltr;
const Size defaultSize = Size(800.0, 600.0);
const Size wideSize = Size(1200.0, 600.0);
const String title = 'License ABC';
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['ABC'], 'DEF'),
]);
});
addTearDown(() async {
await tester.binding.setSurfaceSize(null);
});
// Configure to show the default layout.
await tester.binding.setSurfaceSize(defaultSize);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
title: title,
home: const Scaffold(
body: Directionality(
textDirection: textDirection,
child: LicensePage(),
),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// If the layout width is less than 840.0 pixels, nested layout is
// used which positions license page title at the top center.
Offset titleOffset = tester.getCenter(find.text(title));
expect(titleOffset, Offset(defaultSize.width / 2, 92.0));
expect(tester.getCenter(find.byType(ListView)), Offset(defaultSize.width / 2, 328.0));
// Configure a wide window to show the lateral UI.
await tester.binding.setSurfaceSize(wideSize);
await tester.pumpWidget(
const MaterialApp(
title: title,
home: Scaffold(
body: Directionality(
textDirection: textDirection,
child: LicensePage(),
),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// If the layout width is greater than 840.0 pixels, lateral UI layout
// is used which positions license page title and packageList
// at the top left.
titleOffset = tester.getTopRight(find.text(title));
expect(titleOffset, const Offset(292.0, 136.0));
expect(titleOffset.dx, lessThan(wideSize.width - 320)); // Default master view width is 320.0.
expect(tester.getCenter(find.byType(ListView)), const Offset(160, 356));
});
testWidgets('Material3 - LicensePage master view layout position - ltr', (WidgetTester tester) async {
const TextDirection textDirection = TextDirection.ltr;
const Size defaultSize = Size(800.0, 600.0);
const Size wideSize = Size(1200.0, 600.0);
const String title = 'License ABC';
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['ABC'], 'DEF'),
]);
});
addTearDown(() async {
await tester.binding.setSurfaceSize(null);
});
// Configure to show the default layout.
await tester.binding.setSurfaceSize(defaultSize);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
title: title,
home: const Scaffold(
body: Directionality(
textDirection: textDirection,
child: LicensePage(),
),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// If the layout width is less than 840.0 pixels, nested layout is
// used which positions license page title at the top center.
Offset titleOffset = tester.getCenter(find.text(title));
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(titleOffset, Offset(defaultSize.width / 2, 96.0));
}
expect(tester.getCenter(find.byType(ListView)), Offset(defaultSize.width / 2, 328.0));
// Configure a wide window to show the lateral UI.
await tester.binding.setSurfaceSize(wideSize);
await tester.pumpWidget(
const MaterialApp(
title: title,
home: Scaffold(
body: Directionality(
textDirection: textDirection,
child: LicensePage(),
),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// If the layout width is greater than 840.0 pixels, lateral UI layout
// is used which positions license page title and packageList
// at the top left.
titleOffset = tester.getTopRight(find.text(title));
expect(titleOffset, const Offset(292.0, 136.0));
expect(titleOffset.dx, lessThan(wideSize.width - 320)); // Default master view width is 320.0.
expect(tester.getCenter(find.byType(ListView)), const Offset(160, 356));
});
testWidgets('Material2 - LicensePage master view layout position - rtl', (WidgetTester tester) async {
const TextDirection textDirection = TextDirection.rtl;
const Size defaultSize = Size(800.0, 600.0);
const Size wideSize = Size(1200.0, 600.0);
const String title = 'License ABC';
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['ABC'], 'DEF'),
]);
});
addTearDown(() async {
await tester.binding.setSurfaceSize(null);
});
// Configure to show the default layout.
await tester.binding.setSurfaceSize(defaultSize);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
title: title,
home: const Scaffold(
body: Directionality(
textDirection: textDirection,
child: LicensePage(),
),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// If the layout width is less than 840.0 pixels, nested layout is
// used which positions license page title at the top center.
Offset titleOffset = tester.getCenter(find.text(title));
expect(titleOffset, Offset(defaultSize.width / 2, 92.0));
expect(tester.getCenter(find.byType(ListView)), Offset(defaultSize.width / 2, 328.0));
// Configure a wide window to show the lateral UI.
await tester.binding.setSurfaceSize(wideSize);
await tester.pumpWidget(
const MaterialApp(
title: title,
home: Scaffold(
body: Directionality(
textDirection: textDirection,
child: LicensePage(),
),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// If the layout width is greater than 840.0 pixels, lateral UI layout
// is used which positions license page title and packageList
// at the top right.
titleOffset = tester.getTopLeft(find.text(title));
expect(titleOffset, const Offset(908.0, 136.0));
expect(titleOffset.dx, greaterThan(wideSize.width - 320)); // Default master view width is 320.0.
expect(tester.getCenter(find.byType(ListView)), const Offset(1040.0, 356.0));
});
testWidgets('Material3 - LicensePage master view layout position - rtl', (WidgetTester tester) async {
const TextDirection textDirection = TextDirection.rtl;
const Size defaultSize = Size(800.0, 600.0);
const Size wideSize = Size(1200.0, 600.0);
const String title = 'License ABC';
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['ABC'], 'DEF'),
]);
});
addTearDown(() async {
await tester.binding.setSurfaceSize(null);
});
// Configure to show the default layout.
await tester.binding.setSurfaceSize(defaultSize);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
title: title,
home: const Scaffold(
body: Directionality(
textDirection: textDirection,
child: LicensePage(),
),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// If the layout width is less than 840.0 pixels, nested layout is
// used which positions license page title at the top center.
Offset titleOffset = tester.getCenter(find.text(title));
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(titleOffset, Offset(defaultSize.width / 2, 96.0));
}
expect(tester.getCenter(find.byType(ListView)), Offset(defaultSize.width / 2, 328.0));
// Configure a wide window to show the lateral UI.
await tester.binding.setSurfaceSize(wideSize);
await tester.pumpWidget(
const MaterialApp(
title: title,
home: Scaffold(
body: Directionality(
textDirection: textDirection,
child: LicensePage(),
),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// If the layout width is greater than 840.0 pixels, lateral UI layout
// is used which positions license page title and packageList
// at the top right.
titleOffset = tester.getTopLeft(find.text(title));
expect(titleOffset, const Offset(908.0, 136.0));
expect(titleOffset.dx, greaterThan(wideSize.width - 320)); // Default master view width is 320.0.
expect(tester.getCenter(find.byType(ListView)), const Offset(1040.0, 356.0));
});
testWidgets('License page title in lateral UI does not use AppBarTheme.foregroundColor', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/108991
final ThemeData theme = ThemeData(
appBarTheme: const AppBarTheme(foregroundColor: Color(0xFFFFFFFF)),
useMaterial3: true,
);
const String title = 'License ABC';
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['ABC'], 'DEF'),
]);
});
addTearDown(() async {
await tester.binding.setSurfaceSize(null);
});
// Configure a wide window to show the lateral UI.
await tester.binding.setSurfaceSize(const Size(1200.0, 600.0));
await tester.pumpWidget(
MaterialApp(
title: title,
theme: theme,
home: const Scaffold(
body: LicensePage(),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
final RenderParagraph renderParagraph = tester.renderObject(find.text('ABC').last) as RenderParagraph;
// License page title should not use AppBarTheme's foregroundColor.
expect(renderParagraph.text.style!.color, isNot(theme.appBarTheme.foregroundColor));
// License page title in the lateral UI uses default text style color.
expect(renderParagraph.text.style!.color, theme.textTheme.titleLarge!.color);
});
testWidgets('License page default title text color in the nested UI', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/108991
final ThemeData theme = ThemeData(useMaterial3: true);
const String title = 'License ABC';
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['ABC'], 'DEF'),
]);
});
await tester.pumpWidget(
MaterialApp(
title: title,
theme: theme,
home: const Scaffold(
body: LicensePage(),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// Currently in the master view.
expect(find.text('License ABC'), findsOneWidget);
// Navigate to the license page.
await tester.tap(find.text('ABC'));
await tester.pumpAndSettle();
// Master view is no longer visible.
expect(find.text('License ABC'), findsNothing);
final RenderParagraph renderParagraph = tester.renderObject(find.text('ABC').first) as RenderParagraph;
expect(renderParagraph.text.style!.color, theme.textTheme.titleLarge!.color);
});
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('License page default title text color in the nested UI', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/108991
final ThemeData theme = ThemeData(useMaterial3: false);
const String title = 'License ABC';
LicenseRegistry.addLicense(() {
return Stream<LicenseEntry>.fromIterable(<LicenseEntry>[
const LicenseEntryWithLineBreaks(<String>['ABC'], 'DEF'),
]);
});
await tester.pumpWidget(
MaterialApp(
title: title,
theme: theme,
home: const Scaffold(
body: LicensePage(),
),
),
);
await tester.pumpAndSettle(); // Finish rendering the page.
// Currently in the master view.
expect(find.text('License ABC'), findsOneWidget);
// Navigate to the license page.
await tester.tap(find.text('ABC'));
await tester.pumpAndSettle();
// Master view is no longer visible.
expect(find.text('License ABC'), findsNothing);
final RenderParagraph renderParagraph = tester.renderObject(find.text('ABC').first) as RenderParagraph;
expect(renderParagraph.text.style!.color, theme.primaryTextTheme.titleLarge!.color);
});
});
}
class FakeLicenseEntry extends LicenseEntry {
FakeLicenseEntry();
bool get packagesCalled => _packagesCalled;
bool _packagesCalled = false;
@override
Iterable<LicenseParagraph> paragraphs = <LicenseParagraph>[];
@override
Iterable<String> get packages {
_packagesCalled = true;
return <String>[];
}
}
class LicensePageObserver extends NavigatorObserver {
int licensePageCount = 0;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (route is MaterialPageRoute<dynamic>) {
licensePageCount++;
}
super.didPush(route, previousRoute);
}
}
class AboutDialogObserver extends NavigatorObserver {
int dialogCount = 0;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (route is DialogRoute) {
dialogCount++;
}
super.didPush(route, previousRoute);
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (route is DialogRoute) {
dialogCount--;
}
super.didPop(route, previousRoute);
}
}
| flutter/packages/flutter/test/material/about_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/about_test.dart",
"repo_id": "flutter",
"token_count": 25861
} | 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('MaterialBanner properties are respected', (WidgetTester tester) async {
const String contentText = 'Content';
const Color backgroundColor = Colors.pink;
const Color surfaceTintColor = Colors.green;
const Color shadowColor = Colors.blue;
const Color dividerColor = Colors.yellow;
const TextStyle contentTextStyle = TextStyle(color: Colors.pink);
await tester.pumpWidget(
MaterialApp(
home: MaterialBanner(
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
dividerColor: dividerColor,
contentTextStyle: contentTextStyle,
content: const Text(contentText),
actions: <Widget>[
TextButton(
child: const Text('Action'),
onPressed: () { },
),
],
),
),
);
final Material material = _getMaterialFromBanner(tester);
expect(material.elevation, 0.0);
expect(material.color, backgroundColor);
expect(material.surfaceTintColor, surfaceTintColor);
expect(material.shadowColor, shadowColor);
final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText);
expect(content.text.style, contentTextStyle);
final Divider divider = tester.widget<Divider>(find.byType(Divider));
expect(divider.color, dividerColor);
});
testWidgets('MaterialBanner properties are respected when presented by ScaffoldMessenger', (WidgetTester tester) async {
const String contentText = 'Content';
const Key tapTarget = Key('tap-target');
const Color backgroundColor = Colors.pink;
const Color surfaceTintColor = Colors.green;
const Color shadowColor = Colors.blue;
const Color dividerColor = Colors.yellow;
const TextStyle contentTextStyle = TextStyle(color: Colors.pink);
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: tapTarget,
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const Text(contentText),
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
dividerColor: dividerColor,
contentTextStyle: contentTextStyle,
actions: <Widget>[
TextButton(
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
);
},
),
),
));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
final Material material = _getMaterialFromText(tester, contentText);
expect(material.elevation, 0.0);
expect(material.color, backgroundColor);
expect(material.surfaceTintColor, surfaceTintColor);
expect(material.shadowColor, shadowColor);
final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText);
expect(content.text.style, contentTextStyle);
final Divider divider = tester.widget<Divider>(find.byType(Divider));
expect(divider.color, dividerColor);
});
testWidgets('Actions laid out below content if more than one action', (WidgetTester tester) async {
const String contentText = 'Content';
await tester.pumpWidget(
MaterialApp(
home: MaterialBanner(
content: const Text(contentText),
actions: <Widget>[
TextButton(
child: const Text('Action 1'),
onPressed: () { },
),
TextButton(
child: const Text('Action 2'),
onPressed: () { },
),
],
),
),
);
final Offset contentBottomLeft = tester.getBottomLeft(find.text(contentText));
final Offset actionsTopLeft = tester.getTopLeft(find.byType(OverflowBar));
expect(contentBottomLeft.dy, lessThan(actionsTopLeft.dy));
expect(contentBottomLeft.dx, lessThan(actionsTopLeft.dx));
});
testWidgets('Actions laid out below content if more than one action when presented by ScaffoldMessenger', (WidgetTester tester) async {
const String contentText = 'Content';
const Key tapTarget = Key('tap-target');
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: tapTarget,
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const Text(contentText),
actions: <Widget>[
TextButton(
child: const Text('OK'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
TextButton(
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
);
},
),
),
));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
final Offset contentBottomLeft = tester.getBottomLeft(find.text(contentText));
final Offset actionsTopLeft = tester.getTopLeft(find.byType(OverflowBar));
expect(contentBottomLeft.dy, lessThan(actionsTopLeft.dy));
expect(contentBottomLeft.dx, lessThan(actionsTopLeft.dx));
});
testWidgets('Actions laid out beside content if only one action', (WidgetTester tester) async {
const String contentText = 'Content';
await tester.pumpWidget(
MaterialApp(
home: MaterialBanner(
content: const Text(contentText),
actions: <Widget>[
TextButton(
child: const Text('Action'),
onPressed: () { },
),
],
),
),
);
final Offset contentBottomLeft = tester.getBottomLeft(find.text(contentText));
final Offset actionsTopRight = tester.getTopRight(find.byType(OverflowBar));
expect(contentBottomLeft.dy, greaterThan(actionsTopRight.dy));
expect(contentBottomLeft.dx, lessThan(actionsTopRight.dx));
});
testWidgets('Actions laid out beside content if only one action when presented by ScaffoldMessenger', (WidgetTester tester) async {
const String contentText = 'Content';
const Key tapTarget = Key('tap-target');
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: tapTarget,
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const Text(contentText),
actions: <Widget>[
TextButton(
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
);
},
),
),
));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
final Offset contentBottomLeft = tester.getBottomLeft(find.text(contentText));
final Offset actionsTopRight = tester.getTopRight(find.byType(OverflowBar));
expect(contentBottomLeft.dy, greaterThan(actionsTopRight.dy));
expect(contentBottomLeft.dx, lessThan(actionsTopRight.dx));
});
testWidgets('material banner content can scale and has maxScaleFactor', (WidgetTester tester) async {
const String label = 'A';
Widget buildApp({ required TextScaler textScaler }) {
return MaterialApp(
home: MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: MaterialBanner(
forceActionsBelow: true,
content: const SizedBox(child:Center(child:Text(label))),
actions: <Widget>[
TextButton(
child: const Text('B'),
onPressed: () { },
),
],
),
),
);
}
await tester.pumpWidget(buildApp(textScaler: TextScaler.noScaling));
expect(find.text(label), findsOneWidget);
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(tester.getSize(find.text(label)), const Size(14.25, 20.0));
}
await tester.pumpWidget(buildApp(textScaler: const TextScaler.linear(1.1)));
await tester.pumpAndSettle();
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(_sizeAlmostEqual(tester.getSize(find.text(label)), const Size(15.65, 22.0)), true);
}
await tester.pumpWidget(buildApp(textScaler: const TextScaler.linear(1.5)));
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(_sizeAlmostEqual(tester.getSize(find.text(label)), const Size(21.25, 30)), true);
}
await tester.pumpWidget(buildApp(textScaler: const TextScaler.linear(4)));
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(_sizeAlmostEqual(tester.getSize(find.text(label)), const Size(21.25, 30)), true);
}
});
group('MaterialBanner elevation', () {
Widget buildBanner(Key tapTarget, {double? elevation, double? themeElevation}) {
return MaterialApp(
theme: ThemeData(bannerTheme: MaterialBannerThemeData(elevation: themeElevation)),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: tapTarget,
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const Text('MaterialBanner'),
elevation: elevation,
actions: <Widget>[
TextButton(
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
);
},
),
),
);
}
testWidgets('Elevation defaults to 0', (WidgetTester tester) async {
const Key tapTarget = Key('tap-target');
await tester.pumpWidget(buildBanner(tapTarget));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
expect(_getMaterialFromBanner(tester).elevation, 0.0);
await tester.tap(find.text('DISMISS'));
await tester.pumpAndSettle();
await tester.pumpWidget(buildBanner(tapTarget, themeElevation: 6.0));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
expect(_getMaterialFromBanner(tester).elevation, 6.0);
await tester.tap(find.text('DISMISS'));
await tester.pumpAndSettle();
await tester.pumpWidget(buildBanner(tapTarget, elevation: 3.0, themeElevation: 6.0));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
expect(_getMaterialFromBanner(tester).elevation, 3.0);
await tester.tap(find.text('DISMISS'));
await tester.pumpAndSettle();
});
testWidgets('Uses elevation of MaterialBannerTheme by default', (WidgetTester tester) async {
const Key tapTarget = Key('tap-target');
await tester.pumpWidget(buildBanner(tapTarget, themeElevation: 6.0));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
expect(_getMaterialFromBanner(tester).elevation, 6.0);
await tester.tap(find.text('DISMISS'));
await tester.pumpAndSettle();
await tester.pumpWidget(buildBanner(tapTarget, elevation: 3.0, themeElevation: 6.0));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
expect(_getMaterialFromBanner(tester).elevation, 3.0);
await tester.tap(find.text('DISMISS'));
await tester.pumpAndSettle();
});
testWidgets('Scaffold body is pushed down if elevation is 0', (WidgetTester tester) async {
const Key tapTarget = Key('tap-target');
await tester.pumpWidget(buildBanner(tapTarget, elevation: 0.0));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
final Offset contentTopLeft = tester.getTopLeft(find.byKey(tapTarget));
final Offset bannerBottomLeft = tester.getBottomLeft(find.byType(MaterialBanner));
expect(contentTopLeft.dx, 0.0);
expect(contentTopLeft.dy, greaterThanOrEqualTo(bannerBottomLeft.dy));
});
});
testWidgets('MaterialBanner control test', (WidgetTester tester) async {
const String helloMaterialBanner = 'Hello MaterialBanner';
const Key tapTarget = Key('tap-target');
const Key dismissTarget = Key('dismiss-target');
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: tapTarget,
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const Text(helloMaterialBanner),
actions: <Widget>[
TextButton(
key: dismissTarget,
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
);
},
),
),
));
expect(find.text(helloMaterialBanner), findsNothing);
await tester.tap(find.byKey(tapTarget));
expect(find.text(helloMaterialBanner), findsNothing);
await tester.pump(); // schedule animation
expect(find.text(helloMaterialBanner), findsOneWidget);
await tester.pump(); // begin animation
expect(find.text(helloMaterialBanner), findsOneWidget);
await tester.pump(const Duration(milliseconds: 750)); // 0.75s // animation last frame; two second timer starts here
expect(find.text(helloMaterialBanner), findsOneWidget);
await tester.pump(const Duration(milliseconds: 750)); // 1.50s
expect(find.text(helloMaterialBanner), findsOneWidget);
await tester.pump(const Duration(milliseconds: 750)); // 2.25s
expect(find.text(helloMaterialBanner), findsOneWidget);
await tester.tap(find.byKey(dismissTarget));
await tester.pump(); // begin animation
expect(find.text(helloMaterialBanner), findsOneWidget); // frame 0 of dismiss animation
await tester.pumpAndSettle(); // 3.75s // last frame of animation, material banner removed from build
expect(find.text(helloMaterialBanner), findsNothing);
});
testWidgets('MaterialBanner twice test', (WidgetTester tester) async {
int materialBannerCount = 0;
const Key tapTarget = Key('tap-target');
const Key dismissTarget = Key('dismiss-target');
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: tapTarget,
onTap: () {
materialBannerCount += 1;
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: Text('banner$materialBannerCount'),
actions: <Widget>[
TextButton(
key: dismissTarget,
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
);
},
),
),
));
expect(find.text('banner1'), findsNothing);
expect(find.text('banner2'), findsNothing);
await tester.tap(find.byKey(tapTarget)); // queue banner1
await tester.tap(find.byKey(tapTarget)); // queue banner2
expect(find.text('banner1'), findsNothing);
expect(find.text('banner2'), findsNothing);
await tester.pump(); // schedule animation for banner1
expect(find.text('banner1'), findsOneWidget);
expect(find.text('banner2'), findsNothing);
await tester.pump(); // begin animation
expect(find.text('banner1'), findsOneWidget);
expect(find.text('banner2'), findsNothing);
await tester.pump(const Duration(milliseconds: 750)); // 0.75s // animation last frame
expect(find.text('banner1'), findsOneWidget);
expect(find.text('banner2'), findsNothing);
await tester.pump(const Duration(milliseconds: 750)); // 1.50s
expect(find.text('banner1'), findsOneWidget);
expect(find.text('banner2'), findsNothing);
await tester.pump(const Duration(milliseconds: 750)); // 2.25s
expect(find.text('banner1'), findsOneWidget);
expect(find.text('banner2'), findsNothing);
await tester.tap(find.byKey(dismissTarget));
await tester.pump(); // begin animation
expect(find.text('banner1'), findsOneWidget);
expect(find.text('banner2'), findsNothing);
await tester.pump(const Duration(milliseconds: 750)); // 3.75s // last frame of animation, material banner removed from build, new material banner put in its place
expect(find.text('banner1'), findsNothing);
expect(find.text('banner2'), findsOneWidget);
await tester.pump(); // begin animation
expect(find.text('banner1'), findsNothing);
expect(find.text('banner2'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 750)); // 4.50s // animation last frame
expect(find.text('banner1'), findsNothing);
expect(find.text('banner2'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 750)); // 5.25s
expect(find.text('banner1'), findsNothing);
expect(find.text('banner2'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 750)); // 6.00s
expect(find.text('banner1'), findsNothing);
expect(find.text('banner2'), findsOneWidget);
await tester.tap(find.byKey(dismissTarget)); // reverse animation is scheduled
await tester.pump(); // begin animation
expect(find.text('banner1'), findsNothing);
expect(find.text('banner2'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 750)); // 7.50s // last frame of animation, material banner removed from build
expect(find.text('banner1'), findsNothing);
expect(find.text('banner2'), findsNothing);
});
testWidgets('ScaffoldMessenger does not duplicate a MaterialBanner when presenting a SnackBar.', (WidgetTester tester) async {
const Key materialBannerTapTarget = Key('materialbanner-tap-target');
const Key snackBarTapTarget = Key('snackbar-tap-target');
const String snackBarText = 'SnackBar';
const String materialBannerText = 'MaterialBanner';
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return Column(
children: <Widget>[
GestureDetector(
key: snackBarTapTarget,
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text(snackBarText),
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
),
GestureDetector(
key: materialBannerTapTarget,
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const Text(materialBannerText),
actions: <Widget>[
TextButton(
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
),
],
);
},
),
),
));
await tester.tap(find.byKey(snackBarTapTarget));
await tester.tap(find.byKey(materialBannerTapTarget));
await tester.pumpAndSettle();
expect(find.text(snackBarText), findsOneWidget);
expect(find.text(materialBannerText), findsOneWidget);
});
// Regression test for https://github.com/flutter/flutter/issues/39574
testWidgets('Single action laid out beside content but aligned to the trailing edge', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: MaterialBanner(
content: const Text('Content'),
actions: <Widget>[
TextButton(
child: const Text('Action'),
onPressed: () { },
),
],
),
),
);
final Offset actionsTopRight = tester.getTopRight(find.byType(OverflowBar));
final Offset bannerTopRight = tester.getTopRight(find.byType(MaterialBanner));
expect(actionsTopRight.dx + 8, bannerTopRight.dx); // actions OverflowBar is padded by 8
});
// Regression test for https://github.com/flutter/flutter/issues/39574
testWidgets('Single action laid out beside content but aligned to the trailing edge when presented by ScaffoldMessenger', (WidgetTester tester) async {
const Key tapTarget = Key('tap-target');
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: tapTarget,
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const Text('Content'),
actions: <Widget>[
TextButton(
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
);
},
),
),
));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
final Offset actionsTopRight = tester.getTopRight(find.byType(OverflowBar));
final Offset bannerTopRight = tester.getTopRight(find.byType(MaterialBanner));
expect(actionsTopRight.dx + 8, bannerTopRight.dx); // actions OverflowBar is padded by 8
});
// Regression test for https://github.com/flutter/flutter/issues/39574
testWidgets('Single action laid out beside content but aligned to the trailing edge - RTL', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: MaterialBanner(
content: const Text('Content'),
actions: <Widget>[
TextButton(
child: const Text('Action'),
onPressed: () { },
),
],
),
),
),
);
final Offset actionsTopLeft = tester.getTopLeft(find.byType(OverflowBar));
final Offset bannerTopLeft = tester.getTopLeft(find.byType(MaterialBanner));
expect(actionsTopLeft.dx - 8, moreOrLessEquals(bannerTopLeft.dx)); // actions OverflowBar is padded by 8
});
testWidgets('Single action laid out beside content but aligned to the trailing edge when presented by ScaffoldMessenger - RTL', (WidgetTester tester) async {
const Key tapTarget = Key('tap-target');
await tester.pumpWidget(MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: tapTarget,
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const Text('Content'),
actions: <Widget>[
TextButton(
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
);
},
),
),
),
));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
final Offset actionsTopLeft = tester.getTopLeft(find.byType(OverflowBar));
final Offset bannerTopLeft = tester.getTopLeft(find.byType(MaterialBanner));
expect(actionsTopLeft.dx - 8, moreOrLessEquals(bannerTopLeft.dx)); // actions OverflowBar is padded by 8
});
testWidgets('Actions laid out below content if forced override', (WidgetTester tester) async {
const String contentText = 'Content';
await tester.pumpWidget(
MaterialApp(
home: MaterialBanner(
forceActionsBelow: true,
content: const Text(contentText),
actions: <Widget>[
TextButton(
child: const Text('Action'),
onPressed: () { },
),
],
),
),
);
final Offset contentBottomLeft = tester.getBottomLeft(find.text(contentText));
final Offset actionsTopLeft = tester.getTopLeft(find.byType(OverflowBar));
expect(contentBottomLeft.dy, lessThan(actionsTopLeft.dy));
expect(contentBottomLeft.dx, lessThan(actionsTopLeft.dx));
});
testWidgets('Actions laid out below content if forced override when presented by ScaffoldMessenger', (WidgetTester tester) async {
const String contentText = 'Content';
const Key tapTarget = Key('tap-target');
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: tapTarget,
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const Text(contentText),
forceActionsBelow: true,
actions: <Widget>[
TextButton(
child: const Text('DISMISS'),
onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
],
));
},
behavior: HitTestBehavior.opaque,
child: const SizedBox(
height: 100.0,
width: 100.0,
),
);
},
),
),
));
await tester.tap(find.byKey(tapTarget));
await tester.pumpAndSettle();
final Offset contentBottomLeft = tester.getBottomLeft(find.text(contentText));
final Offset actionsTopLeft = tester.getTopLeft(find.byType(OverflowBar));
expect(contentBottomLeft.dy, lessThan(actionsTopLeft.dy));
expect(contentBottomLeft.dx, lessThan(actionsTopLeft.dx));
});
testWidgets('Action widgets layout', (WidgetTester tester) async {
// This regression test ensures that the action widgets layout matches what
// it was, before ButtonBar was replaced by OverflowBar.
Widget buildFrame(int actionCount, TextDirection textDirection) {
return MaterialApp(
home: Directionality(
textDirection: textDirection,
child: MaterialBanner(
content: const SizedBox(width: 100, height: 100),
actions: List<Widget>.generate(actionCount, (int index) {
return SizedBox(
width: 64,
height: 48,
key: ValueKey<int>(index),
);
}),
),
),
);
}
final Finder action0 = find.byKey(const ValueKey<int>(0));
final Finder action1 = find.byKey(const ValueKey<int>(1));
final Finder action2 = find.byKey(const ValueKey<int>(2));
// The action coordinates that follow were obtained by running
// the test code, before ButtonBar was replaced by OverflowBar.
await tester.pumpWidget(buildFrame(1, TextDirection.ltr));
expect(tester.getTopLeft(action0), const Offset(728, 28));
await tester.pumpWidget(buildFrame(1, TextDirection.rtl));
expect(tester.getTopLeft(action0), const Offset(8, 28));
await tester.pumpWidget(buildFrame(3, TextDirection.ltr));
expect(tester.getTopLeft(action0), const Offset(584, 130));
expect(tester.getTopLeft(action1), const Offset(656, 130));
expect(tester.getTopLeft(action2), const Offset(728, 130));
await tester.pumpWidget(buildFrame(3, TextDirection.rtl));
expect(tester.getTopLeft(action0), const Offset(152, 130));
expect(tester.getTopLeft(action1), const Offset(80, 130));
expect(tester.getTopLeft(action2), const Offset(8, 130));
});
testWidgets('Action widgets layout when presented by ScaffoldMessenger', (WidgetTester tester) async {
// This regression test ensures that the action widgets layout matches what
// it was, before ButtonBar was replaced by OverflowBar.
Widget buildFrame(int actionCount, TextDirection textDirection) {
return MaterialApp(
home: Directionality(
textDirection: textDirection,
child: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: const ValueKey<String>('tap-target'),
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const SizedBox(width: 100, height: 100),
actions: List<Widget>.generate(actionCount, (int index) {
if (index == 0) {
return SizedBox(
width: 64,
height: 48,
key: ValueKey<int>(index),
child: GestureDetector(
key: const ValueKey<String>('dismiss-target'),
onTap: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
);
}
return SizedBox(
width: 64,
height: 48,
key: ValueKey<int>(index),
);
}),
));
},
);
}
),
),
),
);
}
final Finder tapTarget = find.byKey(const ValueKey<String>('tap-target'));
final Finder dismissTarget = find.byKey(const ValueKey<String>('dismiss-target'));
final Finder action0 = find.byKey(const ValueKey<int>(0));
final Finder action1 = find.byKey(const ValueKey<int>(1));
final Finder action2 = find.byKey(const ValueKey<int>(2));
// The action coordinates that follow were obtained by running
// the test code, before ButtonBar was replaced by OverflowBar.
await tester.pumpWidget(buildFrame(1, TextDirection.ltr));
await tester.tap(tapTarget);
await tester.pumpAndSettle();
expect(tester.getTopLeft(action0), const Offset(728, 28));
await tester.tap(dismissTarget);
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(1, TextDirection.rtl));
await tester.tap(tapTarget);
await tester.pumpAndSettle();
expect(tester.getTopLeft(action0), const Offset(8, 28));
await tester.tap(dismissTarget);
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(3, TextDirection.ltr));
await tester.tap(tapTarget);
await tester.pumpAndSettle();
expect(tester.getTopLeft(action0), const Offset(584, 130));
expect(tester.getTopLeft(action1), const Offset(656, 130));
expect(tester.getTopLeft(action2), const Offset(728, 130));
await tester.tap(dismissTarget);
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(3, TextDirection.rtl));
await tester.tap(tapTarget);
await tester.pumpAndSettle();
expect(tester.getTopLeft(action0), const Offset(152, 130));
expect(tester.getTopLeft(action1), const Offset(80, 130));
expect(tester.getTopLeft(action2), const Offset(8, 130));
await tester.tap(dismissTarget);
await tester.pumpAndSettle();
});
testWidgets('Action widgets layout with overflow', (WidgetTester tester) async {
// This regression test ensures that the action widgets layout matches what
// it was, before ButtonBar was replaced by OverflowBar.
const int actionCount = 4;
Widget buildFrame(TextDirection textDirection) {
return MaterialApp(
home: Directionality(
textDirection: textDirection,
child: MaterialBanner(
content: const SizedBox(width: 100, height: 100),
actions: List<Widget>.generate(actionCount, (int index) {
return SizedBox(
width: 200,
height: 10,
key: ValueKey<int>(index),
);
}),
),
),
);
}
// The action coordinates that follow were obtained by running
// the test code, before ButtonBar was replaced by OverflowBar.
await tester.pumpWidget(buildFrame(TextDirection.ltr));
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(592, 134.0 + index * 10));
}
await tester.pumpWidget(buildFrame(TextDirection.rtl));
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(8, 134.0 + index * 10));
}
});
testWidgets('Action widgets layout with overflow when presented by ScaffoldMessenger', (WidgetTester tester) async {
// This regression test ensures that the action widgets layout matches what
// it was, before ButtonBar was replaced by OverflowBar.
const int actionCount = 4;
Widget buildFrame(TextDirection textDirection) {
return MaterialApp(
home: Directionality(
textDirection: textDirection,
child: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: const ValueKey<String>('tap-target'),
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
content: const SizedBox(width: 100, height: 100),
actions: List<Widget>.generate(actionCount, (int index) {
if (index == 0) {
return SizedBox(
width: 200,
height: 10,
key: ValueKey<int>(index),
child: GestureDetector(
key: const ValueKey<String>('dismiss-target'),
onTap: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
);
}
return SizedBox(
width: 200,
height: 10,
key: ValueKey<int>(index),
);
}),
));
},
);
}
),
),
),
);
}
// The action coordinates that follow were obtained by running
// the test code, before ButtonBar was replaced by OverflowBar.
final Finder tapTarget = find.byKey(const ValueKey<String>('tap-target'));
final Finder dismissTarget = find.byKey(const ValueKey<String>('dismiss-target'));
await tester.pumpWidget(buildFrame(TextDirection.ltr));
await tester.tap(tapTarget);
await tester.pumpAndSettle();
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(592, 134.0 + index * 10));
}
await tester.tap(dismissTarget);
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(TextDirection.rtl));
await tester.tap(tapTarget);
await tester.pumpAndSettle();
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(8, 134.0 + index * 10));
}
await tester.tap(dismissTarget);
await tester.pumpAndSettle();
});
testWidgets('[overflowAlignment] test', (WidgetTester tester) async {
const int actionCount = 4;
Widget buildFrame(TextDirection textDirection, OverflowBarAlignment overflowAlignment) {
return MaterialApp(
home: Directionality(
textDirection: textDirection,
child: MaterialBanner(
overflowAlignment: overflowAlignment,
content: const SizedBox(width: 100, height: 100),
actions: List<Widget>.generate(actionCount, (int index) {
return SizedBox(
width: 200,
height: 10,
key: ValueKey<int>(index),
);
}),
),
),
);
}
await tester.pumpWidget(buildFrame(TextDirection.ltr, OverflowBarAlignment.start));
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(8, 134.0 + index * 10));
}
await tester.pumpWidget(buildFrame(TextDirection.ltr, OverflowBarAlignment.center));
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(300, 134.0 + index * 10));
}
await tester.pumpWidget(buildFrame(TextDirection.ltr, OverflowBarAlignment.end));
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(592, 134.0 + index * 10));
}
});
testWidgets('[overflowAlignment] test when presented by ScaffoldMessenger', (WidgetTester tester) async {
const int actionCount = 4;
Widget buildFrame(TextDirection textDirection, OverflowBarAlignment overflowAlignment) {
return MaterialApp(
home: Directionality(
textDirection: textDirection,
child: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
key: const ValueKey<String>('tap-target'),
onTap: () {
ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner(
overflowAlignment: overflowAlignment,
content: const SizedBox(width: 100, height: 100),
actions: List<Widget>.generate(actionCount, (int index) {
if (index == 0) {
return SizedBox(
width: 200,
height: 10,
key: ValueKey<int>(index),
child: GestureDetector(
key: const ValueKey<String>('dismiss-target'),
onTap: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
),
);
}
return SizedBox(
width: 200,
height: 10,
key: ValueKey<int>(index),
);
}),
));
},
);
}
),
),
),
);
}
final Finder tapTarget = find.byKey(const ValueKey<String>('tap-target'));
final Finder dismissTarget = find.byKey(const ValueKey<String>('dismiss-target'));
await tester.pumpWidget(buildFrame(TextDirection.ltr, OverflowBarAlignment.start));
await tester.tap(tapTarget);
await tester.pumpAndSettle();
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(8, 134.0 + index * 10));
}
await tester.tap(dismissTarget);
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(TextDirection.ltr, OverflowBarAlignment.center));
await tester.tap(tapTarget);
await tester.pumpAndSettle();
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(300, 134.0 + index * 10));
}
await tester.tap(dismissTarget);
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(TextDirection.ltr, OverflowBarAlignment.end));
await tester.tap(tapTarget);
await tester.pumpAndSettle();
for (int index = 0; index < actionCount; index += 1) {
expect(tester.getTopLeft(find.byKey(ValueKey<int>(index))), Offset(592, 134.0 + index * 10));
}
await tester.tap(dismissTarget);
await tester.pumpAndSettle();
});
testWidgets('ScaffoldMessenger will alert for MaterialBanners that cannot be presented', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/103004
await tester.pumpWidget(const MaterialApp(
home: Center(),
));
final ScaffoldMessengerState scaffoldMessengerState = tester.state<ScaffoldMessengerState>(
find.byType(ScaffoldMessenger),
);
expect(
() {
scaffoldMessengerState.showMaterialBanner(const MaterialBanner(
content: Text('Banner'),
actions: <Widget>[],
));
},
throwsA(
isA<AssertionError>().having(
(AssertionError error) => error.toString(),
'description',
contains(
'ScaffoldMessenger.showMaterialBanner was called, but there are currently '
'no descendant Scaffolds to present to.'
)
),
),
);
});
testWidgets('Custom Margin respected', (WidgetTester tester) async {
const EdgeInsets margin = EdgeInsets.all(30);
await tester.pumpWidget(
MaterialApp(
home: MaterialBanner(
margin: margin,
content: const Text('I am a banner'),
actions: <Widget>[
TextButton(
child: const Text('Action'),
onPressed: () { },
),
],
),
),
);
final Offset topLeft = tester.getTopLeft(find.descendant(of: find.byType(MaterialBanner), matching: find.byType(Material)).first);
/// Compare the offset of banner from top left
expect(topLeft.dx, margin.left);
});
}
Material _getMaterialFromBanner(WidgetTester tester) {
return tester.widget<Material>(find.descendant(of: find.byType(MaterialBanner), matching: find.byType(Material)).first);
}
Material _getMaterialFromText(WidgetTester tester, String text) {
return tester.widget<Material>(find.widgetWithText(Material, text).first);
}
RenderParagraph _getTextRenderObjectFromDialog(WidgetTester tester, String text) {
return tester.element<StatelessElement>(find.descendant(of: find.byType(MaterialBanner), matching: find.text(text))).renderObject! as RenderParagraph;
}
bool _sizeAlmostEqual(Size a, Size b, {double maxDiff=0.05}) {
return (a.width - b.width).abs() <= maxDiff && (a.height - b.height).abs() <= maxDiff;
}
| flutter/packages/flutter/test/material/banner_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/banner_test.dart",
"repo_id": "flutter",
"token_count": 20882
} | 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.
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/gestures/constants.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() {
final ThemeData theme = ThemeData();
setUp(() {
debugResetSemanticsIdCounter();
});
testWidgets('Checkbox size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async {
await tester.pumpWidget(
Theme(
data: theme.copyWith(materialTapTargetSize: MaterialTapTargetSize.padded),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Checkbox(
value: true,
onChanged: (bool? newValue) { },
),
),
),
),
),
);
expect(tester.getSize(find.byType(Checkbox)), const Size(48.0, 48.0));
await tester.pumpWidget(
Theme(
data: theme.copyWith(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Checkbox(
value: true,
onChanged: (bool? newValue) { },
),
),
),
),
),
);
expect(tester.getSize(find.byType(Checkbox)), const Size(40.0, 40.0));
});
testWidgets('Checkbox semantics', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(Theme(
data: theme,
child: Material(
child: Checkbox(
value: false,
onChanged: (bool? b) { },
),
),
));
expect(tester.getSemantics(find.byType(Focus)), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isEnabled: true,
hasTapAction: true,
isFocusable: true,
));
await tester.pumpWidget(Theme(
data: theme,
child: Material(
child: Checkbox(
value: true,
onChanged: (bool? b) { },
),
),
));
expect(tester.getSemantics(find.byType(Focus)), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isChecked: true,
isEnabled: true,
hasTapAction: true,
isFocusable: true,
));
await tester.pumpWidget(Theme(
data: theme,
child: const Material(
child: Checkbox(
value: false,
onChanged: null,
),
),
));
expect(tester.getSemantics(find.byType(Checkbox)), 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(Checkbox)), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
));
await tester.pumpWidget(Theme(
data: theme,
child: const Material(
child: Checkbox(
value: true,
onChanged: null,
),
),
));
expect(tester.getSemantics(find.byType(Checkbox)), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isChecked: true,
));
await tester.pumpWidget(Theme(
data: theme,
child: const Material(
child: Checkbox(
value: null,
tristate: true,
onChanged: null,
),
),
));
expect(tester.getSemantics(find.byType(Checkbox)), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isCheckStateMixed: true,
));
await tester.pumpWidget(Theme(
data: theme,
child: const Material(
child: Checkbox(
value: true,
tristate: true,
onChanged: null,
),
),
));
expect(tester.getSemantics(find.byType(Checkbox)), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isChecked: true,
));
await tester.pumpWidget(Theme(
data: theme,
child: const Material(
child: Checkbox(
value: false,
tristate: true,
onChanged: null,
),
),
));
expect(tester.getSemantics(find.byType(Checkbox)), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
));
// Check if semanticLabel is there.
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Theme(
data: theme,
child: Material(
child: Checkbox(
semanticLabel: 'checkbox',
value: true,
onChanged: (bool? b) { },
),
),
),
));
expect(tester.getSemantics(find.byType(Focus)), matchesSemantics(
label: 'checkbox',
textDirection: TextDirection.ltr,
hasCheckedState: true,
hasEnabledState: true,
isChecked: true,
isEnabled: true,
hasTapAction: true,
isFocusable: true,
));
handle.dispose();
});
testWidgets('Can wrap Checkbox with Semantics', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(Theme(
data: theme,
child: Material(
child: Semantics(
label: 'foo',
textDirection: TextDirection.ltr,
child: Checkbox(
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('Checkbox tristate: true', (WidgetTester tester) async {
bool? checkBoxValue;
await tester.pumpWidget(
Theme(
data: theme,
child: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Checkbox(
tristate: true,
value: checkBoxValue,
onChanged: (bool? value) {
setState(() {
checkBoxValue = value;
});
},
);
},
),
),
),
);
expect(tester.widget<Checkbox>(find.byType(Checkbox)).value, null);
await tester.tap(find.byType(Checkbox));
await tester.pumpAndSettle();
expect(checkBoxValue, false);
await tester.tap(find.byType(Checkbox));
await tester.pumpAndSettle();
expect(checkBoxValue, true);
await tester.tap(find.byType(Checkbox));
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(
Theme(
data: theme,
child: Material(
child: Checkbox(
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(
Theme(
data: theme,
child: Material(
child: Checkbox(
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(
Theme(
data: theme,
child: Material(
child: Checkbox(
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(
Theme(
data: theme,
child: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: checkboxValue,
onChanged: (bool? value) {
setState(() {
checkboxValue = value;
});
},
);
},
),
),
),
);
await tester.tap(find.byType(Checkbox));
final RenderObject object = tester.firstRenderObject(find.byType(Checkbox));
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('Material2 - Checkbox tristate rendering, programmatic transitions', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
Widget buildFrame(bool? checkboxValue) {
return Theme(
data: theme,
child: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Checkbox(
tristate: true,
value: checkboxValue,
onChanged: (bool? value) { },
);
},
),
),
);
}
RenderBox getCheckboxRenderer() {
return tester.renderObject<RenderBox>(find.byType(Checkbox));
}
await tester.pumpWidget(buildFrame(false));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: Colors.transparent)); // paint transparent border
expect(getCheckboxRenderer(), isNot(paints..line())); // null is rendered as a line (a "dash")
expect(getCheckboxRenderer(), paints..drrect()); // empty checkbox
await tester.pumpWidget(buildFrame(true));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(),
paints
..path(color: theme.colorScheme.secondary)
..path(color: const Color(0xFFFFFFFF))
); // checkmark is rendered as a path
await tester.pumpWidget(buildFrame(false));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: Colors.transparent)); // paint transparent border
expect(getCheckboxRenderer(), isNot(paints..line())); // null is rendered as a line (a "dash")
expect(getCheckboxRenderer(), paints..drrect()); // empty checkbox
await tester.pumpWidget(buildFrame(null));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..line()); // null is rendered as a line (a "dash")
await tester.pumpWidget(buildFrame(true));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(),
paints
..path(color: theme.colorScheme.secondary)
..path(color: const Color(0xFFFFFFFF))
); // checkmark is rendered as a path
await tester.pumpWidget(buildFrame(null));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..line()); // null is rendered as a line (a "dash")
});
testWidgets('Material3 - Checkbox tristate rendering, programmatic transitions', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
Widget buildFrame(bool? checkboxValue) {
return Theme(
data: theme,
child: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Checkbox(
tristate: true,
value: checkboxValue,
onChanged: (bool? value) { },
);
},
),
),
);
}
RenderBox getCheckboxRenderer() {
return tester.renderObject<RenderBox>(find.byType(Checkbox));
}
await tester.pumpWidget(buildFrame(false));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: Colors.transparent)); // paint transparent border
expect(getCheckboxRenderer(), isNot(paints..line())); // null is rendered as a line (a "dash")
expect(getCheckboxRenderer(), paints..drrect()); // empty checkbox
await tester.pumpWidget(buildFrame(true));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(),
paints
..path(color: theme.colorScheme.primary)
..path(color: theme.colorScheme.onPrimary)
); // checkmark is rendered as a path
await tester.pumpWidget(buildFrame(false));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: Colors.transparent)); // paint transparent border
expect(getCheckboxRenderer(), isNot(paints..line())); // null is rendered as a line (a "dash")
expect(getCheckboxRenderer(), paints..drrect()); // empty checkbox
await tester.pumpWidget(buildFrame(null));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..line()); // null is rendered as a line (a "dash")
await tester.pumpWidget(buildFrame(true));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(),
paints
..path(color: theme.colorScheme.primary)
..path(color: theme.colorScheme.onPrimary)
); // checkmark is rendered as a path
await tester.pumpWidget(buildFrame(null));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..line()); // null is rendered as a line (a "dash")
});
testWidgets('Material2 - Checkbox color rendering', (WidgetTester tester) async {
ThemeData theme = ThemeData(useMaterial3: false);
const Color borderColor = Color(0xff2196f3);
Color checkColor = const Color(0xffFFFFFF);
Color activeColor;
Widget buildFrame({Color? activeColor, Color? checkColor, ThemeData? themeData}) {
return Material(
child: Theme(
data: themeData ?? theme,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: true,
activeColor: activeColor,
checkColor: checkColor,
onChanged: (bool? value) { },
);
},
),
),
);
}
RenderBox getCheckboxRenderer() {
return tester.renderObject<RenderBox>(find.byType(Checkbox));
}
await tester.pumpWidget(buildFrame(checkColor: checkColor));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: borderColor)..path(color: checkColor)); // paints's color is 0xFFFFFFFF (default color)
checkColor = const Color(0xFF000000);
await tester.pumpWidget(buildFrame(checkColor: checkColor));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: borderColor)..path(color: checkColor)); // paints's color is 0xFF000000 (params)
activeColor = const Color(0xFF00FF00);
final ColorScheme colorScheme = const ColorScheme.light().copyWith(secondary: activeColor);
theme = theme.copyWith(colorScheme: colorScheme);
await tester.pumpWidget(buildFrame(
themeData: theme),
);
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: activeColor)); // paints's color is 0xFF00FF00 (theme)
activeColor = const Color(0xFF000000);
await tester.pumpWidget(buildFrame(activeColor: activeColor));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: activeColor));
});
testWidgets('Material3 - Checkbox color rendering', (WidgetTester tester) async {
ThemeData theme = ThemeData(useMaterial3: true);
const Color borderColor = Color(0xFF6750A4);
Color checkColor = const Color(0xffFFFFFF);
Color activeColor;
Widget buildFrame({Color? activeColor, Color? checkColor, ThemeData? themeData}) {
return Material(
child: Theme(
data: themeData ?? theme,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: true,
activeColor: activeColor,
checkColor: checkColor,
onChanged: (bool? value) { },
);
},
),
),
);
}
RenderBox getCheckboxRenderer() {
return tester.renderObject<RenderBox>(find.byType(Checkbox));
}
await tester.pumpWidget(buildFrame(checkColor: checkColor));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: borderColor)..path(color: checkColor)); // paints's color is 0xFFFFFFFF (default color)
checkColor = const Color(0xFF000000);
await tester.pumpWidget(buildFrame(checkColor: checkColor));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: borderColor)..path(color: checkColor)); // paints's color is 0xFF000000 (params)
activeColor = const Color(0xFF00FF00);
final ColorScheme colorScheme = const ColorScheme.light().copyWith(primary: activeColor);
theme = theme.copyWith(colorScheme: colorScheme);
await tester.pumpWidget(buildFrame(themeData: theme));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: activeColor)); // paints's color is 0xFF00FF00 (theme)
activeColor = const Color(0xFF000000);
await tester.pumpWidget(buildFrame(activeColor: activeColor));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: activeColor));
});
testWidgets('Material2 - Checkbox is focusable and has correct focus color', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Checkbox');
addTearDown(focusNode.dispose);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool? value = true;
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: value,
onChanged: enabled ? (bool? newValue) {
setState(() {
value = newValue;
});
} : null,
focusColor: Colors.orange[500],
autofocus: true,
focusNode: focusNode,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(color: Colors.orange[500])
..path(color: const Color(0xff2196f3))
..path(color: Colors.white)
);
// Check the false value.
value = false;
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(color: Colors.orange[500])
..drrect(
color: const Color(0x8a000000),
outer: RRect.fromLTRBR(15.0, 15.0, 33.0, 33.0, const Radius.circular(1.0)),
inner: RRect.fromLTRBR(17.0, 17.0, 31.0, 31.0, Radius.zero),
),
);
// Check what happens when disabled.
value = false;
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..drrect(
color: const Color(0x61000000),
outer: RRect.fromLTRBR(15.0, 15.0, 33.0, 33.0, const Radius.circular(1.0)),
inner: RRect.fromLTRBR(17.0, 17.0, 31.0, 31.0, Radius.zero),
),
);
});
testWidgets('Material3 - Checkbox is focusable and has correct focus color', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Checkbox');
addTearDown(focusNode.dispose);
final ThemeData theme = ThemeData(useMaterial3: true);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool? value = true;
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: value,
onChanged: enabled ? (bool? newValue) {
setState(() {
value = newValue;
});
} : null,
focusColor: Colors.orange[500],
autofocus: true,
focusNode: focusNode,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(color: Colors.orange[500])
..path(color: theme.colorScheme.primary)
..path(color: theme.colorScheme.onPrimary)
);
// Check the false value.
value = false;
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(color: Colors.orange[500])
..drrect(
color: theme.colorScheme.onSurface,
outer: RRect.fromLTRBR(15.0, 15.0, 33.0, 33.0, const Radius.circular(2.0)),
inner: RRect.fromLTRBR(17.0, 17.0, 31.0, 31.0, Radius.zero),
),
);
// Check what happens when disabled.
value = false;
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..drrect(
color: theme.colorScheme.onSurface.withOpacity(0.38),
outer: RRect.fromLTRBR(15.0, 15.0, 33.0, 33.0, const Radius.circular(2.0)),
inner: RRect.fromLTRBR(17.0, 17.0, 31.0, 31.0, Radius.zero),
),
);
});
testWidgets('Checkbox with splash radius set', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const double splashRadius = 30;
Widget buildApp() {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: false,
onChanged: (bool? newValue) {},
focusColor: Colors.orange[500],
autofocus: true,
splashRadius: splashRadius,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..circle(color: Colors.orange[500], radius: splashRadius),
);
});
testWidgets('Checkbox starts the splash in center, even when tap is on the corner', (WidgetTester tester) async {
Widget buildApp() {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: false,
onChanged: (bool? newValue) {},
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
final Offset checkboxTopLeftGlobal = tester.getTopLeft(find.byType(Checkbox));
final Offset checkboxCenterGlobal = tester.getCenter(find.byType(Checkbox));
final Offset checkboxCenterLocal = checkboxCenterGlobal - checkboxTopLeftGlobal;
final TestGesture gesture = await tester.startGesture(checkboxTopLeftGlobal);
await tester.pump();
// Wait for the splash to be drawn, but not long enough for it to animate towards the center, since
// we want to catch it in its starting position.
await tester.pump(const Duration(milliseconds: 1));
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..circle(x: checkboxCenterLocal.dx, y: checkboxCenterLocal.dy),
);
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
});
testWidgets('Material2 - Checkbox can be hovered and has correct hover color', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool? value = true;
final ThemeData theme = ThemeData(useMaterial3: false);
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: value,
onChanged: enabled ? (bool? newValue) {
setState(() {
value = newValue;
});
} : null,
hoverColor: Colors.orange[500],
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..path(color: const Color(0xff2196f3))
..path(color: const Color(0xffffffff), style: PaintingStyle.stroke, strokeWidth: 2.0),
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byType(Checkbox)));
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..path(color: const Color(0xff2196f3))
..path(color: const Color(0xffffffff), style: PaintingStyle.stroke, strokeWidth: 2.0),
);
// Check what happens when disabled.
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..path(color: const Color(0x61000000))
..path(color: const Color(0xffffffff), style: PaintingStyle.stroke, strokeWidth: 2.0),
);
});
testWidgets('Material3 - Checkbox can be hovered and has correct hover color', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool? value = true;
final ThemeData theme = ThemeData(useMaterial3: true);
Widget buildApp({bool enabled = true}) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: value,
onChanged: enabled ? (bool? newValue) {
setState(() {
value = newValue;
});
} : null,
hoverColor: Colors.orange[500],
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..path(color: const Color(0xff6750a4))
..path(color: theme.colorScheme.onPrimary, style: PaintingStyle.stroke, strokeWidth: 2.0),
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byType(Checkbox)));
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..path(color: const Color(0xff6750a4))
..path(color: theme.colorScheme.onPrimary, style: PaintingStyle.stroke, strokeWidth: 2.0),
);
// Check what happens when disabled.
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..path(color: theme.colorScheme.onSurface.withOpacity(0.38))
..path(color: theme.colorScheme.surface, style: PaintingStyle.stroke, strokeWidth: 2.0),
);
});
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 MaterialApp(
theme: theme,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: value,
onChanged: enabled ? (bool? newValue) {
setState(() {
value = newValue;
});
} : null,
focusColor: Colors.orange[500],
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 responds to density changes.', (WidgetTester tester) async {
const Key key = Key('test');
Future<void> buildTest(VisualDensity visualDensity) async {
return tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Checkbox(
visualDensity: visualDensity,
key: key,
onChanged: (bool? value) {},
value: true,
),
),
),
),
);
}
await buildTest(VisualDensity.standard);
final RenderBox box = tester.renderObject(find.byKey(key));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(48, 48)));
await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(60, 60)));
await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(36, 36)));
await buildTest(const VisualDensity(horizontal: 3.0, vertical: -3.0));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(60, 36)));
});
testWidgets('Checkbox stops hover animation when removed from the tree.', (WidgetTester tester) async {
const Key checkboxKey = Key('checkbox');
bool? checkboxVal = true;
await tester.pumpWidget(
Theme(
data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.padded),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: StatefulBuilder(
builder: (_, StateSetter setState) => Checkbox(
key: checkboxKey,
value: checkboxVal,
onChanged: (bool? newValue) => setState(() {checkboxVal = newValue;}),
),
),
),
),
),
),
);
expect(find.byKey(checkboxKey), findsOneWidget);
final Offset checkboxCenter = tester.getCenter(find.byKey(checkboxKey));
final TestGesture testGesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await testGesture.moveTo(checkboxCenter);
await tester.pump(); // start animation
await tester.pump(const Duration(milliseconds: 25)); // hover animation duration is 50 ms. It is half-way.
await tester.pumpWidget(
Theme(
data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.padded),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: Container(),
),
),
),
),
);
// Hover animation should not trigger an exception when the checkbox is removed
// before the hover animation should complete.
expect(tester.takeException(), isNull);
await testGesture.removePointer();
});
testWidgets('Checkbox changes mouse cursor when hovered', (WidgetTester tester) async {
// Test Checkbox() constructor
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: Checkbox(
mouseCursor: SystemMouseCursors.text,
value: true,
onChanged: (_) {},
),
),
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(Checkbox)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test default cursor
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: Checkbox(
value: true,
onChanged: (_) {},
),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test default cursor when disabled
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: Checkbox(
value: true,
onChanged: null,
),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
// Test cursor when tristate
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: Checkbox(
value: null,
tristate: true,
onChanged: null,
mouseCursor: _SelectedGrabMouseCursor(),
),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab);
await tester.pumpAndSettle();
});
testWidgets('Checkbox fill color resolves in enabled/disabled states', (WidgetTester tester) async {
const Color activeEnabledFillColor = Color(0xFF000001);
const Color activeDisabledFillColor = Color(0xFF000002);
Color getFillColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return activeDisabledFillColor;
}
return activeEnabledFillColor;
}
final MaterialStateProperty<Color> fillColor =
MaterialStateColor.resolveWith(getFillColor);
Widget buildFrame({required bool enabled}) {
return Material(
child: Theme(
data: theme,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: true,
fillColor: fillColor,
onChanged: enabled ? (bool? value) { } : null,
);
},
),
),
);
}
RenderBox getCheckboxRenderer() {
return tester.renderObject<RenderBox>(find.byType(Checkbox));
}
await tester.pumpWidget(buildFrame(enabled: true));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: activeEnabledFillColor));
await tester.pumpWidget(buildFrame(enabled: false));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: activeDisabledFillColor));
});
testWidgets('Checkbox fill color resolves in hovered/focused states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'checkbox');
addTearDown(focusNode.dispose);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredFillColor = Color(0xFF000001);
const Color focusedFillColor = Color(0xFF000002);
Color getFillColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoveredFillColor;
}
if (states.contains(MaterialState.focused)) {
return focusedFillColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> fillColor =
MaterialStateColor.resolveWith(getFillColor);
Widget buildFrame() {
return Material(
child: Theme(
data: theme,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Checkbox(
focusNode: focusNode,
autofocus: true,
value: true,
fillColor: fillColor,
onChanged: (bool? value) { },
);
},
),
),
);
}
RenderBox getCheckboxRenderer() {
return tester.renderObject<RenderBox>(find.byType(Checkbox));
}
await tester.pumpWidget(buildFrame());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(getCheckboxRenderer(), paints..path(color: focusedFillColor));
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..path(color: hoveredFillColor));
});
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 MaterialApp(
theme: theme,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: false,
onChanged: (bool? newValue) {},
shape: roundedRectangleBorder,
side: side,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(tester.widget<Checkbox>(find.byType(Checkbox)).shape, roundedRectangleBorder);
expect(tester.widget<Checkbox>(find.byType(Checkbox)).side, side);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..drrect(
color: const Color(0xfff44336),
outer: RRect.fromLTRBR(15.0, 15.0, 33.0, 33.0, const Radius.circular(5)),
inner: RRect.fromLTRBR(19.0, 19.0, 29.0, 29.0, const Radius.circular(1)),
),
);
});
testWidgets('Material2 - Checkbox default overlay color in active/pressed/focused/hovered states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Checkbox');
addTearDown(focusNode.dispose);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final ThemeData theme = ThemeData(useMaterial3: false);
final ColorScheme colors = theme.colorScheme;
Widget buildCheckbox({bool active = false, bool focused = false}) {
return MaterialApp(
theme: theme,
home: Scaffold(
body: Checkbox(
focusNode: focusNode,
autofocus: focused,
value: active,
onChanged: (_) { },
),
),
);
}
await tester.pumpWidget(buildCheckbox());
final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(color: theme.unselectedWidgetColor.withAlpha(kRadialReactionAlpha)),
reason: 'Default inactive pressed Checkbox should have overlay color from default fillColor',
);
await tester.pumpWidget(buildCheckbox(active: true));
final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(color: colors.secondary.withAlpha(kRadialReactionAlpha)),
reason: 'Default active pressed Checkbox should have overlay color from default fillColor',
);
await tester.pumpWidget(Container()); // reset test
await tester.pumpWidget(buildCheckbox(focused: true));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..circle(color: theme.focusColor),
reason: 'Focused Checkbox should use default focused overlay color',
);
await tester.pumpWidget(Container()); // reset test
await tester.pumpWidget(buildCheckbox());
final TestGesture gesture3 = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture3.addPointer();
await gesture3.moveTo(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..circle(color: theme.hoverColor),
reason: 'Hovered Checkbox should use default hovered overlay color',
);
// Finish gestures to release resources.
await gesture1.up();
await gesture2.up();
await tester.pumpAndSettle();
});
testWidgets('Material3 - Checkbox default overlay color in active/pressed/focused/hovered states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Checkbox');
addTearDown(focusNode.dispose);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final ThemeData theme = ThemeData(useMaterial3: true);
final ColorScheme colors = theme.colorScheme;
Widget buildCheckbox({bool active = false, bool focused = false}) {
return MaterialApp(
theme: theme,
home: Scaffold(
body: Checkbox(
focusNode: focusNode,
autofocus: focused,
value: active,
onChanged: (_) { },
),
),
);
}
await tester.pumpWidget(buildCheckbox());
final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..circle(color: colors.primary.withOpacity(0.1)),
reason: 'Default inactive pressed Checkbox should have overlay color from default fillColor',
);
await tester.pumpWidget(buildCheckbox(active: true));
final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..circle(color: colors.onSurface.withOpacity(0.1)),
reason: 'Default active pressed Checkbox should have overlay color from default fillColor',
);
await tester.pumpWidget(Container()); // reset test
await tester.pumpWidget(buildCheckbox(focused: true));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..circle(color: colors.onSurface.withOpacity(0.1)),
reason: 'Focused Checkbox should use default focused overlay color',
);
await tester.pumpWidget(Container()); // reset test
await tester.pumpWidget(buildCheckbox());
final TestGesture gesture3 = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture3.addPointer();
await gesture3.moveTo(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..circle(color: colors.onSurface.withOpacity(0.08)),
reason: 'Hovered Checkbox should use default hovered overlay color',
);
// Finish gestures to release resources.
await gesture1.up();
await gesture2.up();
await tester.pumpAndSettle();
});
testWidgets('Checkbox overlay color resolves in active/pressed/focused/hovered states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Checkbox');
addTearDown(focusNode.dispose);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color fillColor = Color(0xFF000000);
const Color activePressedOverlayColor = Color(0xFF000001);
const Color inactivePressedOverlayColor = Color(0xFF000002);
const Color hoverOverlayColor = Color(0xFF000003);
const Color focusOverlayColor = Color(0xFF000004);
const Color hoverColor = Color(0xFF000005);
const Color focusColor = Color(0xFF000006);
Color? getOverlayColor(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
if (states.contains(MaterialState.selected)) {
return activePressedOverlayColor;
}
return inactivePressedOverlayColor;
}
if (states.contains(MaterialState.hovered)) {
return hoverOverlayColor;
}
if (states.contains(MaterialState.focused)) {
return focusOverlayColor;
}
return null;
}
const double splashRadius = 24.0;
Widget buildCheckbox({bool active = false, bool focused = false, bool useOverlay = true}) {
return MaterialApp(
theme: theme,
home: Scaffold(
body: Checkbox(
focusNode: focusNode,
autofocus: focused,
value: active,
onChanged: (_) { },
fillColor: const MaterialStatePropertyAll<Color>(fillColor),
overlayColor: useOverlay ? MaterialStateProperty.resolveWith(getOverlayColor) : null,
hoverColor: hoverColor,
focusColor: focusColor,
splashRadius: splashRadius,
),
),
);
}
await tester.pumpWidget(buildCheckbox(useOverlay: false));
final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: fillColor.withAlpha(kRadialReactionAlpha),
radius: splashRadius,
),
reason: 'Default inactive pressed Checkbox should have overlay color from fillColor',
);
await tester.pumpWidget(buildCheckbox(active: true, useOverlay: false));
final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: fillColor.withAlpha(kRadialReactionAlpha),
radius: splashRadius,
),
reason: 'Default active pressed Checkbox should have overlay color from fillColor',
);
await tester.pumpWidget(buildCheckbox());
final TestGesture gesture3 = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: inactivePressedOverlayColor,
radius: splashRadius,
),
reason: 'Inactive pressed Checkbox should have overlay color: $inactivePressedOverlayColor',
);
await tester.pumpWidget(buildCheckbox(active: true));
final TestGesture gesture4 = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: activePressedOverlayColor,
radius: splashRadius,
),
reason: 'Active pressed Checkbox should have overlay color: $activePressedOverlayColor',
);
await tester.pumpWidget(Container()); // reset test
await tester.pumpWidget(buildCheckbox(focused: true));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: focusOverlayColor,
radius: splashRadius,
),
reason: 'Focused Checkbox should use overlay color $focusOverlayColor over $focusColor',
);
// Start hovering
final TestGesture gesture5 = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture5.addPointer();
await gesture5.moveTo(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: hoverOverlayColor,
radius: splashRadius,
),
reason: 'Hovered Checkbox should use overlay color $hoverOverlayColor over $hoverColor',
);
// Finish gestures to release resources.
await gesture1.up();
await gesture2.up();
await gesture3.up();
await gesture4.up();
await tester.pumpAndSettle();
});
testWidgets('Tristate Checkbox overlay color resolves in pressed active/inactive states', (WidgetTester tester) async {
const Color activePressedOverlayColor = Color(0xFF000001);
const Color inactivePressedOverlayColor = Color(0xFF000002);
Color? getOverlayColor(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
if (states.contains(MaterialState.selected)) {
return activePressedOverlayColor;
}
return inactivePressedOverlayColor;
}
return null;
}
const double splashRadius = 24.0;
TestGesture gesture;
bool? value = false;
Widget buildTristateCheckbox() {
return MaterialApp(
theme: theme,
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: value,
tristate: true,
onChanged: (bool? v) {
setState(() {
value = v;
});
},
overlayColor: MaterialStateProperty.resolveWith(getOverlayColor),
splashRadius: splashRadius,
);
},
),
),
);
}
// The checkbox is inactive.
await tester.pumpWidget(buildTristateCheckbox());
gesture = await tester.press(find.byType(Checkbox));
await tester.pumpAndSettle();
expect(value, false);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: inactivePressedOverlayColor,
radius: splashRadius,
),
reason: 'Inactive pressed Checkbox should have overlay color: $inactivePressedOverlayColor',
);
// The checkbox is active.
await gesture.up();
gesture = await tester.press(find.byType(Checkbox));
await tester.pumpAndSettle();
expect(value, true);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: activePressedOverlayColor,
radius: splashRadius,
),
reason: 'Active pressed Checkbox should have overlay color: $activePressedOverlayColor',
);
// The checkbox is active in tri-state.
await gesture.up();
gesture = await tester.press(find.byType(Checkbox));
await tester.pumpAndSettle();
expect(value, null);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: activePressedOverlayColor,
radius: splashRadius,
),
reason: 'Active (tristate) pressed Checkbox should have overlay color: $activePressedOverlayColor',
);
// The checkbox is inactive again.
await gesture.up();
gesture = await tester.press(find.byType(Checkbox));
await tester.pumpAndSettle();
expect(value, false);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(
color: inactivePressedOverlayColor,
radius: splashRadius,
),
reason: 'Inactive pressed Checkbox should have overlay color: $inactivePressedOverlayColor',
);
await gesture.up();
});
testWidgets('Do not crash when widget disappears while pointer is down', (WidgetTester tester) async {
Widget buildCheckbox(bool show) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: show ? Checkbox(value: true, onChanged: (_) { }) : Container(),
),
),
);
}
await tester.pumpWidget(buildCheckbox(true));
final Offset center = tester.getCenter(find.byType(Checkbox));
// Put a pointer down on the screen.
final TestGesture gesture = await tester.startGesture(center);
await tester.pump();
// While the pointer is down, the widget disappears.
await tester.pumpWidget(buildCheckbox(false));
expect(find.byType(Checkbox), findsNothing);
// Release pointer after widget disappeared.
await gesture.up();
});
testWidgets('Checkbox BorderSide side only applies when unselected in M2', (WidgetTester tester) async {
const Color borderColor = Color(0xfff44336);
const Color activeColor = Color(0xff123456);
const BorderSide side = BorderSide(
width: 4,
color: borderColor,
);
Widget buildApp({ bool? value, bool enabled = true }) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: Checkbox(
value: value,
tristate: value == null,
activeColor: activeColor,
onChanged: enabled ? (bool? newValue) { } : null,
side: side,
),
),
),
);
}
RenderBox getCheckboxRenderer() {
return tester.renderObject<RenderBox>(find.byType(Checkbox));
}
void expectBorder() {
expect(
getCheckboxRenderer(),
paints
..drrect(
color: borderColor,
outer: RRect.fromLTRBR(15, 15, 33, 33, const Radius.circular(1)),
inner: RRect.fromLTRBR(19, 19, 29, 29, Radius.zero),
),
);
}
// Checkbox is unselected, so the specified BorderSide appears.
await tester.pumpWidget(buildApp(value: false));
await tester.pumpAndSettle();
expectBorder();
await tester.pumpWidget(buildApp(value: false, enabled: false));
await tester.pumpAndSettle();
expectBorder();
// Checkbox is selected/indeterminate, so the specified BorderSide is transparent
await tester.pumpWidget(buildApp(value: true));
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..drrect(color: Colors.transparent));
expect(getCheckboxRenderer(), paints..path(color: activeColor)); // checkbox fill
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(getCheckboxRenderer(), paints..drrect(color: Colors.transparent));
expect(getCheckboxRenderer(), paints..path(color: activeColor)); // checkbox fill
});
testWidgets('Material2 - Checkbox MaterialStateBorderSide applies unconditionally', (WidgetTester tester) async {
const Color borderColor = Color(0xfff44336);
const BorderSide side = BorderSide(
width: 4,
color: borderColor,
);
final ThemeData theme = ThemeData(useMaterial3: false);
Widget buildApp({ bool? value, bool enabled = true }) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Checkbox(
value: value,
tristate: value == null,
onChanged: enabled ? (bool? newValue) { } : null,
side: MaterialStateBorderSide.resolveWith((Set<MaterialState> states) => side),
),
),
),
);
}
void expectBorder() {
expect(
tester.renderObject<RenderBox>(find.byType(Checkbox)),
paints
..drrect(
color: borderColor,
outer: RRect.fromLTRBR(15, 15, 33, 33, const Radius.circular(1)),
inner: RRect.fromLTRBR(19, 19, 29, 29, Radius.zero),
),
);
}
await tester.pumpWidget(buildApp(value: false));
await tester.pumpAndSettle();
expectBorder();
await tester.pumpWidget(buildApp(value: false, enabled: false));
await tester.pumpAndSettle();
expectBorder();
await tester.pumpWidget(buildApp(value: true));
await tester.pumpAndSettle();
expectBorder();
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expectBorder();
});
testWidgets('Material3 - Checkbox MaterialStateBorderSide applies unconditionally', (WidgetTester tester) async {
const Color borderColor = Color(0xfff44336);
const BorderSide side = BorderSide(
width: 4,
color: borderColor,
);
final ThemeData theme = ThemeData(useMaterial3: true);
Widget buildApp({ bool? value, bool enabled = true }) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Checkbox(
value: value,
tristate: value == null,
onChanged: enabled ? (bool? newValue) { } : null,
side: MaterialStateBorderSide.resolveWith((Set<MaterialState> states) => side),
),
),
),
);
}
void expectBorder() {
expect(
tester.renderObject<RenderBox>(find.byType(Checkbox)),
paints
..drrect(
color: borderColor,
outer: RRect.fromLTRBR(15, 15, 33, 33, const Radius.circular(2)),
inner: RRect.fromLTRBR(19, 19, 29, 29, Radius.zero),
),
);
}
await tester.pumpWidget(buildApp(value: false));
await tester.pumpAndSettle();
expectBorder();
await tester.pumpWidget(buildApp(value: false, enabled: false));
await tester.pumpAndSettle();
expectBorder();
await tester.pumpWidget(buildApp(value: true));
await tester.pumpAndSettle();
expectBorder();
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expectBorder();
});
testWidgets('disabled checkbox shows tooltip', (WidgetTester tester) async {
const String longPressTooltip = 'long press tooltip';
const String tapTooltip = 'tap tooltip';
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Tooltip(
message: longPressTooltip,
child: Checkbox(value: true, onChanged: null),
),
),
)
);
// Default tooltip shows up after long pressed.
final Finder tooltip0 = find.byType(Tooltip);
expect(find.text(longPressTooltip), findsNothing);
await tester.tap(tooltip0);
await tester.pump(const Duration(milliseconds: 10));
expect(find.text(longPressTooltip), findsNothing);
final TestGesture gestureLongPress = await tester.startGesture(tester.getCenter(tooltip0));
await tester.pump();
await tester.pump(kLongPressTimeout);
await gestureLongPress.up();
await tester.pump();
expect(find.text(longPressTooltip), findsOneWidget);
// Tooltip shows up after tapping when set triggerMode to TooltipTriggerMode.tap.
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: Tooltip(
triggerMode: TooltipTriggerMode.tap,
message: tapTooltip,
child: Checkbox(value: true, onChanged: null),
),
),
)
);
await tester.pump(const Duration(days: 1));
await tester.pumpAndSettle();
expect(find.text(tapTooltip), findsNothing);
expect(find.text(longPressTooltip), findsNothing);
final Finder tooltip1 = find.byType(Tooltip);
await tester.tap(tooltip1);
await tester.pump(const Duration(milliseconds: 10));
expect(find.text(tapTooltip), findsOneWidget);
});
testWidgets('Material3 - Checkbox has default error color when isError is set to true', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Checkbox');
addTearDown(focusNode.dispose);
final ThemeData themeData = ThemeData(useMaterial3: true);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool? value = true;
Widget buildApp({bool autoFocus = true}) {
return MaterialApp(
theme: themeData,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
isError: true,
value: value,
onChanged: (bool? newValue) {
setState(() {
value = newValue;
});
},
autofocus: autoFocus,
focusNode: focusNode,
);
}),
),
),
);
}
// Focused
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..circle(color: themeData.colorScheme.error.withOpacity(0.1))..path(color: themeData.colorScheme.error)..path(color: themeData.colorScheme.onError)
);
// Default color
await tester.pumpWidget(Container());
await tester.pumpWidget(buildApp(autoFocus: false));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints..path(color: themeData.colorScheme.error)..path(color: themeData.colorScheme.onError)
);
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(color: themeData.colorScheme.error.withOpacity(0.08))
..path(color: themeData.colorScheme.error)
);
// Start pressing
final TestGesture gestureLongPress = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pump();
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..circle(color: themeData.colorScheme.error.withOpacity(0.1))
..path(color: themeData.colorScheme.error)
);
await gestureLongPress.up();
await tester.pump();
});
testWidgets('Material3 - Checkbox MaterialStateBorderSide applies in error states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'Checkbox');
addTearDown(focusNode.dispose);
final ThemeData themeData = ThemeData(useMaterial3: true);
const Color borderColor = Color(0xffffeb3b);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool? value = false;
Widget buildApp({bool autoFocus = true}) {
return MaterialApp(
theme: themeData,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
isError: true,
side: MaterialStateBorderSide.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.error)) {
return const BorderSide(color: borderColor, width: 4);
}
return const BorderSide(color: Colors.red, width: 2);
}),
value: value,
onChanged: (bool? newValue) {
setState(() {
value = newValue;
});
},
autofocus: autoFocus,
focusNode: focusNode,
);
}),
),
),
);
}
void expectBorder() {
expect(
tester.renderObject<RenderBox>(find.byType(Checkbox)),
paints
..drrect(
color: borderColor,
outer: RRect.fromLTRBR(15, 15, 33, 33, const Radius.circular(2)),
inner: RRect.fromLTRBR(19, 19, 29, 29, Radius.zero),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expectBorder();
// Focused
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expectBorder();
// Default color
await tester.pumpWidget(Container());
await tester.pumpWidget(buildApp(autoFocus: false));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
expectBorder();
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Checkbox)));
await tester.pumpAndSettle();
expectBorder();
// Start pressing
final TestGesture gestureLongPress = await tester.startGesture(tester.getCenter(find.byType(Checkbox)));
await tester.pump();
expectBorder();
await gestureLongPress.up();
await tester.pump();
});
testWidgets('Material3 - Checkbox has correct default shape', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: true);
Widget buildApp() {
return MaterialApp(
theme: themeData,
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox(
value: false,
onChanged: (bool? newValue) {},
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
final OutlinedBorder? expectedShape = themeData.checkboxTheme.shape;
expect(tester.widget<Checkbox>(find.byType(Checkbox)).shape, expectedShape);
expect(
Material.of(tester.element(find.byType(Checkbox))),
paints
..drrect(
outer: RRect.fromLTRBR(15.0, 15.0, 33.0, 33.0, const Radius.circular(2)),
inner: RRect.fromLTRBR(17.0, 17.0, 31.0, 31.0, Radius.zero),
),
);
});
testWidgets('Checkbox.adaptive shows the correct platform widget', (WidgetTester tester) async {
Widget buildApp(TargetPlatform platform) {
return MaterialApp(
theme: ThemeData(platform: platform),
home: Material(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return Checkbox.adaptive(
value: false,
onChanged: (bool? newValue) {},
);
}),
),
),
);
}
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
await tester.pumpWidget(buildApp(platform));
await tester.pumpAndSettle();
expect(find.byType(CupertinoCheckbox), findsOneWidget);
}
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows ]) {
await tester.pumpWidget(buildApp(platform));
await tester.pumpAndSettle();
expect(find.byType(CupertinoCheckbox), findsNothing);
}
});
testWidgets('Material2 - Checkbox respects fillColor when it is unchecked', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
const Color activeBackgroundColor = Color(0xff123456);
const Color inactiveBackgroundColor = Color(0xff654321);
Widget buildApp({ bool enabled = true }) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Checkbox(
fillColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return activeBackgroundColor;
}
return inactiveBackgroundColor;
}),
value: false,
onChanged: enabled ? (bool? newValue) { } : null,
),
),
),
);
}
RenderBox getCheckboxRenderer() {
return tester.renderObject<RenderBox>(find.byType(Checkbox));
}
// Checkbox is unselected, so the default BorderSide appears and fillColor is checkbox's background color.
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
getCheckboxRenderer(),
paints
..drrect(
color: theme.unselectedWidgetColor,
),
);
expect(getCheckboxRenderer(), paints..path(color: inactiveBackgroundColor));
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
getCheckboxRenderer(),
paints
..drrect(
color: theme.disabledColor,
),
);
expect(getCheckboxRenderer(), paints..path(color: inactiveBackgroundColor));
});
testWidgets('Material3 - Checkbox respects fillColor when it is unchecked', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
const Color activeBackgroundColor = Color(0xff123456);
const Color inactiveBackgroundColor = Color(0xff654321);
Widget buildApp({ bool enabled = true }) {
return MaterialApp(
theme: theme,
home: Material(
child: Center(
child: Checkbox(
fillColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return activeBackgroundColor;
}
return inactiveBackgroundColor;
}),
value: false,
onChanged: enabled ? (bool? newValue) { } : null,
),
),
),
);
}
RenderBox getCheckboxRenderer() {
return tester.renderObject<RenderBox>(find.byType(Checkbox));
}
// Checkbox is unselected, so the default BorderSide appears and fillColor is checkbox's background color.
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(
getCheckboxRenderer(),
paints
..drrect(
color: theme.colorScheme.onSurfaceVariant,
),
);
expect(getCheckboxRenderer(), paints..path(color: inactiveBackgroundColor));
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(
getCheckboxRenderer(),
paints
..drrect(
color: theme.colorScheme.onSurface.withOpacity(0.38),
),
);
expect(getCheckboxRenderer(), paints..path(color: inactiveBackgroundColor));
});
}
class _SelectedGrabMouseCursor extends MaterialStateMouseCursor {
const _SelectedGrabMouseCursor();
@override
MouseCursor resolve(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return SystemMouseCursors.grab;
}
return SystemMouseCursors.basic;
}
@override
String get debugDescription => '_SelectedGrabMouseCursor()';
}
| flutter/packages/flutter/test/material/checkbox_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/checkbox_test.dart",
"repo_id": "flutter",
"token_count": 32217
} | 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
testWidgets('positions itself at the anchor', (WidgetTester tester) async {
// An arbitrary point on the screen to position at.
const Offset anchor = Offset(30.0, 40.0);
await tester.pumpWidget(
MaterialApp(
home: Center(
child: DesktopTextSelectionToolbar(
anchor: anchor,
children: <Widget>[
DesktopTextSelectionToolbarButton(
child: const Text('Tap me'),
onPressed: () {},
),
],
),
),
),
);
expect(
tester.getTopLeft(find.byType(DesktopTextSelectionToolbarButton)),
anchor,
);
});
}
| flutter/packages/flutter/test/material/desktop_text_selection_toolbar_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/desktop_text_selection_toolbar_test.dart",
"repo_id": "flutter",
"token_count": 416
} | 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
class SimpleExpansionPanelListTestWidget extends StatefulWidget {
const SimpleExpansionPanelListTestWidget({
super.key,
this.firstPanelKey,
this.secondPanelKey,
this.canTapOnHeader = false,
this.expandedHeaderPadding,
this.dividerColor,
this.elevation = 2,
});
final Key? firstPanelKey;
final Key? secondPanelKey;
final bool canTapOnHeader;
final Color? dividerColor;
final double elevation;
/// If null, the default [ExpansionPanelList]'s expanded header padding value is applied via [defaultExpandedHeaderPadding]
final EdgeInsets? expandedHeaderPadding;
/// Mirrors the default expanded header padding as its source constants are private.
static EdgeInsets defaultExpandedHeaderPadding()
{
return const ExpansionPanelList().expandedHeaderPadding;
}
@override
State<SimpleExpansionPanelListTestWidget> createState() => _SimpleExpansionPanelListTestWidgetState();
}
class _SimpleExpansionPanelListTestWidgetState extends State<SimpleExpansionPanelListTestWidget> {
List<bool> extendedState = <bool>[false, false];
@override
Widget build(BuildContext context) {
return ExpansionPanelList(
expandedHeaderPadding: widget.expandedHeaderPadding ?? SimpleExpansionPanelListTestWidget.defaultExpandedHeaderPadding(),
expansionCallback: (int index, bool isExpanded) {
setState(() {
extendedState[index] = !extendedState[index];
});
},
dividerColor: widget.dividerColor,
elevation: widget.elevation,
children: <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A', key: widget.firstPanelKey);
},
body: const SizedBox(height: 100.0),
canTapOnHeader: widget.canTapOnHeader,
isExpanded: extendedState[0],
),
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C', key: widget.secondPanelKey);
},
body: const SizedBox(height: 100.0),
canTapOnHeader: widget.canTapOnHeader,
isExpanded: extendedState[1],
),
],
);
}
}
class ExpansionPanelListSemanticsTest extends StatefulWidget {
const ExpansionPanelListSemanticsTest({ super.key, required this.headerKey });
final Key headerKey;
@override
ExpansionPanelListSemanticsTestState createState() => ExpansionPanelListSemanticsTestState();
}
class ExpansionPanelListSemanticsTestState extends State<ExpansionPanelListSemanticsTest> {
bool headerTapped = false;
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
ExpansionPanelList(
children: <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return MergeSemantics(
key: widget.headerKey,
child: GestureDetector(
onTap: () => headerTapped = true,
child: const Text.rich(
TextSpan(
text:'head1',
),
),
),
);
},
body: const Placeholder(),
),
],
),
],
);
}
}
void main() {
testWidgets('ExpansionPanelList test', (WidgetTester tester) async {
late int capturedIndex;
late bool capturedIsExpanded;
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList(
expansionCallback: (int index, bool isExpanded) {
capturedIndex = index;
capturedIsExpanded = isExpanded;
},
children: <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
),
],
),
),
),
);
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
RenderBox box = tester.renderObject(find.byType(ExpansionPanelList));
final double oldHeight = box.size.height;
expect(find.byType(ExpandIcon), findsOneWidget);
await tester.tap(find.byType(ExpandIcon));
expect(capturedIndex, 0);
expect(capturedIsExpanded, isTrue);
box = tester.renderObject(find.byType(ExpansionPanelList));
expect(box.size.height, equals(oldHeight));
// Now, expand the child panel.
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList(
expansionCallback: (int index, bool isExpanded) {
capturedIndex = index;
capturedIsExpanded = isExpanded;
},
children: <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
isExpanded: true, // this is the addition
),
],
),
),
),
);
await tester.pump(const Duration(milliseconds: 200));
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
box = tester.renderObject(find.byType(ExpansionPanelList));
expect(box.size.height - oldHeight, greaterThanOrEqualTo(100.0)); // 100 + some margin
});
testWidgets('Material2 - ExpansionPanelList does not merge header when canTapOnHeader is false', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
final Key headerKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: ExpansionPanelListSemanticsTest(headerKey: headerKey),
),
);
// Make sure custom gesture detector widget is clickable.
await tester.tap(find.text('head1'));
await tester.pump();
final ExpansionPanelListSemanticsTestState state =
tester.state(find.byType(ExpansionPanelListSemanticsTest));
expect(state.headerTapped, true);
// Check the expansion icon semantics does not merged with header widget.
final Finder expansionIcon = find.descendant(
of: find.ancestor(
of: find.byKey(headerKey),
matching: find.byType(Row),
),
matching: find.byType(ExpandIcon),
);
expect(tester.getSemantics(expansionIcon), matchesSemantics(
label: 'Expand',
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
hasTapAction: true,
));
// Check custom header widget semantics is preserved.
final Finder headerWidget = find.descendant(
of: find.byKey(headerKey),
matching: find.byType(RichText),
);
expect(tester.getSemantics(headerWidget), matchesSemantics(
label: 'head1',
hasTapAction: true,
));
handle.dispose();
});
testWidgets('Material3 - ExpansionPanelList does not merge header when canTapOnHeader is false', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
final Key headerKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: ExpansionPanelListSemanticsTest(headerKey: headerKey),
),
);
// Make sure custom gesture detector widget is clickable.
await tester.tap(find.text('head1'));
await tester.pump();
final ExpansionPanelListSemanticsTestState state =
tester.state(find.byType(ExpansionPanelListSemanticsTest));
expect(state.headerTapped, true);
// Check the expansion icon semantics does not merged with header widget.
final Finder expansionIcon = find.descendant(
of: find.ancestor(
of: find.byKey(headerKey),
matching: find.byType(Row),
),
matching: find.byType(ExpandIcon),
);
expect(tester.getSemantics(expansionIcon), matchesSemantics(
label: 'Expand',
children: <Matcher>[
matchesSemantics(
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
hasTapAction: true,
),
],
));
// Check custom header widget semantics is preserved.
final Finder headerWidget = find.descendant(
of: find.byKey(headerKey),
matching: find.byType(RichText),
);
expect(tester.getSemantics(headerWidget), matchesSemantics(
label: 'head1',
hasTapAction: true,
));
handle.dispose();
});
testWidgets('Multiple Panel List test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: ListView(
children: <ExpansionPanelList>[
ExpansionPanelList(
children: <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
isExpanded: true,
),
],
),
ExpansionPanelList(
children: <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
isExpanded: true,
),
],
),
],
),
),
);
await tester.pump(const Duration(milliseconds: 200));
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
expect(find.text('C'), findsNothing);
expect(find.text('D'), findsOneWidget);
});
testWidgets('Open/close animations', (WidgetTester tester) async {
const Duration kSizeAnimationDuration = Duration(milliseconds: 1000);
// The MaterialGaps animate in using kThemeAnimationDuration (hardcoded),
// which should be less than our test size animation length. So we can assume that they
// appear immediately. Here we just verify that our assumption is true.
expect(kThemeAnimationDuration, lessThan(kSizeAnimationDuration ~/ 2));
Widget build(bool a, bool b, bool c) {
return MaterialApp(
home: Column(
children: <Widget>[
ExpansionPanelList(
animationDuration: kSizeAnimationDuration,
children: <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) => const Placeholder(
fallbackHeight: 12.0,
),
body: const SizedBox(height: 100.0, child: Placeholder(
fallbackHeight: 12.0,
)),
isExpanded: a,
),
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) => const Placeholder(
fallbackHeight: 12.0,
),
body: const SizedBox(height: 100.0, child: Placeholder()),
isExpanded: b,
),
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) => const Placeholder(
fallbackHeight: 12.0,
),
body: const SizedBox(height: 100.0, child: Placeholder()),
isExpanded: c,
),
],
),
],
),
);
}
await tester.pumpWidget(build(false, false, false));
expect(tester.renderObjectList(find.byType(AnimatedSize)), hasLength(3));
expect(tester.getRect(find.byType(AnimatedSize).at(0)), const Rect.fromLTWH(0.0, 48.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(1)), const Rect.fromLTWH(0.0, 97.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(2)), const Rect.fromLTWH(0.0, 146.0, 800.0, 0.0));
await tester.pump(const Duration(milliseconds: 200));
expect(tester.getRect(find.byType(AnimatedSize).at(0)), const Rect.fromLTWH(0.0, 48.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(1)), const Rect.fromLTWH(0.0, 97.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(2)), const Rect.fromLTWH(0.0, 146.0, 800.0, 0.0));
await tester.pumpWidget(build(false, true, false));
expect(tester.getRect(find.byType(AnimatedSize).at(0)), const Rect.fromLTWH(0.0, 48.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(1)), const Rect.fromLTWH(0.0, 97.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(2)), const Rect.fromLTWH(0.0, 146.0, 800.0, 0.0));
await tester.pump(kSizeAnimationDuration ~/ 2);
expect(tester.getRect(find.byType(AnimatedSize).at(0)), const Rect.fromLTWH(0.0, 48.0, 800.0, 0.0));
final Rect rect1 = tester.getRect(find.byType(AnimatedSize).at(1));
expect(rect1.left, 0.0);
expect(rect1.top, inExclusiveRange(113.0, 113.0 + 16.0 + 24.0)); // 16.0 material gap, plus 12.0 top and bottom margins added to the header
expect(rect1.width, 800.0);
expect(rect1.height, inExclusiveRange(0.0, 100.0));
final Rect rect2 = tester.getRect(find.byType(AnimatedSize).at(2));
expect(rect2, Rect.fromLTWH(0.0, rect1.bottom + 16.0 + 48.0, 800.0, 0.0)); // the 16.0 comes from the MaterialGap being introduced, the 48.0 is the header height.
await tester.pumpWidget(build(false, false, false));
expect(tester.getRect(find.byType(AnimatedSize).at(0)), const Rect.fromLTWH(0.0, 48.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(1)), rect1);
expect(tester.getRect(find.byType(AnimatedSize).at(2)), rect2);
await tester.pumpWidget(build(false, false, true));
expect(tester.getRect(find.byType(AnimatedSize).at(0)), const Rect.fromLTWH(0.0, 48.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(1)), rect1);
expect(tester.getRect(find.byType(AnimatedSize).at(2)), rect2);
// a few no-op pumps to make sure there's nothing fishy going on
await tester.pump();
await tester.pump();
await tester.pump();
expect(tester.getRect(find.byType(AnimatedSize).at(0)), const Rect.fromLTWH(0.0, 48.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(1)), rect1);
expect(tester.getRect(find.byType(AnimatedSize).at(2)), rect2);
await tester.pumpAndSettle();
expect(tester.getRect(find.byType(AnimatedSize).at(0)), const Rect.fromLTWH(0.0, 48.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(1)), const Rect.fromLTWH(0.0, 48.0 + 1.0 + 48.0, 800.0, 0.0));
expect(tester.getRect(find.byType(AnimatedSize).at(2)), const Rect.fromLTWH(0.0, 48.0 + 1.0 + 48.0 + 16.0 + 16.0 + 48.0 + 16.0, 800.0, 100.0));
});
testWidgets('Radio mode has max of one panel open at a time', (WidgetTester tester) async {
final List<ExpansionPanel> demoItemsRadio = <ExpansionPanelRadio>[
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
value: 0,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
value: 1,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'F' : 'E');
},
body: const SizedBox(height: 100.0),
value: 2,
),
];
final ExpansionPanelList expansionListRadio = ExpansionPanelList.radio(
children: demoItemsRadio,
);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: expansionListRadio,
),
),
);
// Initializes with all panels closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
RenderBox box = tester.renderObject(find.byType(ExpansionPanelList));
double oldHeight = box.size.height;
expect(find.byType(ExpandIcon), findsNWidgets(3));
await tester.tap(find.byType(ExpandIcon).at(0));
box = tester.renderObject(find.byType(ExpansionPanelList));
expect(box.size.height, equals(oldHeight));
await tester.pump(const Duration(milliseconds: 200));
await tester.pumpAndSettle();
// Now the first panel is open
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
box = tester.renderObject(find.byType(ExpansionPanelList));
expect(box.size.height - oldHeight, greaterThanOrEqualTo(100.0)); // 100 + some margin
await tester.tap(find.byType(ExpandIcon).at(1));
box = tester.renderObject(find.byType(ExpansionPanelList));
oldHeight = box.size.height;
await tester.pump(const Duration(milliseconds: 200));
// Now the first panel is closed and the second should be opened
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsNothing);
expect(find.text('D'), findsOneWidget);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
expect(box.size.height, greaterThanOrEqualTo(oldHeight));
demoItemsRadio.removeAt(0);
await tester.pumpAndSettle();
// Now the first panel should be opened
expect(find.text('C'), findsNothing);
expect(find.text('D'), findsOneWidget);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
final List<ExpansionPanel> demoItems = <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
),
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
),
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'F' : 'E');
},
body: const SizedBox(height: 100.0),
),
];
final ExpansionPanelList expansionList = ExpansionPanelList(
children: demoItems,
);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: expansionList,
),
),
);
// We've reinitialized with a regular expansion panel so they should all be closed again
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
});
testWidgets('Radio mode calls expansionCallback once if other panels closed', (WidgetTester tester) async {
final List<ExpansionPanel> demoItemsRadio = <ExpansionPanelRadio>[
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
value: 0,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
value: 1,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'F' : 'E');
},
body: const SizedBox(height: 100.0),
value: 2,
),
];
final List<Map<String, dynamic>> callbackHistory = <Map<String, dynamic>>[];
final ExpansionPanelList expansionListRadio = ExpansionPanelList.radio(
expansionCallback: (int index, bool isExpanded) {
callbackHistory.add(<String, dynamic>{
'index': index,
'isExpanded': isExpanded,
});
},
children: demoItemsRadio,
);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: expansionListRadio,
),
),
);
// Initializes with all panels closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
// Open one panel
await tester.tap(find.byType(ExpandIcon).at(1));
await tester.pumpAndSettle();
// Callback is invoked once with appropriate arguments
expect(callbackHistory.length, equals(1));
expect(callbackHistory.last['index'], equals(1));
expect(callbackHistory.last['isExpanded'], equals(true));
// Close the same panel
await tester.tap(find.byType(ExpandIcon).at(1));
await tester.pumpAndSettle();
// Callback is invoked once with appropriate arguments
expect(callbackHistory.length, equals(2));
expect(callbackHistory.last['index'], equals(1));
expect(callbackHistory.last['isExpanded'], equals(false));
});
testWidgets('Radio mode calls expansionCallback twice if other panel open prior', (WidgetTester tester) async {
final List<ExpansionPanel> demoItemsRadio = <ExpansionPanelRadio>[
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
value: 0,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
value: 1,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'F' : 'E');
},
body: const SizedBox(height: 100.0),
value: 2,
),
];
final List<Map<String, dynamic>> callbackHistory = <Map<String, dynamic>>[];
Map<String, dynamic> callbackResults;
final ExpansionPanelList expansionListRadio = ExpansionPanelList.radio(
expansionCallback: (int index, bool isExpanded) {
callbackHistory.add(<String, dynamic>{
'index': index,
'isExpanded': isExpanded,
});
},
children: demoItemsRadio,
);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: expansionListRadio,
),
),
);
// Initializes with all panels closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
// Open one panel
await tester.tap(find.byType(ExpandIcon).at(1));
await tester.pumpAndSettle();
// Callback is invoked once with appropriate arguments
expect(callbackHistory.length, equals(1));
callbackResults = callbackHistory[callbackHistory.length - 1];
expect(callbackResults['index'], equals(1));
expect(callbackResults['isExpanded'], equals(true));
// Close a different panel
await tester.tap(find.byType(ExpandIcon).at(2));
await tester.pumpAndSettle();
// Callback is invoked the first time with correct arguments
expect(callbackHistory.length, equals(3));
callbackResults = callbackHistory[callbackHistory.length - 2];
expect(callbackResults['index'], equals(1));
expect(callbackResults['isExpanded'], equals(false));
// Callback is invoked the second time with correct arguments
callbackResults = callbackHistory[callbackHistory.length - 1];
expect(callbackResults['index'], equals(2));
expect(callbackResults['isExpanded'], equals(true));
});
testWidgets('ExpansionPanelList.radio callback displays true or false based on the visibility of a list item', (WidgetTester tester) async {
late int lastExpanded;
bool topElementExpanded = false;
bool bottomElementExpanded = false;
final List<ExpansionPanel> demoItemsRadio = <ExpansionPanelRadio>[
// topElement
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
value: 0,
),
// bottomElement
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
value: 1,
),
];
final ExpansionPanelList expansionListRadio = ExpansionPanelList.radio(
children: demoItemsRadio,
expansionCallback: (int index, bool isExpanded)
{
lastExpanded = index;
if (index == 0)
{
topElementExpanded = isExpanded;
bottomElementExpanded = false;
}
else
{
topElementExpanded = false;
bottomElementExpanded = isExpanded;
}
}
);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: expansionListRadio,
),
),
);
// Initializes with all panels closed.
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byType(ExpandIcon).at(0));
await tester.pump(const Duration(milliseconds: 200));
await tester.pumpAndSettle();
// Now the first panel is open.
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
expect(lastExpanded,0);
expect(topElementExpanded,true);
await tester.tap(find.byType(ExpandIcon).at(1));
await tester.pump(const Duration(milliseconds: 200));
await tester.pumpAndSettle();
// Open the other panel and ensure the first is now closed.
expect(lastExpanded,1);
expect(bottomElementExpanded,true);
expect(topElementExpanded,false);
expect(find.text('D'), findsOneWidget);
expect(find.text('A'), findsOneWidget);
await tester.tap(find.byType(ExpandIcon).at(1));
await tester.pump(const Duration(milliseconds: 200));
await tester.pumpAndSettle();
// Close the item that was expanded should now be false.
expect(lastExpanded,1);
expect(bottomElementExpanded,false);
// All panels should be closed.
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
});
testWidgets(
'didUpdateWidget accounts for toggling between ExpansionPanelList '
'and ExpansionPaneList.radio',
(WidgetTester tester) async {
bool isRadioList = false;
final List<bool> panelExpansionState = <bool>[
false,
false,
false,
];
ExpansionPanelList buildRadioExpansionPanelList() {
return ExpansionPanelList.radio(
initialOpenPanelValue: 2,
children: <ExpansionPanelRadio>[
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
value: 0,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
value: 1,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'F' : 'E');
},
body: const SizedBox(height: 100.0),
value: 2,
),
],
);
}
ExpansionPanelList buildExpansionPanelList(StateSetter setState) {
return ExpansionPanelList(
expansionCallback: (int index, _) => setState(() { panelExpansionState[index] = !panelExpansionState[index]; }),
children: <ExpansionPanel>[
ExpansionPanel(
isExpanded: panelExpansionState[0],
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
),
ExpansionPanel(
isExpanded: panelExpansionState[1],
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
),
ExpansionPanel(
isExpanded: panelExpansionState[2],
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'F' : 'E');
},
body: const SizedBox(height: 100.0),
),
],
);
}
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: isRadioList
? buildRadioExpansionPanelList()
: buildExpansionPanelList(setState),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() { isRadioList = !isRadioList; }),
),
),
);
},
),
);
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
await tester.tap(find.byType(ExpandIcon).at(0));
await tester.tap(find.byType(ExpandIcon).at(1));
await tester.pumpAndSettle();
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
expect(find.text('C'), findsNothing);
expect(find.text('D'), findsOneWidget);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
// ExpansionPanelList --> ExpansionPanelList.radio
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
expect(find.text('E'), findsNothing);
expect(find.text('F'), findsOneWidget);
// ExpansionPanelList.radio --> ExpansionPanelList
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
expect(find.text('C'), findsNothing);
expect(find.text('D'), findsOneWidget);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
},
);
testWidgets('No duplicate global keys at layout/build time', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/13780
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
// Wrapping with LayoutBuilder or other widgets that augment
// layout/build order should not create duplicate keys
home: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return SingleChildScrollView(
child: ExpansionPanelList.radio(
expansionCallback: (int index, bool isExpanded) {
if (!isExpanded) {
// setState invocation required to trigger
// _ExpansionPanelListState.didUpdateWidget,
// which causes duplicate keys to be
// generated in the regression
setState(() {});
}
},
children: <ExpansionPanelRadio>[
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
value: 0,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
value: 1,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'F' : 'E');
},
body: const SizedBox(height: 100.0),
value: 2,
),
],
),
);
},
),
);
},
),
);
// Initializes with all panels closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
expect(find.text('E'), findsOneWidget);
expect(find.text('F'), findsNothing);
// Open a panel
await tester.tap(find.byType(ExpandIcon).at(1));
await tester.pumpAndSettle();
final List<bool> panelExpansionState = <bool>[false, false];
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Scaffold(
// Wrapping with LayoutBuilder or other widgets that augment
// layout/build order should not create duplicate keys
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return SingleChildScrollView(
child: ExpansionPanelList(
expansionCallback: (int index, bool isExpanded) {
// setState invocation required to trigger
// _ExpansionPanelListState.didUpdateWidget, which
// causes duplicate keys to be generated in the
// regression
setState(() {
panelExpansionState[index] = !isExpanded;
});
},
children: <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A');
},
body: const SizedBox(height: 100.0),
isExpanded: panelExpansionState[0],
),
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C');
},
body: const SizedBox(height: 100.0),
isExpanded: panelExpansionState[1],
),
],
),
);
},
),
),
);
},
),
);
// initializes with all panels closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
// open a panel
await tester.tap(find.byType(ExpandIcon).at(1));
await tester.pumpAndSettle();
});
testWidgets('Material2 - Panel header has semantics, canTapOnHeader = false', (WidgetTester tester) async {
const Key expandedKey = Key('expanded');
const Key collapsedKey = Key('collapsed');
const DefaultMaterialLocalizations localizations = DefaultMaterialLocalizations();
final SemanticsHandle handle = tester.ensureSemantics();
final List<ExpansionPanel> demoItems = <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('Expanded', key: expandedKey);
},
body: const SizedBox(height: 100.0),
isExpanded: true,
),
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('Collapsed', key: collapsedKey);
},
body: const SizedBox(height: 100.0),
),
];
final ExpansionPanelList expansionList = ExpansionPanelList(
children: demoItems,
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: SingleChildScrollView(
child: expansionList,
),
),
);
// Check the semantics of [ExpandIcon] for expanded panel.
final Finder expandedIcon = find.descendant(
of: find.ancestor(
of: find.byKey(expandedKey),
matching: find.byType(Row),
),
matching: find.byType(ExpandIcon),
);
expect(tester.getSemantics(expandedIcon), matchesSemantics(
label: 'Collapse',
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
hasTapAction: true,
onTapHint: localizations.expandedIconTapHint,
));
// Check the semantics of the header widget for expanded panel.
final Finder expandedHeader = find.byKey(expandedKey);
expect(tester.getSemantics(expandedHeader), matchesSemantics(
label: 'Expanded',
));
// Check the semantics of [ExpandIcon] for collapsed panel.
final Finder collapsedIcon = find.descendant(
of: find.ancestor(
of: find.byKey(collapsedKey),
matching: find.byType(Row),
),
matching: find.byType(ExpandIcon),
);
expect(tester.getSemantics(collapsedIcon), matchesSemantics(
label: 'Expand',
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
hasTapAction: true,
onTapHint: localizations.collapsedIconTapHint,
));
// Check the semantics of the header widget for expanded panel.
final Finder collapsedHeader = find.byKey(collapsedKey);
expect(tester.getSemantics(collapsedHeader), matchesSemantics(
label: 'Collapsed',
));
handle.dispose();
});
testWidgets('Material3 - Panel header has semantics, canTapOnHeader = false', (WidgetTester tester) async {
const Key expandedKey = Key('expanded');
const Key collapsedKey = Key('collapsed');
const DefaultMaterialLocalizations localizations = DefaultMaterialLocalizations();
final SemanticsHandle handle = tester.ensureSemantics();
final List<ExpansionPanel> demoItems = <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('Expanded', key: expandedKey);
},
body: const SizedBox(height: 100.0),
isExpanded: true,
),
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('Collapsed', key: collapsedKey);
},
body: const SizedBox(height: 100.0),
),
];
final ExpansionPanelList expansionList = ExpansionPanelList(
children: demoItems,
);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: expansionList,
),
),
);
// Check the semantics of [ExpandIcon] for expanded panel.
final Finder expandedIcon = find.descendant(
of: find.ancestor(
of: find.byKey(expandedKey),
matching: find.byType(Row),
),
matching: find.byType(ExpandIcon),
);
expect(tester.getSemantics(expandedIcon), matchesSemantics(
label: 'Collapse',
onTapHint: localizations.expandedIconTapHint,
children: <Matcher>[
matchesSemantics(
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
hasTapAction: true,
),
],
));
// Check the semantics of the header widget for expanded panel.
final Finder expandedHeader = find.byKey(expandedKey);
expect(tester.getSemantics(expandedHeader), matchesSemantics(
label: 'Expanded',
));
// Check the semantics of [ExpandIcon] for collapsed panel.
final Finder collapsedIcon = find.descendant(
of: find.ancestor(
of: find.byKey(collapsedKey),
matching: find.byType(Row),
),
matching: find.byType(ExpandIcon),
);
expect(tester.getSemantics(collapsedIcon), matchesSemantics(
label: 'Expand',
onTapHint: localizations.collapsedIconTapHint,
children: <Matcher>[
matchesSemantics(
isButton: true,
hasEnabledState: true,
isEnabled: true,
isFocusable: true,
hasTapAction: true,
),
],
));
// Check the semantics of the header widget for expanded panel.
final Finder collapsedHeader = find.byKey(collapsedKey);
expect(tester.getSemantics(collapsedHeader), matchesSemantics(
label: 'Collapsed',
));
handle.dispose();
});
testWidgets('Panel header has semantics, canTapOnHeader = true', (WidgetTester tester) async {
const Key expandedKey = Key('expanded');
const Key collapsedKey = Key('collapsed');
final SemanticsHandle handle = tester.ensureSemantics();
final List<ExpansionPanel> demoItems = <ExpansionPanel>[
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('Expanded', key: expandedKey);
},
canTapOnHeader: true,
body: const SizedBox(height: 100.0),
isExpanded: true,
),
ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('Collapsed', key: collapsedKey);
},
canTapOnHeader: true,
body: const SizedBox(height: 100.0),
),
];
final ExpansionPanelList expansionList = ExpansionPanelList(
children: demoItems,
);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: expansionList,
),
),
);
expect(tester.getSemantics(find.byKey(expandedKey)), matchesSemantics(
label: 'Expanded',
isButton: true,
isFocusable: true,
hasEnabledState: true,
hasTapAction: true,
));
expect(tester.getSemantics(find.byKey(collapsedKey)), matchesSemantics(
label: 'Collapsed',
isButton: true,
isFocusable: true,
hasEnabledState: true,
hasTapAction: true,
));
handle.dispose();
});
testWidgets('Ensure canTapOnHeader is false by default', (WidgetTester tester) async {
final ExpansionPanel expansionPanel = ExpansionPanel(
headerBuilder: (BuildContext context, bool isExpanded) => const Text('Demo'),
body: const SizedBox(height: 100.0),
);
expect(expansionPanel.canTapOnHeader, isFalse);
});
testWidgets('Toggle ExpansionPanelRadio when tapping header and canTapOnHeader is true', (WidgetTester tester) async {
const Key firstPanelKey = Key('firstPanelKey');
const Key secondPanelKey = Key('secondPanelKey');
final List<ExpansionPanel> demoItemsRadio = <ExpansionPanelRadio>[
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A', key: firstPanelKey);
},
body: const SizedBox(height: 100.0),
value: 0,
canTapOnHeader: true,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C', key: secondPanelKey);
},
body: const SizedBox(height: 100.0),
value: 1,
canTapOnHeader: true,
),
];
final ExpansionPanelList expansionListRadio = ExpansionPanelList.radio(
children: demoItemsRadio,
);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: expansionListRadio,
),
),
);
// Initializes with all panels closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byKey(firstPanelKey));
await tester.pumpAndSettle();
// Now the first panel is open
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byKey(secondPanelKey));
await tester.pumpAndSettle();
// Now the second panel is open
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsNothing);
expect(find.text('D'), findsOneWidget);
});
testWidgets('Toggle ExpansionPanel when tapping header and canTapOnHeader is true', (WidgetTester tester) async {
const Key firstPanelKey = Key('firstPanelKey');
const Key secondPanelKey = Key('secondPanelKey');
await tester.pumpWidget(
const MaterialApp(
home: SingleChildScrollView(
child: SimpleExpansionPanelListTestWidget(
firstPanelKey: firstPanelKey,
secondPanelKey: secondPanelKey,
canTapOnHeader: true,
),
),
),
);
// Initializes with all panels closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byKey(firstPanelKey));
await tester.pumpAndSettle();
// The first panel is open
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byKey(firstPanelKey));
await tester.pumpAndSettle();
// The first panel is closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byKey(secondPanelKey));
await tester.pumpAndSettle();
// The second panel is open
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsNothing);
expect(find.text('D'), findsOneWidget);
await tester.tap(find.byKey(secondPanelKey));
await tester.pumpAndSettle();
// The second panel is closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
});
testWidgets('Do not toggle ExpansionPanel when tapping header and canTapOnHeader is false', (WidgetTester tester) async {
const Key firstPanelKey = Key('firstPanelKey');
const Key secondPanelKey = Key('secondPanelKey');
await tester.pumpWidget(
const MaterialApp(
home: SingleChildScrollView(
child: SimpleExpansionPanelListTestWidget(
firstPanelKey: firstPanelKey,
secondPanelKey: secondPanelKey,
),
),
),
);
// Initializes with all panels closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byKey(firstPanelKey));
await tester.pumpAndSettle();
// The first panel is closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byKey(secondPanelKey));
await tester.pumpAndSettle();
// The second panel is closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
});
testWidgets('Do not toggle ExpansionPanelRadio when tapping header and canTapOnHeader is false', (WidgetTester tester) async {
const Key firstPanelKey = Key('firstPanelKey');
const Key secondPanelKey = Key('secondPanelKey');
final List<ExpansionPanel> demoItemsRadio = <ExpansionPanelRadio>[
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A', key: firstPanelKey);
},
body: const SizedBox(height: 100.0),
value: 0,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C', key: secondPanelKey);
},
body: const SizedBox(height: 100.0),
value: 1,
),
];
final ExpansionPanelList expansionListRadio = ExpansionPanelList.radio(
children: demoItemsRadio,
);
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: expansionListRadio,
),
),
);
// Initializes with all panels closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byKey(firstPanelKey));
await tester.pumpAndSettle();
// The first panel is closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
await tester.tap(find.byKey(secondPanelKey));
await tester.pumpAndSettle();
// The second panel is closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
expect(find.text('D'), findsNothing);
});
testWidgets('Correct default header padding', (WidgetTester tester) async {
const Key firstPanelKey = Key('firstPanelKey');
await tester.pumpWidget(
const MaterialApp(
home: SingleChildScrollView(
child: SimpleExpansionPanelListTestWidget(
firstPanelKey: firstPanelKey,
canTapOnHeader: true,
),
),
),
);
// The panel is closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
// No padding applied to closed header
RenderBox box = tester.renderObject(find.ancestor(of: find.byKey(firstPanelKey), matching: find.byType(AnimatedContainer)).first);
expect(box.size.height, equals(48.0)); // _kPanelHeaderCollapsedHeight
expect(box.size.width, equals(744.0));
// Now, expand the child panel.
await tester.tap(find.byKey(firstPanelKey));
await tester.pumpAndSettle();
// The panel is expanded
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
// Padding is added to expanded header
box = tester.renderObject(find.ancestor(of: find.byKey(firstPanelKey), matching: find.byType(AnimatedContainer)).first);
expect(box.size.height, equals(80.0)); // _kPanelHeaderCollapsedHeight + 24.0 (double default padding)
expect(box.size.width, equals(744.0));
});
// Regression test for https://github.com/flutter/flutter/issues/5848.
testWidgets('The AnimatedContainer and IconButton have the same height of 48px', (WidgetTester tester) async {
const Key firstPanelKey = Key('firstPanelKey');
await tester.pumpWidget(
const MaterialApp(
home: SingleChildScrollView(
child: SimpleExpansionPanelListTestWidget(
firstPanelKey: firstPanelKey,
canTapOnHeader: true,
),
),
),
);
// The panel is closed.
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
// No padding applied to closed header.
final RenderBox boxOfContainer = tester.renderObject(find.ancestor(of: find.byKey(firstPanelKey), matching: find.byType(AnimatedContainer)).first);
final RenderBox boxOfIconButton = tester.renderObject(find.byType(IconButton).first);
expect(boxOfContainer.size.height, equals(boxOfIconButton.size.height));
expect(boxOfContainer.size.height, equals(48.0)); // Header should have 48px height according to Material 2 Design spec.
});
testWidgets("The AnimatedContainer's height is at least kMinInteractiveDimension", (WidgetTester tester) async {
const Key firstPanelKey = Key('firstPanelKey');
await tester.pumpWidget(
const MaterialApp(
home: SingleChildScrollView(
child: SimpleExpansionPanelListTestWidget(
firstPanelKey: firstPanelKey,
canTapOnHeader: true,
),
),
),
);
// The panel is closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
// No padding applied to closed header
final RenderBox box = tester.renderObject(find.ancestor(of: find.byKey(firstPanelKey), matching: find.byType(AnimatedContainer)).first);
expect(box.size.height, greaterThanOrEqualTo(kMinInteractiveDimension));
});
testWidgets('Correct custom header padding', (WidgetTester tester) async {
const Key firstPanelKey = Key('firstPanelKey');
await tester.pumpWidget(
const MaterialApp(
home: SingleChildScrollView(
child: SimpleExpansionPanelListTestWidget(
firstPanelKey: firstPanelKey,
canTapOnHeader: true,
expandedHeaderPadding: EdgeInsets.symmetric(vertical: 40.0),
),
),
),
);
// The panel is closed
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
// No padding applied to closed header
RenderBox box = tester.renderObject(find.ancestor(of: find.byKey(firstPanelKey), matching: find.byType(AnimatedContainer)).first);
expect(box.size.height, equals(48.0)); // _kPanelHeaderCollapsedHeight
expect(box.size.width, equals(744.0));
// Now, expand the child panel.
await tester.tap(find.byKey(firstPanelKey));
await tester.pumpAndSettle();
// The panel is expanded
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
// Padding is added to expanded header
box = tester.renderObject(find.ancestor(of: find.byKey(firstPanelKey), matching: find.byType(AnimatedContainer)).first);
expect(box.size.height, equals(128.0)); // _kPanelHeaderCollapsedHeight + 80.0 (double padding)
expect(box.size.width, equals(744.0));
});
testWidgets('ExpansionPanelList respects dividerColor', (WidgetTester tester) async {
const Color dividerColor = Colors.red;
await tester.pumpWidget(const MaterialApp(
home: SingleChildScrollView(
child: SimpleExpansionPanelListTestWidget(
dividerColor: dividerColor,
),
),
));
final DecoratedBox decoratedBox = tester.widget(find.byType(DecoratedBox).last);
final BoxDecoration decoration = decoratedBox.decoration as BoxDecoration;
// For the last DecoratedBox, we will have a Border.top with the provided dividerColor.
expect(decoration.border!.top.color, dividerColor);
});
testWidgets('ExpansionPanelList.radio respects DividerColor', (WidgetTester tester) async {
const Color dividerColor = Colors.red;
await tester.pumpWidget(MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList.radio(
dividerColor: dividerColor,
children: <ExpansionPanelRadio>[
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A', key: const Key('firstKey'));
},
body: const SizedBox(height: 100.0),
value: 0,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C', key: const Key('secondKey'));
},
body: const SizedBox(height: 100.0),
value: 1,
),
],
),
),
));
final DecoratedBox decoratedBox = tester.widget(find.byType(DecoratedBox).last);
final BoxDecoration boxDecoration = decoratedBox.decoration as BoxDecoration;
// For the last DecoratedBox, we will have a Border.top with the provided dividerColor.
expect(boxDecoration.border!.top.color, dividerColor);
});
testWidgets('ExpansionPanelList respects expandIconColor', (WidgetTester tester) async {
const Color expandIconColor = Colors.blue;
await tester.pumpWidget(MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList(
expandIconColor: expandIconColor,
children: <ExpansionPanel>[
ExpansionPanel(
canTapOnHeader: true,
body: const SizedBox.shrink(),
headerBuilder: (BuildContext context, bool isExpanded) {
return const SizedBox.shrink();
}
)
],
),
),
));
final ExpandIcon expandIcon = tester.widget(find.byType(ExpandIcon));
expect(expandIcon.color, expandIconColor);
});
testWidgets('ExpansionPanelList.radio respects expandIconColor', (WidgetTester tester) async {
const Color expandIconColor = Colors.blue;
await tester.pumpWidget(MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList.radio(
expandIconColor: expandIconColor,
children: <ExpansionPanelRadio>[
ExpansionPanelRadio(
canTapOnHeader: true,
body: const SizedBox.shrink(),
headerBuilder: (BuildContext context, bool isExpanded) {
return const SizedBox.shrink();
},
value: true
)
],
),
),
));
final ExpandIcon expandIcon = tester.widget(find.byType(ExpandIcon));
expect(expandIcon.color, expandIconColor);
});
testWidgets('elevation is propagated properly to MergeableMaterial', (WidgetTester tester) async {
const double elevation = 8;
// Test for ExpansionPanelList.
await tester.pumpWidget(const MaterialApp(
home: SingleChildScrollView(
child: SimpleExpansionPanelListTestWidget(
elevation: elevation,
),
),
));
expect(tester.widget<MergeableMaterial>(find.byType(MergeableMaterial)).elevation, elevation);
// Test for ExpansionPanelList.radio.
await tester.pumpWidget(MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList.radio(
elevation: elevation,
children: <ExpansionPanelRadio>[
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'B' : 'A', key: const Key('firstKey'));
},
body: const SizedBox(height: 100.0),
value: 0,
),
ExpansionPanelRadio(
headerBuilder: (BuildContext context, bool isExpanded) {
return Text(isExpanded ? 'D' : 'C', key: const Key('secondKey'));
},
body: const SizedBox(height: 100.0),
value: 1,
),
],
),
),
));
expect(tester.widget<MergeableMaterial>(find.byType(MergeableMaterial)).elevation, elevation);
});
testWidgets('Using a value non defined value throws assertion error', (WidgetTester tester) async {
// It should throw an AssertionError since, 19 is not defined in kElevationToShadow.
await tester.pumpWidget(const MaterialApp(
home: SingleChildScrollView(
child: SimpleExpansionPanelListTestWidget(
elevation: 19,
),
),
));
final dynamic exception = tester.takeException();
expect(exception, isAssertionError);
expect((exception as AssertionError).toString(), contains(
'Invalid value for elevation. See the kElevationToShadow constant for'
' possible elevation values.',
));
});
testWidgets('ExpansionPanel.panelColor test', (WidgetTester tester) async {
const Color firstPanelColor = Colors.red;
const Color secondPanelColor = Colors.brown;
await tester.pumpWidget(
MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList(
expansionCallback: (int index, bool isExpanded) {},
children: <ExpansionPanel>[
ExpansionPanel(
backgroundColor: firstPanelColor,
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('A');
},
body: const SizedBox(height: 100.0),
),
ExpansionPanel(
backgroundColor: secondPanelColor,
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('B');
},
body: const SizedBox(height: 100.0),
),
],
),
),
),
);
final MergeableMaterial mergeableMaterial = tester.widget(find.byType(MergeableMaterial));
expect((mergeableMaterial.children.first as MaterialSlice).color, firstPanelColor);
expect((mergeableMaterial.children.last as MaterialSlice).color, secondPanelColor);
});
testWidgets('ExpansionPanelRadio.backgroundColor test', (WidgetTester tester) async {
const Color firstPanelColor = Colors.red;
const Color secondPanelColor = Colors.brown;
await tester.pumpWidget(MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList.radio(
children: <ExpansionPanelRadio>[
ExpansionPanelRadio(
backgroundColor: firstPanelColor,
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('A');
},
body: const SizedBox(height: 100.0),
value: 0,
),
ExpansionPanelRadio(
backgroundColor: secondPanelColor,
headerBuilder: (BuildContext context, bool isExpanded) {
return const Text('B');
},
body: const SizedBox(height: 100.0),
value: 1,
),
],
),
),
));
final MergeableMaterial mergeableMaterial = tester.widget(find.byType(MergeableMaterial));
expect((mergeableMaterial.children.first as MaterialSlice).color, firstPanelColor);
expect((mergeableMaterial.children.last as MaterialSlice).color, secondPanelColor);
});
testWidgets('ExpansionPanelList.materialGapSize defaults to 16.0', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList(
children: <ExpansionPanel>[
ExpansionPanel(
canTapOnHeader: true,
body: const SizedBox.shrink(),
headerBuilder: (BuildContext context, bool isExpanded) {
return const SizedBox.shrink();
},
)
],
),
),
));
final ExpansionPanelList expansionPanelList = tester.widget(find.byType(ExpansionPanelList));
expect(expansionPanelList.materialGapSize, 16);
});
testWidgets('ExpansionPanelList respects materialGapSize', (WidgetTester tester) async {
Widget buildWidgetForTest({double materialGapSize = 16}) {
return MaterialApp(
home: SingleChildScrollView(
child: ExpansionPanelList(
materialGapSize: materialGapSize,
children: <ExpansionPanel>[
ExpansionPanel(
isExpanded: true,
canTapOnHeader: true,
body: const SizedBox.shrink(),
headerBuilder: (BuildContext context, bool isExpanded) {
return const SizedBox.shrink();
},
),
ExpansionPanel(
canTapOnHeader: true,
body: const SizedBox.shrink(),
headerBuilder: (BuildContext context, bool isExpanded) {
return const SizedBox.shrink();
},
),
],
),
),
);
}
await tester.pumpWidget(buildWidgetForTest(materialGapSize: 0));
await tester.pumpAndSettle();
final MergeableMaterial mergeableMaterial = tester.widget(find.byType(MergeableMaterial));
expect(mergeableMaterial.children.length, 3);
expect(mergeableMaterial.children.whereType<MaterialGap>().length, 1);
expect(mergeableMaterial.children.whereType<MaterialSlice>().length, 2);
for (final MergeableMaterialItem e in mergeableMaterial.children) {
if (e is MaterialGap) {
expect(e.size, 0);
}
}
await tester.pumpWidget(buildWidgetForTest(materialGapSize: 20));
await tester.pumpAndSettle();
final MergeableMaterial mergeableMaterial2 = tester.widget(find.byType(MergeableMaterial));
expect(mergeableMaterial2.children.length, 3);
expect(mergeableMaterial2.children.whereType<MaterialGap>().length, 1);
expect(mergeableMaterial2.children.whereType<MaterialSlice>().length, 2);
for (final MergeableMaterialItem e in mergeableMaterial2.children) {
if (e is MaterialGap) {
expect(e.size, 20);
}
}
await tester.pumpWidget(buildWidgetForTest());
await tester.pumpAndSettle();
final MergeableMaterial mergeableMaterial3 = tester.widget(find.byType(MergeableMaterial));
expect(mergeableMaterial3.children.length, 3);
expect(mergeableMaterial3.children.whereType<MaterialGap>().length, 1);
expect(mergeableMaterial3.children.whereType<MaterialSlice>().length, 2);
for (final MergeableMaterialItem e in mergeableMaterial3.children) {
if (e is MaterialGap) {
expect(e.size, 16);
}
}
});
}
| flutter/packages/flutter/test/material/expansion_panel_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/expansion_panel_test.dart",
"repo_id": "flutter",
"token_count": 28515
} | 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';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
import 'feedback_tester.dart';
class MockOnPressedFunction {
int called = 0;
void handler() {
called++;
}
}
void main() {
late MockOnPressedFunction mockOnPressedFunction;
const ColorScheme colorScheme = ColorScheme.light();
final ThemeData theme = ThemeData.from(colorScheme: colorScheme);
setUp(() {
mockOnPressedFunction = MockOnPressedFunction();
});
testWidgets('test icon is findable by key', (WidgetTester tester) async {
const ValueKey<String> key = ValueKey<String>('icon-button');
await tester.pumpWidget(
wrap(
useMaterial3: true,
child: IconButton(
key: key,
onPressed: () {},
icon: const Icon(Icons.link),
),
),
);
expect(find.byKey(key), findsOneWidget);
});
testWidgets('test default icon buttons are sized up to 48', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
),
),
);
final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
expect(iconButton.size, const Size(48.0, 48.0));
await tester.tap(find.byType(IconButton));
expect(mockOnPressedFunction.called, 1);
});
testWidgets('test small icons are sized up to 48dp', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: IconButton(
iconSize: 10.0,
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
),
)
);
final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
expect(iconButton.size, const Size(48.0, 48.0));
});
testWidgets('test icons can be small when total size is >48dp', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: IconButton(
iconSize: 10.0,
padding: const EdgeInsets.all(30.0),
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
),
)
);
final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
expect(iconButton.size, const Size(70.0, 70.0));
});
testWidgets('when both iconSize and IconTheme.of(context).size are null, size falls back to 24.0', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: IconTheme(
data: const IconThemeData(),
child: IconButton(
focusNode: focusNode,
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
),
)
)
);
final RenderBox icon = tester.renderObject(find.byType(Icon));
expect(icon.size, const Size(24.0, 24.0));
focusNode.dispose();
});
testWidgets('when null, iconSize is overridden by closest IconTheme', (WidgetTester tester) async {
RenderBox icon;
final bool material3 = theme.useMaterial3;
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: IconTheme(
data: const IconThemeData(size: 10),
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
),
)
)
);
icon = tester.renderObject(find.byType(Icon));
expect(icon.size, const Size(10.0, 10.0));
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: Theme(
data: ThemeData(
useMaterial3: material3,
iconTheme: const IconThemeData(size: 10),
),
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
),
)
)
);
icon = tester.renderObject(find.byType(Icon));
expect(icon.size, const Size(10.0, 10.0));
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: Theme(
data: ThemeData(
useMaterial3: material3,
iconTheme: const IconThemeData(size: 20),
),
child: IconTheme(
data: const IconThemeData(size: 10),
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
),
),
)
),
);
icon = tester.renderObject(find.byType(Icon));
expect(icon.size, const Size(10.0, 10.0));
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: IconTheme(
data: const IconThemeData(size: 20),
child: Theme(
data: ThemeData(
useMaterial3: material3,
iconTheme: const IconThemeData(size: 10),
),
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
),
),
)
),
);
icon = tester.renderObject(find.byType(Icon));
expect(icon.size, const Size(10.0, 10.0));
});
testWidgets('when non-null, iconSize precedes IconTheme.of(context).size', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: IconTheme(
data: const IconThemeData(size: 30.0),
child: IconButton(
iconSize: 10.0,
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
),
)
),
);
final RenderBox icon = tester.renderObject(find.byType(Icon));
expect(icon.size, const Size(10.0, 10.0));
});
testWidgets('Small icons with non-null constraints can be <48dp for M2, but =48dp for M3', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: IconButton(
iconSize: 10.0,
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
constraints: const BoxConstraints(),
)
)
);
final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
final RenderBox icon = tester.renderObject(find.byType(Icon));
// By default IconButton has a padding of 8.0 on all sides, so both
// width and height are 10.0 + 2 * 8.0 = 26.0
// M3 IconButton is a subclass of ButtonStyleButton which has a minimum
// Size(48.0, 48.0).
expect(iconButton.size, material3 ? const Size(48.0, 48.0) : const Size(26.0, 26.0));
expect(icon.size, const Size(10.0, 10.0));
});
testWidgets('Small icons with non-null constraints and custom padding can be <48dp', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: IconButton(
iconSize: 10.0,
padding: const EdgeInsets.all(3.0),
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
constraints: const BoxConstraints(),
),
),
);
final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
final RenderBox icon = tester.renderObject(find.byType(Icon));
// This IconButton has a padding of 3.0 on all sides, so both
// width and height are 10.0 + 2 * 3.0 = 16.0
// M3 IconButton is a subclass of ButtonStyleButton which has a minimum
// Size(48.0, 48.0).
expect(iconButton.size, material3 ? const Size(48.0, 48.0) : const Size(16.0, 16.0));
expect(icon.size, const Size(10.0, 10.0));
});
testWidgets('Small icons comply with VisualDensity requirements', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
final ThemeData themeDataM2 = ThemeData(
useMaterial3: material3,
visualDensity: const VisualDensity(horizontal: 1, vertical: -1),
);
final ThemeData themeDataM3 = ThemeData(
useMaterial3: material3,
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(
visualDensity: const VisualDensity(horizontal: 1, vertical: -1)
)
),
);
await tester.pumpWidget(
wrap(
useMaterial3: material3,
child: Theme(
data: material3 ? themeDataM3 : themeDataM2,
child: IconButton(
iconSize: 10.0,
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link),
constraints: const BoxConstraints(minWidth: 32.0, minHeight: 32.0),
),
),
),
);
final RenderBox iconButton = tester.renderObject(find.byType(IconButton));
// VisualDensity(horizontal: 1, vertical: -1) increases the icon's
// width by 4 pixels and decreases its height by 4 pixels, giving
// final width 32.0 + 4.0 = 36.0 and
// final height 32.0 - 4.0 = 28.0
expect(iconButton.size, material3 ? const Size(52.0, 44.0) : const Size(36.0, 28.0));
});
testWidgets('test default icon buttons are constrained', (WidgetTester tester) async {
await tester.pumpWidget(
wrap(
useMaterial3: theme.useMaterial3,
child: IconButton(
padding: EdgeInsets.zero,
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.ac_unit),
iconSize: 80.0,
),
),
);
final RenderBox box = tester.renderObject(find.byType(IconButton));
expect(box.size, const Size(80.0, 80.0));
});
testWidgets('test default icon buttons can be stretched if specified', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget> [
IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.ac_unit),
),
],
),
),
),
);
final RenderBox box = tester.renderObject(find.byType(IconButton));
expect(box.size, const Size(48.0, 600.0));
// Test for Material 3
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: colorScheme, useMaterial3: true),
home: Directionality(
textDirection: TextDirection.ltr,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget> [
IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.ac_unit),
),
],
),
),
)
);
final RenderBox boxM3 = tester.renderObject(find.byType(IconButton));
expect(boxM3.size, const Size(48.0, 600.0));
});
testWidgets('test default padding', (WidgetTester tester) async {
await tester.pumpWidget(
wrap(
useMaterial3: theme.useMaterial3,
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.ac_unit),
iconSize: 80.0,
),
),
);
final RenderBox box = tester.renderObject(find.byType(IconButton));
expect(box.size, const Size(96.0, 96.0));
});
testWidgets('test default alignment', (WidgetTester tester) async {
await tester.pumpWidget(
wrap(
useMaterial3: theme.useMaterial3,
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.ac_unit),
iconSize: 80.0,
),
),
);
final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align)));
expect(align.alignment, Alignment.center);
});
testWidgets('test tooltip', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.ac_unit),
),
),
),
),
);
expect(find.byType(Tooltip), findsNothing);
// Clear the widget tree.
await tester.pumpWidget(Container(key: UniqueKey()));
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.ac_unit),
tooltip: 'Test tooltip',
),
),
),
),
);
expect(find.byType(Tooltip), findsOneWidget);
expect(find.byTooltip('Test tooltip'), findsOneWidget);
await tester.tap(find.byTooltip('Test tooltip'));
expect(mockOnPressedFunction.called, 1);
});
testWidgets('IconButton AppBar size', (WidgetTester tester) async {
final bool material3 = theme.useMaterial3;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
padding: EdgeInsets.zero,
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.ac_unit),
),
],
),
),
),
);
final RenderBox barBox = tester.renderObject(find.byType(AppBar));
final RenderBox iconBox = tester.renderObject(find.byType(IconButton));
expect(iconBox.size.height, material3 ? 48 : equals(barBox.size.height));
expect(tester.getCenter(find.byType(IconButton)).dy, 28);
});
// This test is very similar to the '...explicit splashColor and highlightColor' test
// in buttons_test.dart. If you change this one, you may want to also change that one.
testWidgets('IconButton with explicit splashColor and highlightColor - M2', (WidgetTester tester) async {
const Color directSplashColor = Color(0xFF00000F);
const Color directHighlightColor = Color(0xFF0000F0);
Widget buttonWidget = wrap(
useMaterial3: false,
child: IconButton(
icon: const Icon(Icons.android),
splashColor: directSplashColor,
highlightColor: directHighlightColor,
onPressed: () { /* enable the button */ },
),
);
await tester.pumpWidget(
Theme(
data: ThemeData(useMaterial3: false),
child: buttonWidget,
),
);
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start gesture
await tester.pump(const Duration(milliseconds: 200)); // wait for splash to be well under way
expect(
Material.of(tester.element(find.byType(IconButton))),
paints
..circle(color: directSplashColor)
..circle(color: directHighlightColor),
);
const Color themeSplashColor1 = Color(0xFF000F00);
const Color themeHighlightColor1 = Color(0xFF00FF00);
buttonWidget = wrap(
useMaterial3: false,
child: IconButton(
icon: const Icon(Icons.android),
onPressed: () { /* enable the button */ },
),
);
await tester.pumpWidget(
Theme(
data: ThemeData(
highlightColor: themeHighlightColor1,
splashColor: themeSplashColor1,
useMaterial3: false,
),
child: buttonWidget,
),
);
expect(
Material.of(tester.element(find.byType(IconButton))),
paints
..circle(color: themeSplashColor1)
..circle(color: themeHighlightColor1),
);
const Color themeSplashColor2 = Color(0xFF002200);
const Color themeHighlightColor2 = Color(0xFF001100);
await tester.pumpWidget(
Theme(
data: ThemeData(
highlightColor: themeHighlightColor2,
splashColor: themeSplashColor2,
useMaterial3: false,
),
child: buttonWidget, // same widget, so does not get updated because of us
),
);
expect(
Material.of(tester.element(find.byType(IconButton))),
paints
..circle(color: themeSplashColor2)
..circle(color: themeHighlightColor2),
);
await gesture.up();
});
testWidgets('IconButton with explicit splash radius - M2', (WidgetTester tester) async {
const double splashRadius = 30.0;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: IconButton(
icon: const Icon(Icons.android),
splashRadius: splashRadius,
onPressed: () { /* enable the button */ },
),
),
),
),
);
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // Start gesture.
await tester.pump(const Duration(milliseconds: 1000)); // Wait for splash to be well under way.
expect(
Material.of(tester.element(find.byType(IconButton))),
paints
..circle(radius: splashRadius),
);
await gesture.up();
});
testWidgets('IconButton Semantics (enabled) - M2', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
wrap(
useMaterial3: false,
child: IconButton(
onPressed: mockOnPressedFunction.handler,
icon: const Icon(Icons.link, semanticLabel: 'link'),
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: const Rect.fromLTRB(0.0, 0.0, 48.0, 48.0),
actions: <SemanticsAction>[
SemanticsAction.tap,
],
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
label: 'link',
),
],
), ignoreId: true, ignoreTransform: true));
semantics.dispose();
});
testWidgets('IconButton Semantics (disabled) - M2', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
wrap(
useMaterial3: false,
child: const IconButton(
onPressed: null,
icon: Icon(Icons.link, semanticLabel: 'link'),
),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: const Rect.fromLTRB(0.0, 0.0, 48.0, 48.0),
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isButton,
],
label: 'link',
),
],
), ignoreId: true, ignoreTransform: true));
semantics.dispose();
});
testWidgets('IconButton Semantics (selected) - M3', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
wrap(
useMaterial3: true,
child: IconButton(
onPressed: mockOnPressedFunction.handler,
isSelected: true,
icon: const Icon(Icons.link, semanticLabel: 'link'),
),
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
actions: <SemanticsAction>[
SemanticsAction.tap,
],
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
SemanticsFlag.isSelected,
],
label: 'link',
),
],
),
],
),
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
),
);
semantics.dispose();
});
testWidgets('IconButton loses focus when disabled.', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'IconButton');
await tester.pumpWidget(
wrap(
useMaterial3: theme.useMaterial3,
child: IconButton(
focusNode: focusNode,
autofocus: true,
onPressed: () {},
icon: const Icon(Icons.link),
),
),
);
await tester.pump();
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.pumpWidget(
wrap(
useMaterial3: theme.useMaterial3,
child: IconButton(
focusNode: focusNode,
autofocus: true,
onPressed: null,
icon: const Icon(Icons.link),
),
),
);
await tester.pump();
expect(focusNode.hasPrimaryFocus, isFalse);
focusNode.dispose();
});
testWidgets('IconButton keeps focus when disabled in directional navigation mode.', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'IconButton');
await tester.pumpWidget(
wrap(
useMaterial3: theme.useMaterial3,
child: MediaQuery(
data: const MediaQueryData(
navigationMode: NavigationMode.directional,
),
child: IconButton(
focusNode: focusNode,
autofocus: true,
onPressed: () {},
icon: const Icon(Icons.link),
),
),
),
);
await tester.pump();
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.pumpWidget(
wrap(
useMaterial3: theme.useMaterial3,
child: MediaQuery(
data: const MediaQueryData(
navigationMode: NavigationMode.directional,
),
child: IconButton(
focusNode: focusNode,
autofocus: true,
onPressed: null,
icon: const Icon(Icons.link),
),
),
),
);
await tester.pump();
expect(focusNode.hasPrimaryFocus, isTrue);
focusNode.dispose();
});
testWidgets("Disabled IconButton can't be traversed to when disabled.", (WidgetTester tester) async {
final FocusNode focusNode1 = FocusNode(debugLabel: 'IconButton 1');
final FocusNode focusNode2 = FocusNode(debugLabel: 'IconButton 2');
addTearDown(() {
focusNode1.dispose();
focusNode2.dispose();
});
await tester.pumpWidget(
wrap(
useMaterial3: theme.useMaterial3,
child: Column(
children: <Widget>[
IconButton(
focusNode: focusNode1,
autofocus: true,
onPressed: () {},
icon: const Icon(Icons.link),
),
IconButton(
focusNode: focusNode2,
onPressed: null,
icon: const Icon(Icons.link),
),
],
),
),
);
await tester.pump();
expect(focusNode1.hasPrimaryFocus, isTrue);
expect(focusNode2.hasPrimaryFocus, isFalse);
expect(focusNode1.nextFocus(), isFalse);
await tester.pump();
expect(focusNode1.hasPrimaryFocus, !kIsWeb);
expect(focusNode2.hasPrimaryFocus, isFalse);
});
group('feedback', () {
late FeedbackTester feedback;
setUp(() {
feedback = FeedbackTester();
});
tearDown(() {
feedback.dispose();
});
testWidgets('IconButton with disabled feedback', (WidgetTester tester) async {
final Widget button = Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconButton(
onPressed: () {},
enableFeedback: false,
icon: const Icon(Icons.link),
),
),
);
await tester.pumpWidget(
theme.useMaterial3
? MaterialApp(theme: theme, home: button)
: Material(child: button)
);
await tester.tap(find.byType(IconButton), pointer: 1);
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 0);
expect(feedback.hapticCount, 0);
});
testWidgets('IconButton with enabled feedback', (WidgetTester tester) async {
final Widget button = Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconButton(
onPressed: () {},
icon: const Icon(Icons.link),
),
),
);
await tester.pumpWidget(
theme.useMaterial3
? MaterialApp(theme: theme, home: button)
: Material(child: button),
);
await tester.tap(find.byType(IconButton), pointer: 1);
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
});
testWidgets('IconButton with enabled feedback by default', (WidgetTester tester) async {
final Widget button = Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconButton(
onPressed: () {},
icon: const Icon(Icons.link),
),
),
);
await tester.pumpWidget(
theme.useMaterial3
? MaterialApp(theme: theme, home: button)
: Material(child: button),
);
await tester.tap(find.byType(IconButton), pointer: 1);
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
});
});
testWidgets('IconButton responds to density changes.', (WidgetTester tester) async {
const Key key = Key('test');
final bool material3 = theme.useMaterial3;
Future<void> buildTest(VisualDensity visualDensity) async {
return tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: IconButton(
visualDensity: visualDensity,
key: key,
onPressed: () {},
icon: const Icon(Icons.play_arrow),
),
),
),
),
);
}
await buildTest(VisualDensity.standard);
final RenderBox box = tester.renderObject(find.byType(IconButton));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(48, 48)));
await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0));
await tester.pumpAndSettle();
expect(box.size, equals(material3 ? const Size(64, 64) : const Size(60, 60)));
await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0));
await tester.pumpAndSettle();
// IconButton is a subclass of ButtonStyleButton in Material 3, so the negative
// visualDensity cannot be applied to horizontal padding.
// The size of the Button with padding is (24 + 8 + 8, 24) -> (40, 24)
// minSize of M3 IconButton is (48 - 12, 48 - 12) -> (36, 36)
// So, the button size in Material 3 is (40, 36)
expect(box.size, equals(material3 ? const Size(40, 36) : const Size(40, 40)));
await buildTest(const VisualDensity(horizontal: 3.0, vertical: -3.0));
await tester.pumpAndSettle();
expect(box.size, equals(material3 ? const Size(64, 36) : const Size(60, 40)));
});
testWidgets('IconButton.mouseCursor changes cursor on hover', (WidgetTester tester) async {
// Test argument works
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconButton(
onPressed: () {},
mouseCursor: SystemMouseCursors.forbidden,
icon: const Icon(Icons.play_arrow),
),
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(IconButton)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden);
// Test default is click
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconButton(
onPressed: () {},
icon: const Icon(Icons.play_arrow),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
});
testWidgets('disabled IconButton has basic mouse cursor', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconButton(
onPressed: null, // null value indicates IconButton is disabled
icon: Icon(Icons.play_arrow),
),
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(IconButton)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('IconButton.mouseCursor overrides implicit setting of mouse cursor', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconButton(
onPressed: null,
mouseCursor: SystemMouseCursors.none,
icon: Icon(Icons.play_arrow),
),
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(IconButton)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.none);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconButton(
onPressed: () {},
mouseCursor: SystemMouseCursors.none,
icon: const Icon(Icons.play_arrow),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.none);
});
testWidgets('IconTheme opacity test', (WidgetTester tester) async {
final ThemeData theme = ThemeData.from(colorScheme: colorScheme, useMaterial3: false);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: IconButton(
icon: const Icon(Icons.add),
color: Colors.purple,
onPressed: () {},
)
),
),
)
);
Color? iconColor() => _iconStyle(tester, Icons.add)?.color;
expect(iconColor(), Colors.purple);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: IconTheme.merge(
data: const IconThemeData(opacity: 0.5),
child: IconButton(
icon: const Icon(Icons.add),
color: Colors.purple,
onPressed: () {},
),
)
),
),
)
);
Color? iconColorWithOpacity() => _iconStyle(tester, Icons.add)?.color;
expect(iconColorWithOpacity(), Colors.purple.withOpacity(0.5));
});
testWidgets('IconButton defaults - M3', (WidgetTester tester) async {
final ThemeData themeM3 = ThemeData.from(colorScheme: colorScheme, useMaterial3: true);
// Enabled IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton(
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
final Finder buttonMaterial = find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
);
Material material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align)));
expect(align.alignment, Alignment.center);
expect(tester.getSize(find.byIcon(Icons.ac_unit)), const Size(24.0, 24.0));
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start the splash animation
await tester.pump(const Duration(milliseconds: 100)); // splash is underway
await gesture.up();
await tester.pumpAndSettle();
material = tester.widget<Material>(buttonMaterial);
// No change vs enabled and not pressed.
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
// Disabled IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: const Center(
child: IconButton(
onPressed: null,
icon: Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
});
testWidgets('IconButton default overlayColor resolves pressed state', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: Builder(
builder: (BuildContext context) {
return IconButton(
onPressed: () {},
focusNode: focusNode,
icon: const Icon(Icons.add),
);
},
),
),
),
),
);
RenderObject overlayColor() {
return tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
}
// Hovered.
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08)));
// Highlighted (pressed).
await gesture.down(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect()..rect(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.1)));
// Remove pressed and hovered states
await gesture.up();
await tester.pumpAndSettle();
await gesture.moveTo(const Offset(0, 50));
await tester.pumpAndSettle();
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.1)));
focusNode.dispose();
});
testWidgets('IconButton.fill defaults - M3', (WidgetTester tester) async {
final ThemeData themeM3 = ThemeData.from(colorScheme: colorScheme, useMaterial3: true);
// Enabled IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton.filled(
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
final Finder buttonMaterial = find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
);
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
expect(iconColor(), colorScheme.onPrimary);
Material material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.primary);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align)));
expect(align.alignment, Alignment.center);
expect(tester.getSize(find.byIcon(Icons.ac_unit)), const Size(24.0, 24.0));
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start the splash animation
await tester.pump(const Duration(milliseconds: 100)); // splash is underway
await gesture.up();
await tester.pumpAndSettle();
material = tester.widget<Material>(buttonMaterial);
// No change vs enabled and not pressed.
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.primary);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
// Disabled IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: const Center(
child: IconButton.filled(
onPressed: null,
icon: Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.onSurface.withOpacity(0.12));
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
expect(iconColor(), colorScheme.onSurface.withOpacity(0.38));
});
testWidgets('IconButton.fill default overlayColor resolves pressed state', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: Builder(
builder: (BuildContext context) {
return IconButton.filled(
onPressed: () {},
focusNode: focusNode,
icon: const Icon(Icons.add),
);
},
),
),
),
),
);
RenderObject overlayColor() {
return tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
}
// Hovered.
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.onPrimary.withOpacity(0.08)));
// Highlighted (pressed).
await gesture.down(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect()..rect(color: theme.colorScheme.onPrimary.withOpacity(0.1)));
// Remove pressed and hovered states
await gesture.up();
await tester.pumpAndSettle();
await gesture.moveTo(const Offset(0, 50));
await tester.pumpAndSettle();
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.onPrimary.withOpacity(0.1)));
focusNode.dispose();
});
testWidgets('Toggleable IconButton.fill defaults - M3', (WidgetTester tester) async {
final ThemeData themeM3 = ThemeData.from(colorScheme: colorScheme, useMaterial3: true);
// Enabled selected IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton.filled(
isSelected: true,
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
final Finder buttonMaterial = find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
);
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
expect(iconColor(), colorScheme.onPrimary);
Material material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.primary);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align)));
expect(align.alignment, Alignment.center);
expect(tester.getSize(find.byIcon(Icons.ac_unit)), const Size(24.0, 24.0));
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start the splash animation
await tester.pump(const Duration(milliseconds: 100)); // splash is underway
await gesture.up();
await tester.pumpAndSettle();
material = tester.widget<Material>(buttonMaterial);
// No change vs enabled and not pressed.
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.primary);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
// Enabled unselected IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton.filled(
isSelected: false,
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.surfaceVariant);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
expect(iconColor(), colorScheme.primary);
// Disabled IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: const Center(
child: IconButton.filled(
isSelected: true,
onPressed: null,
icon: Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.onSurface.withOpacity(0.12));
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
expect(iconColor(), colorScheme.onSurface.withOpacity(0.38));
});
testWidgets('IconButton.filledTonal defaults - M3', (WidgetTester tester) async {
final ThemeData themeM3 = ThemeData.from(colorScheme: colorScheme, useMaterial3: true);
// Enabled IconButton.tonal
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton.filledTonal(
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
final Finder buttonMaterial = find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
);
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
expect(iconColor(), colorScheme.onSecondaryContainer);
Material material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.secondaryContainer);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align)));
expect(align.alignment, Alignment.center);
expect(tester.getSize(find.byIcon(Icons.ac_unit)), const Size(24.0, 24.0));
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start the splash animation
await tester.pump(const Duration(milliseconds: 100)); // splash is underway
await gesture.up();
await tester.pumpAndSettle();
material = tester.widget<Material>(buttonMaterial);
// No change vs enabled and not pressed.
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.secondaryContainer);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
// Disabled IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: const Center(
child: IconButton.filledTonal(
onPressed: null,
icon: Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.onSurface.withOpacity(0.12));
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
expect(iconColor(), colorScheme.onSurface.withOpacity(0.38));
});
testWidgets('IconButton.filledTonal default overlayColor resolves pressed state', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: Builder(
builder: (BuildContext context) {
return IconButton.filledTonal(
onPressed: () {},
focusNode: focusNode,
icon: const Icon(Icons.add),
);
},
),
),
),
),
);
RenderObject overlayColor() {
return tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
}
// Hovered.
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.onSecondaryContainer.withOpacity(0.08)));
// Highlighted (pressed).
await gesture.down(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect()..rect(color: theme.colorScheme.onSecondaryContainer.withOpacity(0.1)));
// Remove pressed and hovered states
await gesture.up();
await tester.pumpAndSettle();
await gesture.moveTo(const Offset(0, 50));
await tester.pumpAndSettle();
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.onSecondaryContainer.withOpacity(0.1)));
focusNode.dispose();
});
testWidgets('Toggleable IconButton.filledTonal defaults - M3', (WidgetTester tester) async {
final ThemeData themeM3 = ThemeData.from(colorScheme: colorScheme, useMaterial3: true);
// Enabled selected IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton.filledTonal(
isSelected: true,
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
final Finder buttonMaterial = find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
);
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
expect(iconColor(), colorScheme.onSecondaryContainer);
Material material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.secondaryContainer);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align)));
expect(align.alignment, Alignment.center);
expect(tester.getSize(find.byIcon(Icons.ac_unit)), const Size(24.0, 24.0));
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start the splash animation
await tester.pump(const Duration(milliseconds: 100)); // splash is underway
await gesture.up();
await tester.pumpAndSettle();
material = tester.widget<Material>(buttonMaterial);
// No change vs enabled and not pressed.
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.secondaryContainer);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
// Enabled unselected IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton.filledTonal(
isSelected: false,
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.surfaceVariant);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
expect(iconColor(), colorScheme.onSurfaceVariant);
// Disabled IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: const Center(
child: IconButton.filledTonal(
isSelected: true,
onPressed: null,
icon: Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.onSurface.withOpacity(0.12));
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
expect(iconColor(), colorScheme.onSurface.withOpacity(0.38));
});
testWidgets('IconButton.outlined defaults - M3', (WidgetTester tester) async {
final ThemeData themeM3 = ThemeData.from(colorScheme: colorScheme, useMaterial3: true);
// Enabled IconButton.tonal
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton.outlined(
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
final Finder buttonMaterial = find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
);
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
expect(iconColor(), colorScheme.onSurfaceVariant);
Material material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, StadiumBorder(side: BorderSide(color: colorScheme.outline)));
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align)));
expect(align.alignment, Alignment.center);
expect(tester.getSize(find.byIcon(Icons.ac_unit)), const Size(24.0, 24.0));
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start the splash animation
await tester.pump(const Duration(milliseconds: 100)); // splash is underway
await gesture.up();
await tester.pumpAndSettle();
material = tester.widget<Material>(buttonMaterial);
// No change vs enabled and not pressed.
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, StadiumBorder(side: BorderSide(color: colorScheme.outline)));
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
// Disabled IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: const Center(
child: IconButton.outlined(
onPressed: null,
icon: Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, StadiumBorder(side: BorderSide(color: colorScheme.onSurface.withOpacity(0.12))));
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
expect(iconColor(), colorScheme.onSurface.withOpacity(0.38));
});
testWidgets('IconButton.outlined default overlayColor resolves pressed state', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: Builder(
builder: (BuildContext context) {
return IconButton.outlined(
onPressed: () {},
focusNode: focusNode,
icon: const Icon(Icons.add),
);
},
),
),
),
),
);
RenderObject overlayColor() {
return tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
}
// Hovered.
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08)));
// Highlighted (pressed).
await gesture.down(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect()..rect(color: theme.colorScheme.onSurface.withOpacity(0.1)));
// Remove pressed and hovered states
await gesture.up();
await tester.pumpAndSettle();
await gesture.moveTo(const Offset(0, 50));
await tester.pumpAndSettle();
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08)));
focusNode.dispose();
});
testWidgets('Toggleable IconButton.outlined defaults - M3', (WidgetTester tester) async {
final ThemeData themeM3 = ThemeData.from(colorScheme: colorScheme, useMaterial3: true);
// Enabled selected IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton.outlined(
isSelected: true,
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
final Finder buttonMaterial = find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
);
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
expect(iconColor(), colorScheme.onInverseSurface);
Material material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.inverseSurface);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align)));
expect(align.alignment, Alignment.center);
expect(tester.getSize(find.byIcon(Icons.ac_unit)), const Size(24.0, 24.0));
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start the splash animation
await tester.pump(const Duration(milliseconds: 100)); // splash is underway
await gesture.up();
await tester.pumpAndSettle();
material = tester.widget<Material>(buttonMaterial);
// No change vs enabled and not pressed.
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.inverseSurface);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
// Enabled unselected IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: Center(
child: IconButton.outlined(
isSelected: false,
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, StadiumBorder(side: BorderSide(color: colorScheme.outline)));
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
expect(iconColor(), colorScheme.onSurfaceVariant);
// Disabled IconButton
await tester.pumpWidget(
MaterialApp(
theme: themeM3,
home: const Center(
child: IconButton.outlined(
isSelected: true,
onPressed: null,
icon: Icon(Icons.ac_unit),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, colorScheme.onSurface.withOpacity(0.12));
expect(material.elevation, 0.0);
expect(material.shadowColor, Colors.transparent);
expect(material.shape, const StadiumBorder());
expect(material.textStyle, null);
expect(material.type, MaterialType.button);
expect(iconColor(), colorScheme.onSurface.withOpacity(0.38));
});
testWidgets('Default IconButton meets a11y contrast guidelines - M3', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: Scaffold(
body: Center(
child: IconButton(
onPressed: () { },
focusNode: focusNode,
icon: const Icon(Icons.ac_unit),
),
),
),
),
);
// Default, not disabled.
await expectLater(tester, meetsGuideline(textContrastGuideline));
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
await expectLater(tester, meetsGuideline(textContrastGuideline));
// Hovered.
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
await expectLater(tester, meetsGuideline(textContrastGuideline));
// Highlighted (pressed).
await gesture.down(center);
await tester.pump(); // Start the splash and highlight animations.
await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
await expectLater(tester, meetsGuideline(textContrastGuideline));
await gesture.removePointer();
focusNode.dispose();
},
skip: isBrowser, // https://github.com/flutter/flutter/issues/44115
);
testWidgets('IconButton uses stateful color for icon color in different states - M3', (WidgetTester tester) async {
bool isSelected = false;
final FocusNode focusNode = FocusNode();
const Color pressedColor = Color(0x00000001);
const Color hoverColor = Color(0x00000002);
const Color focusedColor = Color(0x00000003);
const Color defaultColor = Color(0x00000004);
const Color selectedColor = Color(0x00000005);
Color getIconColor(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedColor;
}
if (states.contains(MaterialState.hovered)) {
return hoverColor;
}
if (states.contains(MaterialState.focused)) {
return focusedColor;
}
if (states.contains(MaterialState.selected)) {
return selectedColor;
}
return defaultColor;
}
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
body: Center(
child: IconButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith<Color>(getIconColor),
),
isSelected: isSelected,
onPressed: () {
setState(() {
isSelected = !isSelected;
});
},
focusNode: focusNode,
icon: const Icon(Icons.ac_unit),
),
),
);
}
),
),
);
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
// Default, not disabled.
expect(iconColor(), equals(defaultColor));
// Selected
final Finder button = find.byType(IconButton);
await tester.tap(button);
await tester.pumpAndSettle();
expect(iconColor(), selectedColor);
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(iconColor(), focusedColor);
// Hovered.
final Offset center = tester.getCenter(find.byType(IconButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(iconColor(), hoverColor);
// Highlighted (pressed).
await gesture.down(center);
await tester.pump(); // Start the splash and highlight animations.
await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
expect(iconColor(), pressedColor);
focusNode.dispose();
});
testWidgets('Does IconButton contribute semantics - M3', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Theme(
data: ThemeData(useMaterial3: true),
child: IconButton(
style: const ButtonStyle(
// Specifying minimumSize to mimic the original minimumSize for
// RaisedButton so that the semantics tree's rect and transform
// match the original version of this test.
minimumSize: MaterialStatePropertyAll<Size>(Size(88, 36)),
),
onPressed: () { },
icon: const Icon(Icons.ac_unit),
),
),
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
actions: <SemanticsAction>[
SemanticsAction.tap,
],
rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0),
transform: Matrix4.translationValues(356.0, 276.0, 0.0),
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
),
],
),
ignoreId: true,
));
semantics.dispose();
});
testWidgets('IconButton size is configurable by ThemeData.materialTapTargetSize - M3', (WidgetTester tester) async {
Widget buildFrame(MaterialTapTargetSize tapTargetSize) {
return Theme(
data: ThemeData(materialTapTargetSize: tapTargetSize, useMaterial3: true),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconButton(
style: IconButton.styleFrom(minimumSize: const Size(40, 40)),
icon: const Icon(Icons.ac_unit),
onPressed: () { },
),
),
),
);
}
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.padded));
expect(tester.getSize(find.byType(IconButton)), const Size(48.0, 48.0));
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.shrinkWrap));
expect(tester.getSize(find.byType(IconButton)), const Size(40.0, 40.0));
});
testWidgets('Override IconButton default padding - M3', (WidgetTester tester) async {
// Use [IconButton]'s padding property to override default value.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: Scaffold(
body: Center(
child: IconButton(
padding: const EdgeInsets.all(20),
onPressed: () {},
icon: const Icon(Icons.ac_unit),
),
),
),
)
);
final Padding paddingWidget1 = tester.widget<Padding>(
find.descendant(
of: find.byType(IconButton),
matching: find.byType(Padding),
),
);
expect(paddingWidget1.padding, const EdgeInsets.all(20));
// Use [IconButton.style]'s padding property to override default value.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: Scaffold(
body: Center(
child: IconButton(
style: IconButton.styleFrom(padding: const EdgeInsets.all(20)),
onPressed: () {},
icon: const Icon(Icons.ac_unit),
),
),
),
)
);
final Padding paddingWidget2 = tester.widget<Padding>(
find.descendant(
of: find.byType(IconButton),
matching: find.byType(Padding),
),
);
expect(paddingWidget2.padding, const EdgeInsets.all(20));
// [IconButton.style]'s padding will override [IconButton]'s padding if both
// values are not null.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: Scaffold(
body: Center(
child: IconButton(
padding: const EdgeInsets.all(15),
style: IconButton.styleFrom(padding: const EdgeInsets.all(22)),
onPressed: () {},
icon: const Icon(Icons.ac_unit),
),
),
),
)
);
final Padding paddingWidget3 = tester.widget<Padding>(
find.descendant(
of: find.byType(IconButton),
matching: find.byType(Padding),
),
);
expect(paddingWidget3.padding, const EdgeInsets.all(22));
});
testWidgets('Default IconButton is not selectable - M3', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: IconButton(icon: const Icon(Icons.ac_unit), onPressed: (){},)
)
);
final Finder button = find.byType(IconButton);
IconButton buttonWidget() => tester.widget<IconButton>(button);
Material buttonMaterial() {
return tester.widget<Material>(
find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
)
);
}
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
expect(buttonWidget().isSelected, null);
expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
expect(buttonMaterial().color, Colors.transparent);
await tester.tap(button); // The non-toggle IconButton should not change appearance after clicking
await tester.pumpAndSettle();
expect(buttonWidget().isSelected, null);
expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
expect(buttonMaterial().color, Colors.transparent);
});
testWidgets('Icon button is selectable when isSelected is not null - M3', (WidgetTester tester) async {
bool isSelected = false;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return IconButton(
isSelected: isSelected,
icon: const Icon(Icons.ac_unit),
onPressed: (){
setState(() {
isSelected = !isSelected;
});
},
);
}
)
)
);
final Finder button = find.byType(IconButton);
IconButton buttonWidget() => tester.widget<IconButton>(button);
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
Material buttonMaterial() {
return tester.widget<Material>(
find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
)
);
}
expect(buttonWidget().isSelected, false);
expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
expect(buttonMaterial().color, Colors.transparent);
await tester.tap(button); // The toggle IconButton should change appearance after clicking
await tester.pumpAndSettle();
expect(buttonWidget().isSelected, true);
expect(iconColor(), equals(const ColorScheme.light().primary));
expect(buttonMaterial().color, Colors.transparent);
await tester.tap(button); // The IconButton should be unselected if it's clicked again
await tester.pumpAndSettle();
expect(buttonWidget().isSelected, false);
expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
expect(buttonMaterial().color, Colors.transparent);
});
testWidgets('The IconButton is in selected status if isSelected is true by default - M3', (WidgetTester tester) async {
bool isSelected = true;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return IconButton(
isSelected: isSelected,
icon: const Icon(Icons.ac_unit),
onPressed: (){
setState(() {
isSelected = !isSelected;
});
},
);
}
)
)
);
final Finder button = find.byType(IconButton);
IconButton buttonWidget() => tester.widget<IconButton>(button);
Color? iconColor() => _iconStyle(tester, Icons.ac_unit)?.color;
Material buttonMaterial() {
return tester.widget<Material>(
find.descendant(
of: find.byType(IconButton),
matching: find.byType(Material),
)
);
}
expect(buttonWidget().isSelected, true);
expect(iconColor(), equals(const ColorScheme.light().primary));
expect(buttonMaterial().color, Colors.transparent);
await tester.tap(button); // The IconButton becomes unselected if it's clicked
await tester.pumpAndSettle();
expect(buttonWidget().isSelected, false);
expect(iconColor(), equals(const ColorScheme.light().onSurfaceVariant));
expect(buttonMaterial().color, Colors.transparent);
});
testWidgets("The selectedIcon is used if it's not null and the button is clicked" , (WidgetTester tester) async {
bool isSelected = false;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return IconButton(
isSelected: isSelected,
selectedIcon: const Icon(Icons.account_box),
icon: const Icon(Icons.account_box_outlined),
onPressed: (){
setState(() {
isSelected = !isSelected;
});
},
);
}
)
)
);
final Finder button = find.byType(IconButton);
expect(find.byIcon(Icons.account_box_outlined), findsOneWidget);
expect(find.byIcon(Icons.account_box), findsNothing);
await tester.tap(button); // The icon becomes to selectedIcon
await tester.pumpAndSettle();
expect(find.byIcon(Icons.account_box), findsOneWidget);
expect(find.byIcon(Icons.account_box_outlined), findsNothing);
await tester.tap(button); // The icon becomes the original icon when it's clicked again
await tester.pumpAndSettle();
expect(find.byIcon(Icons.account_box_outlined), findsOneWidget);
expect(find.byIcon(Icons.account_box), findsNothing);
});
testWidgets('The original icon is used for selected and unselected status when selectedIcon is null' , (WidgetTester tester) async {
bool isSelected = false;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return IconButton(
isSelected: isSelected,
icon: const Icon(Icons.account_box),
onPressed: (){
setState(() {
isSelected = !isSelected;
});
},
);
}
)
)
);
final Finder button = find.byType(IconButton);
IconButton buttonWidget() => tester.widget<IconButton>(button);
expect(buttonWidget().isSelected, false);
expect(buttonWidget().selectedIcon, null);
expect(find.byIcon(Icons.account_box), findsOneWidget);
await tester.tap(button); // The icon becomes the original icon when it's clicked again
await tester.pumpAndSettle();
expect(buttonWidget().isSelected, true);
expect(buttonWidget().selectedIcon, null);
expect(find.byIcon(Icons.account_box), findsOneWidget);
});
testWidgets('The selectedIcon is used for disabled button if isSelected is true - M3' , (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: const IconButton(
isSelected: true,
icon: Icon(Icons.account_box),
selectedIcon: Icon(Icons.ac_unit),
onPressed: null,
)
)
);
final Finder button = find.byType(IconButton);
IconButton buttonWidget() => tester.widget<IconButton>(button);
expect(buttonWidget().isSelected, true);
expect(find.byIcon(Icons.account_box), findsNothing);
expect(find.byIcon(Icons.ac_unit), findsOneWidget);
});
testWidgets('The visualDensity of M3 IconButton can be configured by IconButtonTheme, '
'but cannot be configured by ThemeData - M3' , (WidgetTester tester) async {
Future<void> buildTest({VisualDensity? iconButtonThemeVisualDensity, VisualDensity? themeVisualDensity}) async {
return tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: colorScheme, useMaterial3: true).copyWith(
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(visualDensity: iconButtonThemeVisualDensity)
),
visualDensity: themeVisualDensity
),
home: Material(
child: Center(
child: IconButton(
onPressed: () {},
icon: const Icon(Icons.play_arrow),
),
),
),
),
);
}
await buildTest(iconButtonThemeVisualDensity: VisualDensity.standard);
final RenderBox box = tester.renderObject(find.byType(IconButton));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(48, 48)));
await buildTest(iconButtonThemeVisualDensity: VisualDensity.compact);
await tester.pumpAndSettle();
expect(box.size, equals(const Size(40, 40)));
await buildTest(iconButtonThemeVisualDensity: const VisualDensity(horizontal: 3.0, vertical: 3.0));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(64, 64)));
// ThemeData.visualDensity will be ignored because useMaterial3 is true
await buildTest(themeVisualDensity: VisualDensity.standard);
await tester.pumpAndSettle();
expect(box.size, equals(const Size(48, 48)));
await buildTest(themeVisualDensity: VisualDensity.compact);
await tester.pumpAndSettle();
expect(box.size, equals(const Size(48, 48)));
await buildTest(themeVisualDensity: const VisualDensity(horizontal: 3.0, vertical: 3.0));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(48, 48)));
});
group('IconTheme tests in Material 3', () {
testWidgets('IconTheme overrides default values in M3', (WidgetTester tester) async {
// Theme's IconTheme
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(
colorScheme: const ColorScheme.light(),
useMaterial3: true,
).copyWith(
iconTheme: const IconThemeData(color: Colors.red, size: 37),
),
home: IconButton(
icon: const Icon(Icons.account_box),
onPressed: () {},
)
)
);
Color? iconColor0() => _iconStyle(tester, Icons.account_box)?.color;
expect(iconColor0(), Colors.red);
expect(tester.getSize(find.byIcon(Icons.account_box)), equals(const Size(37, 37)),);
// custom IconTheme outside of IconButton
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(
colorScheme: const ColorScheme.light(),
useMaterial3: true,
),
home: IconTheme.merge(
data: const IconThemeData(color: Colors.pink, size: 35),
child: IconButton(
icon: const Icon(Icons.account_box),
onPressed: () {},
),
)
)
);
Color? iconColor1() => _iconStyle(tester, Icons.account_box)?.color;
expect(iconColor1(), Colors.pink);
expect(tester.getSize(find.byIcon(Icons.account_box)), equals(const Size(35, 35)),);
});
testWidgets('Theme IconButtonTheme overrides IconTheme in Material3', (WidgetTester tester) async {
// When IconButtonTheme and IconTheme both exist in ThemeData, the IconButtonTheme can override IconTheme.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(
colorScheme: const ColorScheme.light(),
useMaterial3: true,
).copyWith(
iconTheme: const IconThemeData(color: Colors.red, size: 25),
iconButtonTheme: IconButtonThemeData(style: IconButton.styleFrom(foregroundColor: Colors.green, iconSize: 27),)
),
home: IconButton(
icon: const Icon(Icons.account_box),
onPressed: () {},
)
)
);
Color? iconColor() => _iconStyle(tester, Icons.account_box)?.color;
expect(iconColor(), Colors.green);
expect(tester.getSize(find.byIcon(Icons.account_box)), equals(const Size(27, 27)),);
});
testWidgets('Button IconButtonTheme always overrides IconTheme in Material3', (WidgetTester tester) async {
// When IconButtonTheme is closer to IconButton, IconButtonTheme overrides IconTheme
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(
colorScheme: const ColorScheme.light(),
useMaterial3: true,
),
home: IconTheme.merge(
data: const IconThemeData(color: Colors.orange, size: 36),
child: IconButtonTheme(
data: IconButtonThemeData(style: IconButton.styleFrom(foregroundColor: Colors.blue, iconSize: 35)),
child: IconButton(
icon: const Icon(Icons.account_box),
onPressed: () {},
),
),
)
)
);
Color? iconColor0() => _iconStyle(tester, Icons.account_box)?.color;
expect(iconColor0(), Colors.blue);
expect(tester.getSize(find.byIcon(Icons.account_box)), equals(const Size(35, 35)),);
// When IconTheme is closer to IconButton, IconButtonTheme still overrides IconTheme
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(
colorScheme: const ColorScheme.light(),
useMaterial3: true,
),
home: IconTheme.merge(
data: const IconThemeData(color: Colors.blue, size: 35),
child: IconButtonTheme(
data: IconButtonThemeData(style: IconButton.styleFrom(foregroundColor: Colors.orange, iconSize: 36)),
child: IconButton(
icon: const Icon(Icons.account_box),
onPressed: () {},
),
),
)
)
);
Color? iconColor1() => _iconStyle(tester, Icons.account_box)?.color;
expect(iconColor1(), Colors.orange);
expect(tester.getSize(find.byIcon(Icons.account_box)), equals(const Size(36, 36)),);
});
testWidgets('White icon color defined by users shows correctly in Material3', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(
colorScheme: const ColorScheme.dark(),
useMaterial3: true,
).copyWith(
iconTheme: const IconThemeData(color: Colors.white),
),
home: IconButton(
icon: const Icon(Icons.account_box),
onPressed: () {},
)
)
);
Color? iconColor1() => _iconStyle(tester, Icons.account_box)?.color;
expect(iconColor1(), Colors.white);
});
testWidgets('In light mode, icon color is M3 default color instead of IconTheme.of(context).color, '
'if only setting color in IconTheme', (WidgetTester tester) async {
final ColorScheme darkScheme = const ColorScheme.dark().copyWith(onSurfaceVariant: const Color(0xffe91e60));
// Brightness.dark
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(colorScheme: darkScheme, useMaterial3: true,),
home: Scaffold(
body: IconTheme.merge(
data: const IconThemeData(size: 26),
child: IconButton(
icon: const Icon(Icons.account_box),
onPressed: () {},
),
),
)
)
);
Color? iconColor0() => _iconStyle(tester, Icons.account_box)?.color;
expect(iconColor0(), darkScheme.onSurfaceVariant); // onSurfaceVariant
});
testWidgets('In dark mode, icon color is M3 default color instead of IconTheme.of(context).color, '
'if only setting color in IconTheme', (WidgetTester tester) async {
final ColorScheme lightScheme = const ColorScheme.light().copyWith(onSurfaceVariant: const Color(0xffe91e60));
// Brightness.dark
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(colorScheme: lightScheme, useMaterial3: true,),
home: Scaffold(
body: IconTheme.merge(
data: const IconThemeData(size: 26),
child: IconButton(
icon: const Icon(Icons.account_box),
onPressed: () {},
),
),
)
)
);
Color? iconColor0() => _iconStyle(tester, Icons.account_box)?.color;
expect(iconColor0(), lightScheme.onSurfaceVariant); // onSurfaceVariant
});
testWidgets('black87 icon color defined by users shows correctly in Material3', (WidgetTester tester) async {
});
testWidgets("IconButton.styleFrom doesn't throw exception on passing only one cursor", (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/118071.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: IconButton(
style: OutlinedButton.styleFrom(
enabledMouseCursor: SystemMouseCursors.text,
),
onPressed: () {},
icon: const Icon(Icons.add),
),
),
),
);
expect(tester.takeException(), isNull);
});
testWidgets('Material3 - IconButton memory leak', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/130708.
Widget buildWidget(bool showIconButton) {
return showIconButton
? MaterialApp(
theme: ThemeData(useMaterial3: true),
home: IconButton(
onPressed: () { },
icon: const Icon(Icons.search),
),
)
: const SizedBox();
}
await tester.pumpWidget(buildWidget(true));
await tester.pumpWidget(buildWidget(false));
// No exception is thrown.
});
});
}
Widget wrap({required Widget child, required bool useMaterial3}) {
return useMaterial3
? MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(child: child),
)),
)
: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(child: child),
),
),
);
}
TextStyle? _iconStyle(WidgetTester tester, IconData icon) {
final RichText iconRichText = tester.widget<RichText>(
find.descendant(of: find.byIcon(icon), matching: find.byType(RichText)),
);
return iconRichText.text.style;
}
| flutter/packages/flutter/test/material/icon_button_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/icon_button_test.dart",
"repo_id": "flutter",
"token_count": 40332
} | 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 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
const Key key = Key('testContainer');
const Color trueColor = Colors.red;
const Color falseColor = Colors.green;
/// Mock widget which plays the role of a button -- it can emit notifications
/// that [MaterialState] values are now in or out of play.
class _InnerWidget extends StatefulWidget {
const _InnerWidget({required this.onValueChanged, required this.controller});
final ValueChanged<bool> onValueChanged;
final StreamController<bool> controller;
@override
_InnerWidgetState createState() => _InnerWidgetState();
}
class _InnerWidgetState extends State<_InnerWidget> {
@override
void initState() {
super.initState();
widget.controller.stream.listen((bool val) => widget.onValueChanged(val));
}
@override
Widget build(BuildContext context) => Container();
}
class _MyWidget extends StatefulWidget {
const _MyWidget({
required this.controller,
required this.evaluator,
required this.materialState,
});
/// Wrapper around `MaterialStateMixin.isPressed/isHovered/isFocused/etc`.
final bool Function(_MyWidgetState state) evaluator;
/// Stream passed down to the child [_InnerWidget] to begin the process.
/// This plays the role of an actual user interaction in the wild, but allows
/// us to engage the system without mocking pointers/hovers etc.
final StreamController<bool> controller;
/// The value we're watching in the given test.
final MaterialState materialState;
@override
State createState() => _MyWidgetState();
}
class _MyWidgetState extends State<_MyWidget> with MaterialStateMixin {
@override
Widget build(BuildContext context) {
return ColoredBox(
key: key,
color: widget.evaluator(this) ? trueColor : falseColor,
child: _InnerWidget(
onValueChanged: updateMaterialState(widget.materialState),
controller: widget.controller,
),
);
}
}
void main() {
Future<void> verify(WidgetTester tester, Widget widget, StreamController<bool> controller,) async {
await tester.pumpWidget(MaterialApp(home: Scaffold(body: widget)));
// Set the value to True
controller.sink.add(true);
await tester.pumpAndSettle();
expect(tester.widget<ColoredBox>(find.byKey(key)).color, trueColor);
// Set the value to False
controller.sink.add(false);
await tester.pumpAndSettle();
expect(tester.widget<ColoredBox>(find.byKey(key)).color, falseColor);
}
testWidgets('MaterialState.pressed is tracked', (WidgetTester tester) async {
final StreamController<bool> controller = StreamController<bool>();
final _MyWidget widget = _MyWidget(
controller: controller,
evaluator: (_MyWidgetState state) => state.isPressed,
materialState: MaterialState.pressed,
);
await verify(tester, widget, controller);
});
testWidgets('MaterialState.focused is tracked', (WidgetTester tester) async {
final StreamController<bool> controller = StreamController<bool>();
final _MyWidget widget = _MyWidget(
controller: controller,
evaluator: (_MyWidgetState state) => state.isFocused,
materialState: MaterialState.focused,
);
await verify(tester, widget, controller);
});
testWidgets('MaterialState.hovered is tracked', (WidgetTester tester) async {
final StreamController<bool> controller = StreamController<bool>();
final _MyWidget widget = _MyWidget(
controller: controller,
evaluator: (_MyWidgetState state) => state.isHovered,
materialState: MaterialState.hovered,
);
await verify(tester, widget, controller);
});
testWidgets('MaterialState.disabled is tracked', (WidgetTester tester) async {
final StreamController<bool> controller = StreamController<bool>();
final _MyWidget widget = _MyWidget(
controller: controller,
evaluator: (_MyWidgetState state) => state.isDisabled,
materialState: MaterialState.disabled,
);
await verify(tester, widget, controller);
});
testWidgets('MaterialState.selected is tracked', (WidgetTester tester) async {
final StreamController<bool> controller = StreamController<bool>();
final _MyWidget widget = _MyWidget(
controller: controller,
evaluator: (_MyWidgetState state) => state.isSelected,
materialState: MaterialState.selected,
);
await verify(tester, widget, controller);
});
testWidgets('MaterialState.scrolledUnder is tracked', (WidgetTester tester) async {
final StreamController<bool> controller = StreamController<bool>();
final _MyWidget widget = _MyWidget(
controller: controller,
evaluator: (_MyWidgetState state) => state.isScrolledUnder,
materialState: MaterialState.scrolledUnder,
);
await verify(tester, widget, controller);
});
testWidgets('MaterialState.dragged is tracked', (WidgetTester tester) async {
final StreamController<bool> controller = StreamController<bool>();
final _MyWidget widget = _MyWidget(
controller: controller,
evaluator: (_MyWidgetState state) => state.isDragged,
materialState: MaterialState.dragged,
);
await verify(tester, widget, controller);
});
testWidgets('MaterialState.error is tracked', (WidgetTester tester) async {
final StreamController<bool> controller = StreamController<bool>();
final _MyWidget widget = _MyWidget(
controller: controller,
evaluator: (_MyWidgetState state) => state.isErrored,
materialState: MaterialState.error,
);
await verify(tester, widget, controller);
});
}
| flutter/packages/flutter/test/material/material_state_mixin_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/material_state_mixin_test.dart",
"repo_id": "flutter",
"token_count": 1842
} | 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.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() {
testWidgets('OutlinedButton, OutlinedButton.icon defaults', (WidgetTester tester) async {
const ColorScheme colorScheme = ColorScheme.light();
final ThemeData theme = ThemeData.from(colorScheme: colorScheme);
final bool material3 = theme.useMaterial3;
// Enabled OutlinedButton
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Center(
child: OutlinedButton(
onPressed: () { },
child: const Text('button'),
),
),
),
);
final Finder buttonMaterial = find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(Material),
);
Material material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, material3 ? Colors.transparent : const Color(0xff000000));
expect(material.shape, material3
? StadiumBorder(side: BorderSide(color: colorScheme.outline))
: RoundedRectangleBorder(
side: BorderSide(color: colorScheme.onSurface.withOpacity(0.12)),
borderRadius: const BorderRadius.all(Radius.circular(4))
));
expect(material.textStyle!.color, colorScheme.primary);
expect(material.textStyle!.fontFamily, 'Roboto');
expect(material.textStyle!.fontSize, 14);
expect(material.textStyle!.fontWeight, FontWeight.w500);
expect(material.type, MaterialType.button);
final Align align = tester.firstWidget<Align>(find.ancestor(of: find.text('button'), matching: find.byType(Align)));
expect(align.alignment, Alignment.center);
final Offset center = tester.getCenter(find.byType(OutlinedButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start the splash animation
await tester.pump(const Duration(milliseconds: 100)); // splash is underway
// Material 3 uses the InkSparkle which uses a shader, so we can't capture
// the effect with paint methods.
if (!material3) {
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..circle(color: colorScheme.primary.withOpacity(0.12)));
}
await gesture.up();
await tester.pumpAndSettle();
// No change vs enabled and not pressed.
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, material3 ? Colors.transparent : const Color(0xff000000));
expect(material.shape, material3
? StadiumBorder(side: BorderSide(color: colorScheme.outline))
: RoundedRectangleBorder(
side: BorderSide(color: colorScheme.onSurface.withOpacity(0.12)),
borderRadius: const BorderRadius.all(Radius.circular(4))
));
expect(material.textStyle!.color, colorScheme.primary);
expect(material.textStyle!.fontFamily, 'Roboto');
expect(material.textStyle!.fontSize, 14);
expect(material.textStyle!.fontWeight, FontWeight.w500);
expect(material.type, MaterialType.button);
// Enabled OutlinedButton.icon
final Key iconButtonKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Center(
child: OutlinedButton.icon(
key: iconButtonKey,
onPressed: () { },
icon: const Icon(Icons.add),
label: const Text('label'),
),
),
),
);
final Finder iconButtonMaterial = find.descendant(
of: find.byKey(iconButtonKey),
matching: find.byType(Material),
);
material = tester.widget<Material>(iconButtonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, material3 ? Colors.transparent : const Color(0xff000000));
expect(material.shape, material3
? StadiumBorder(side: BorderSide(color: colorScheme.outline))
: RoundedRectangleBorder(
side: BorderSide(color: colorScheme.onSurface.withOpacity(0.12)),
borderRadius: const BorderRadius.all(Radius.circular(4))
));
expect(material.textStyle!.color, colorScheme.primary);
expect(material.textStyle!.fontFamily, 'Roboto');
expect(material.textStyle!.fontSize, 14);
expect(material.textStyle!.fontWeight, FontWeight.w500);
expect(material.type, MaterialType.button);
// Disabled OutlinedButton
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Center(
child: OutlinedButton(
onPressed: null,
child: Text('button'),
),
),
),
);
material = tester.widget<Material>(buttonMaterial);
expect(material.animationDuration, const Duration(milliseconds: 200));
expect(material.borderOnForeground, true);
expect(material.borderRadius, null);
expect(material.clipBehavior, Clip.none);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shadowColor, material3 ? Colors.transparent : const Color(0xff000000));
expect(material.shape, material3
? StadiumBorder(side: BorderSide(color: colorScheme.onSurface.withOpacity(0.12)))
: RoundedRectangleBorder(
side: BorderSide(color: colorScheme.onSurface.withOpacity(0.12)),
borderRadius: const BorderRadius.all(Radius.circular(4))
));
expect(material.textStyle!.color, colorScheme.onSurface.withOpacity(0.38));
expect(material.textStyle!.fontFamily, 'Roboto');
expect(material.textStyle!.fontSize, 14);
expect(material.textStyle!.fontWeight, FontWeight.w500);
expect(material.type, MaterialType.button);
});
testWidgets('OutlinedButton.icon produces the correct widgets if icon is null', (WidgetTester tester) async {
const ColorScheme colorScheme = ColorScheme.light();
final ThemeData theme = ThemeData.from(colorScheme: colorScheme);
final Key iconButtonKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Center(
child: OutlinedButton.icon(
key: iconButtonKey,
onPressed: () { },
icon: const Icon(Icons.add),
label: const Text('label'),
),
),
),
);
expect(find.byIcon(Icons.add), findsOneWidget);
expect(find.text('label'), findsOneWidget);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Center(
child: OutlinedButton.icon(
key: iconButtonKey,
onPressed: () { },
// No icon specified.
label: const Text('label'),
),
),
),
);
expect(find.byIcon(Icons.add), findsNothing);
expect(find.text('label'), findsOneWidget);
});
testWidgets('OutlinedButton default overlayColor resolves pressed state', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: Builder(
builder: (BuildContext context) {
return OutlinedButton(
onPressed: () {},
focusNode: focusNode,
child: const Text('OutlinedButton'),
);
},
),
),
),
),
);
RenderObject overlayColor() {
return tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
}
// Hovered.
final Offset center = tester.getCenter(find.byType(OutlinedButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.primary.withOpacity(0.08)));
// Highlighted (pressed).
await gesture.down(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect()..rect(color: theme.colorScheme.primary.withOpacity(0.1)));
// Remove pressed and hovered states
await gesture.up();
await tester.pumpAndSettle();
await gesture.moveTo(const Offset(0, 50));
await tester.pumpAndSettle();
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.primary.withOpacity(0.1)));
focusNode.dispose();
});
testWidgets('Does OutlinedButton work with hover', (WidgetTester tester) async {
const Color hoverColor = Color(0xff001122);
Color? getOverlayColor(Set<MaterialState> states) {
return states.contains(MaterialState.hovered) ? hoverColor : null;
}
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
style: ButtonStyle(
overlayColor: MaterialStateProperty.resolveWith<Color?>(getOverlayColor),
),
onPressed: () { },
child: const Text('button'),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(OutlinedButton)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..rect(color: hoverColor));
});
testWidgets('Does OutlinedButton work with focus', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
final ColorScheme colors = theme.colorScheme;
const Color focusColor = Color(0xff001122);
Color? getOverlayColor(Set<MaterialState> states) {
return states.contains(MaterialState.focused) ? focusColor : null;
}
final FocusNode focusNode = FocusNode(debugLabel: 'OutlinedButton Node');
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: OutlinedButton(
style: ButtonStyle(
overlayColor: MaterialStateProperty.resolveWith<Color?>(getOverlayColor),
),
focusNode: focusNode,
onPressed: () { },
child: const Text('button'),
),
),
);
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
focusNode.requestFocus();
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..rect(color: focusColor));
final Finder buttonMaterial = find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(Material),
);
final Material material = tester.widget<Material>(buttonMaterial);
expect(material.shape, StadiumBorder(side: BorderSide(color: colors.primary)));
focusNode.dispose();
});
testWidgets('Does OutlinedButton work with autofocus', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
final ColorScheme colors = theme.colorScheme;
const Color focusColor = Color(0xff001122);
Color? getOverlayColor(Set<MaterialState> states) {
return states.contains(MaterialState.focused) ? focusColor : null;
}
final FocusNode focusNode = FocusNode(debugLabel: 'OutlinedButton Node');
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: OutlinedButton(
autofocus: true,
style: ButtonStyle(
overlayColor: MaterialStateProperty.resolveWith<Color?>(getOverlayColor),
),
focusNode: focusNode,
onPressed: () { },
child: const Text('button'),
),
),
);
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..rect(color: focusColor));
final Finder buttonMaterial = find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(Material),
);
final Material material = tester.widget<Material>(buttonMaterial);
expect(material.shape, StadiumBorder(side: BorderSide(color: colors.primary)));
focusNode.dispose();
});
testWidgets('Default OutlinedButton meets a11y contrast guidelines', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light()),
home: Scaffold(
body: Center(
child: OutlinedButton(
onPressed: () {},
focusNode: focusNode,
child: const Text('OutlinedButton'),
),
),
),
),
);
// Default, not disabled.
await expectLater(tester, meetsGuideline(textContrastGuideline));
// Hovered.
final Offset center = tester.getCenter(find.byType(OutlinedButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
await expectLater(tester, meetsGuideline(textContrastGuideline));
// Highlighted (pressed).
await gesture.down(center);
await tester.pump(); // Start the splash and highlight animations.
await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
await expectLater(tester, meetsGuideline(textContrastGuideline));
await gesture.up();
await tester.pumpAndSettle();
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
await expectLater(tester, meetsGuideline(textContrastGuideline));
focusNode.dispose();
},
skip: isBrowser, // https://github.com/flutter/flutter/issues/44115
);
testWidgets('OutlinedButton with colored theme meets a11y contrast guidelines', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
Color getTextColor(Set<MaterialState> states) {
final Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue[900]!;
}
return Colors.blue[800]!;
}
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: ColorScheme.fromSwatch()),
home: Scaffold(
backgroundColor: Colors.white,
body: Center(
child: OutlinedButtonTheme(
data: OutlinedButtonThemeData(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith<Color>(getTextColor),
),
),
child: Builder(
builder: (BuildContext context) {
return OutlinedButton(
onPressed: () {},
focusNode: focusNode,
child: const Text('OutlinedButton'),
);
},
),
),
),
),
),
);
// Default, not disabled.
await expectLater(tester, meetsGuideline(textContrastGuideline));
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
await expectLater(tester, meetsGuideline(textContrastGuideline));
// Hovered.
final Offset center = tester.getCenter(find.byType(OutlinedButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
await expectLater(tester, meetsGuideline(textContrastGuideline));
// Highlighted (pressed).
await gesture.down(center);
await tester.pump(); // Start the splash and highlight animations.
await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
await expectLater(tester, meetsGuideline(textContrastGuideline));
focusNode.dispose();
},
skip: isBrowser, // https://github.com/flutter/flutter/issues/44115
);
testWidgets('OutlinedButton uses stateful color for text color in different states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
const Color pressedColor = Color(0x00000001);
const Color hoverColor = Color(0x00000002);
const Color focusedColor = Color(0x00000003);
const Color defaultColor = Color(0x00000004);
Color getTextColor(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedColor;
}
if (states.contains(MaterialState.hovered)) {
return hoverColor;
}
if (states.contains(MaterialState.focused)) {
return focusedColor;
}
return defaultColor;
}
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: OutlinedButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith<Color>(getTextColor),
),
onPressed: () {},
focusNode: focusNode,
child: const Text('OutlinedButton'),
),
),
),
),
);
Color textColor() {
return tester.renderObject<RenderParagraph>(find.text('OutlinedButton')).text.style!.color!;
}
// Default, not disabled.
expect(textColor(), equals(defaultColor));
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(textColor(), focusedColor);
// Hovered.
final Offset center = tester.getCenter(find.byType(OutlinedButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(textColor(), hoverColor);
// Highlighted (pressed).
await gesture.down(center);
await tester.pump(); // Start the splash and highlight animations.
await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
expect(textColor(), pressedColor);
focusNode.dispose();
});
testWidgets('OutlinedButton uses stateful color for icon color in different states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
final Key buttonKey = UniqueKey();
const Color pressedColor = Color(0x00000001);
const Color hoverColor = Color(0x00000002);
const Color focusedColor = Color(0x00000003);
const Color defaultColor = Color(0x00000004);
Color getIconColor(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedColor;
}
if (states.contains(MaterialState.hovered)) {
return hoverColor;
}
if (states.contains(MaterialState.focused)) {
return focusedColor;
}
return defaultColor;
}
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: OutlinedButton.icon(
key: buttonKey,
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith<Color>(getIconColor),
),
icon: const Icon(Icons.add),
label: const Text('OutlinedButton'),
onPressed: () {},
focusNode: focusNode,
),
),
),
),
);
Color iconColor() => _iconStyle(tester, Icons.add).color!;
// Default, not disabled.
expect(iconColor(), equals(defaultColor));
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(iconColor(), focusedColor);
// Hovered.
final Offset center = tester.getCenter(find.byKey(buttonKey));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(iconColor(), hoverColor);
// Highlighted (pressed).
await gesture.down(center);
await tester.pump(); // Start the splash and highlight animations.
await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
expect(iconColor(), pressedColor);
focusNode.dispose();
});
testWidgets('OutlinedButton uses stateful color for border color in different states', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
const Color pressedColor = Color(0x00000001);
const Color hoverColor = Color(0x00000002);
const Color focusedColor = Color(0x00000003);
const Color defaultColor = Color(0x00000004);
BorderSide getBorderSide(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return const BorderSide(color: pressedColor);
}
if (states.contains(MaterialState.hovered)) {
return const BorderSide(color: hoverColor);
}
if (states.contains(MaterialState.focused)) {
return const BorderSide(color: focusedColor);
}
return const BorderSide(color: defaultColor);
}
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: OutlinedButton(
style: ButtonStyle(
side: MaterialStateProperty.resolveWith<BorderSide>(getBorderSide),
// Test assumes a rounded rect for the shape
shape: ButtonStyleButton.allOrNull(
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))
),
),
onPressed: () {},
focusNode: focusNode,
child: const Text('OutlinedButton'),
),
),
),
),
);
final Finder outlinedButton = find.byType(OutlinedButton);
// Default, not disabled.
expect(outlinedButton, paints..drrect(color: defaultColor));
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(outlinedButton, paints..drrect(color: focusedColor));
// Hovered.
final Offset center = tester.getCenter(find.byType(OutlinedButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(outlinedButton, paints..drrect(color: hoverColor));
// Highlighted (pressed).
await gesture.down(center);
await tester.pumpAndSettle();
expect(outlinedButton, paints..drrect(color: pressedColor));
focusNode.dispose();
});
testWidgets('OutlinedButton onPressed and onLongPress callbacks are correctly called when non-null', (WidgetTester tester) async {
bool wasPressed;
Finder outlinedButton;
Widget buildFrame({ VoidCallback? onPressed, VoidCallback? onLongPress }) {
return Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
onPressed: onPressed,
onLongPress: onLongPress,
child: const Text('button'),
),
);
}
// onPressed not null, onLongPress null.
wasPressed = false;
await tester.pumpWidget(
buildFrame(onPressed: () { wasPressed = true; }),
);
outlinedButton = find.byType(OutlinedButton);
expect(tester.widget<OutlinedButton>(outlinedButton).enabled, true);
await tester.tap(outlinedButton);
expect(wasPressed, true);
// onPressed null, onLongPress not null.
wasPressed = false;
await tester.pumpWidget(
buildFrame(onLongPress: () { wasPressed = true; }),
);
outlinedButton = find.byType(OutlinedButton);
expect(tester.widget<OutlinedButton>(outlinedButton).enabled, true);
await tester.longPress(outlinedButton);
expect(wasPressed, true);
// onPressed null, onLongPress null.
await tester.pumpWidget(
buildFrame(),
);
outlinedButton = find.byType(OutlinedButton);
expect(tester.widget<OutlinedButton>(outlinedButton).enabled, false);
});
testWidgets("OutlinedButton response doesn't hover when disabled", (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch;
final FocusNode focusNode = FocusNode(debugLabel: 'OutlinedButton Focus');
final GlobalKey childKey = GlobalKey();
bool hovering = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: 100,
height: 100,
child: OutlinedButton(
autofocus: true,
onPressed: () {},
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(
Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: 100,
height: 100,
child: OutlinedButton(
focusNode: focusNode,
onHover: (bool value) { hovering = value; },
onPressed: null,
child: SizedBox(key: childKey),
),
),
),
);
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
focusNode.dispose();
});
testWidgets('disabled and hovered OutlinedButton responds to mouse-exit', (WidgetTester tester) async {
int onHoverCount = 0;
late bool hover;
Widget buildFrame({ required bool enabled }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: OutlinedButton(
onPressed: enabled ? () { } : null,
onHover: (bool value) {
onHoverCount += 1;
hover = value;
},
child: const Text('OutlinedButton'),
),
),
),
);
}
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(OutlinedButton)));
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 OutlinedButton 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(OutlinedButton)));
await tester.pumpAndSettle();
// We no longer see hover events because the OutlinedButton 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 OutlinedButton 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(OutlinedButton)) - const Offset(1, 1));
await tester.pumpAndSettle();
// Moving the mouse a little within the OutlinedButton doesn't change anything.
expect(onHoverCount, 2);
expect(hover, false);
});
testWidgets('Can set OutlinedButton focus and Can set unFocus.', (WidgetTester tester) async {
final FocusNode node = FocusNode(debugLabel: 'OutlinedButton Focus');
bool gotFocus = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
focusNode: node,
onFocusChange: (bool focused) => gotFocus = focused,
onPressed: () { },
child: const SizedBox(),
),
),
);
node.requestFocus();
await tester.pump();
expect(gotFocus, isTrue);
expect(node.hasFocus, isTrue);
node.unfocus();
await tester.pump();
expect(gotFocus, isFalse);
expect(node.hasFocus, isFalse);
node.dispose();
});
testWidgets('When OutlinedButton disable, Can not set OutlinedButton focus.', (WidgetTester tester) async {
final FocusNode node = FocusNode(debugLabel: 'OutlinedButton Focus');
bool gotFocus = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
focusNode: node,
onFocusChange: (bool focused) => gotFocus = focused,
onPressed: null,
child: const SizedBox(),
),
),
);
node.requestFocus();
await tester.pump();
expect(gotFocus, isFalse);
expect(node.hasFocus, isFalse);
node.dispose();
});
testWidgets("Outline button doesn't crash if disabled during a gesture", (WidgetTester tester) async {
Widget buildFrame(VoidCallback? onPressed) {
return Directionality(
textDirection: TextDirection.ltr,
child: Theme(
data: ThemeData(),
child: Center(
child: OutlinedButton(onPressed: onPressed, child: const Text('button')),
),
),
);
}
await tester.pumpWidget(buildFrame(() {}));
await tester.press(find.byType(OutlinedButton));
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(null));
await tester.pumpAndSettle();
});
testWidgets('OutlinedButton shape and border component overrides', (WidgetTester tester) async {
const Color fillColor = Color(0xFF00FF00);
const BorderSide disabledBorderSide = BorderSide(color: Color(0xFFFF0000), width: 3);
const BorderSide enabledBorderSide = BorderSide(color: Color(0xFFFF00FF), width: 4);
const BorderSide pressedBorderSide = BorderSide(color: Color(0xFF0000FF), width: 5);
Widget buildFrame({ VoidCallback? onPressed }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Theme(
data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, textTheme: Typography.englishLike2014),
child: Container(
alignment: Alignment.topLeft,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
shape: const RoundedRectangleBorder(), // default border radius is 0
backgroundColor: fillColor,
minimumSize: const Size(64, 36),
).copyWith(
side: MaterialStateProperty.resolveWith<BorderSide>((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return disabledBorderSide;
}
if (states.contains(MaterialState.pressed)) {
return pressedBorderSide;
}
return enabledBorderSide;
}),
),
clipBehavior: Clip.antiAlias,
onPressed: onPressed,
child: const Text('button'),
),
),
),
);
}
final Finder outlinedButton = find.byType(OutlinedButton);
BorderSide getBorderSide() {
final OutlinedBorder border = tester.widget<Material>(
find.descendant(of: outlinedButton, matching: find.byType(Material)),
).shape! as OutlinedBorder;
return border.side;
}
// Pump a button with a null onPressed callback to make it disabled.
await tester.pumpWidget(
buildFrame(),
);
// Expect that the button is disabled and painted with the disabled border color.
expect(tester.widget<OutlinedButton>(outlinedButton).enabled, false);
expect(getBorderSide(), disabledBorderSide);
// Pump a new button with a no-op onPressed callback to make it enabled.
await tester.pumpWidget(
buildFrame(onPressed: () {}),
);
// Wait for the border color to change from disabled to enabled.
await tester.pumpAndSettle();
expect(getBorderSide(), enabledBorderSide);
final Offset center = tester.getCenter(outlinedButton);
final TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start gesture
// Wait for the border's color to change to pressed
await tester.pump(const Duration(milliseconds: 200));
expect(getBorderSide(), pressedBorderSide);
// Tap gesture completes, button returns to its initial configuration.
await gesture.up();
await tester.pumpAndSettle();
expect(getBorderSide(), enabledBorderSide);
});
testWidgets('OutlinedButton has no clip by default', (WidgetTester tester) async {
final GlobalKey buttonKey = GlobalKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: OutlinedButton(
key: buttonKey,
onPressed: () {},
child: const Text('ABC'),
),
),
),
);
expect(
tester.renderObject(find.byKey(buttonKey)),
paintsExactlyCountTimes(#clipPath, 0),
);
});
testWidgets('OutlinedButton contributes semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Theme(
data: ThemeData(useMaterial3: false),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: OutlinedButton(
style: const ButtonStyle(
// Specifying minimumSize to mimic the original minimumSize for
// RaisedButton so that the corresponding button size matches
// the original version of this test.
minimumSize: MaterialStatePropertyAll<Size>(Size(88, 36)),
),
onPressed: () {},
child: const Text('ABC'),
),
),
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
actions: <SemanticsAction>[
SemanticsAction.tap,
],
label: 'ABC',
rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0),
transform: Matrix4.translationValues(356.0, 276.0, 0.0),
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
),
],
),
ignoreId: true,
));
semantics.dispose();
});
testWidgets('OutlinedButton scales textScaleFactor', (WidgetTester tester) async {
await tester.pumpWidget(
Theme(
data: ThemeData(useMaterial3: false),
child: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: Center(
child: OutlinedButton(
style: const ButtonStyle(
// Specifying minimumSize to mimic the original minimumSize for
// RaisedButton so that the corresponding button size matches
// the original version of this test.
minimumSize: MaterialStatePropertyAll<Size>(Size(88, 36)),
),
onPressed: () {},
child: const Text('ABC'),
),
),
),
),
),
);
expect(tester.getSize(find.byType(OutlinedButton)), equals(const Size(88.0, 48.0)));
expect(tester.getSize(find.byType(Text)), equals(const Size(42.0, 14.0)));
// textScaleFactor expands text, but not button.
await tester.pumpWidget(
Theme(
// Force Material 2 typography.
data: ThemeData(useMaterial3: false),
child: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery.withClampedTextScaling(
minScaleFactor: 1.25,
maxScaleFactor: 1.25,
child: Center(
child: OutlinedButton(
style: const ButtonStyle(
// Specifying minimumSize to mimic the original minimumSize for
// RaisedButton so that the corresponding button size matches
// the original version of this test.
minimumSize: MaterialStatePropertyAll<Size>(Size(88, 36)),
),
onPressed: () {},
child: const Text('ABC'),
),
),
),
),
),
);
expect(tester.getSize(find.byType(OutlinedButton)), equals(const Size(88.0, 48.0)));
expect(tester.getSize(find.byType(Text)), const Size(52.5, 18.0));
// Set text scale large enough to expand text and button.
await tester.pumpWidget(
Theme(
data: ThemeData(useMaterial3: false),
child: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery.withClampedTextScaling(
minScaleFactor: 3.0,
maxScaleFactor: 3.0,
child: Center(
child: OutlinedButton(
onPressed: () {},
child: const Text('ABC'),
),
),
),
),
),
);
expect(tester.getSize(find.byType(OutlinedButton)), const Size(134.0, 48.0));
expect(tester.getSize(find.byType(Text)), const Size(126.0, 42.0));
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/122066
testWidgets('OutlinedButton onPressed and onLongPress callbacks are distinctly recognized', (WidgetTester tester) async {
bool didPressButton = false;
bool didLongPressButton = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
onPressed: () {
didPressButton = true;
},
onLongPress: () {
didLongPressButton = true;
},
child: const Text('button'),
),
),
);
final Finder outlinedButton = find.byType(OutlinedButton);
expect(tester.widget<OutlinedButton>(outlinedButton).enabled, true);
expect(didPressButton, isFalse);
await tester.tap(outlinedButton);
expect(didPressButton, isTrue);
expect(didLongPressButton, isFalse);
await tester.longPress(outlinedButton);
expect(didLongPressButton, isTrue);
});
testWidgets('OutlinedButton responds to density changes.', (WidgetTester tester) async {
const Key key = Key('test');
const Key childKey = Key('test child');
Future<void> buildTest(VisualDensity visualDensity, {bool useText = false}) async {
return tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: OutlinedButton(
style: ButtonStyle(
visualDensity: visualDensity,
minimumSize: ButtonStyleButton.allOrNull(const Size(64, 36)),
),
key: key,
onPressed: () {},
child: useText
? const Text('Text', key: childKey)
: Container(key: childKey, width: 100, height: 100, color: const Color(0xffff0000)),
),
),
),
),
);
}
await buildTest(VisualDensity.standard);
final RenderBox box = tester.renderObject(find.byKey(key));
Rect childRect = tester.getRect(find.byKey(childKey));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(132, 100)));
expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350)));
await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0));
await tester.pumpAndSettle();
childRect = tester.getRect(find.byKey(childKey));
expect(box.size, equals(const Size(156, 124)));
expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350)));
await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0));
await tester.pumpAndSettle();
childRect = tester.getRect(find.byKey(childKey));
expect(box.size, equals(const Size(132, 100)));
expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350)));
await buildTest(VisualDensity.standard, useText: true);
await tester.pumpAndSettle();
childRect = tester.getRect(find.byKey(childKey));
expect(box.size, equals(const Size(88, 48)));
expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0)));
await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0), useText: true);
await tester.pumpAndSettle();
childRect = tester.getRect(find.byKey(childKey));
expect(box.size, equals(const Size(112, 60)));
expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0)));
await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0), useText: true);
await tester.pumpAndSettle();
childRect = tester.getRect(find.byKey(childKey));
expect(box.size, equals(const Size(88, 36)));
expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0)));
});
group('Default OutlinedButton padding for textScaleFactor, textDirection', () {
const ValueKey<String> buttonKey = ValueKey<String>('button');
const ValueKey<String> labelKey = ValueKey<String>('label');
const ValueKey<String> iconKey = ValueKey<String>('icon');
const List<double> textScaleFactorOptions = <double>[0.5, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0];
const List<TextDirection> textDirectionOptions = <TextDirection>[TextDirection.ltr, TextDirection.rtl];
const List<Widget?> iconOptions = <Widget?>[null, Icon(Icons.add, size: 18, key: iconKey)];
// Expected values for each textScaleFactor.
final Map<double, double> paddingVertical = <double, double>{
0.5: 0,
1: 0,
1.25: 0,
1.5: 0,
2: 0,
2.5: 0,
3: 0,
4: 0,
};
final Map<double, double> paddingWithIconGap = <double, double>{
0.5: 8,
1: 8,
1.25: 7,
1.5: 6,
2: 4,
2.5: 4,
3: 4,
4: 4,
};
final Map<double, double> paddingHorizontal = <double, double>{
0.5: 16,
1: 16,
1.25: 14,
1.5: 12,
2: 8,
2.5: 6,
3: 4,
4: 4,
};
Rect globalBounds(RenderBox renderBox) {
final Offset topLeft = renderBox.localToGlobal(Offset.zero);
return topLeft & renderBox.size;
}
/// Computes the padding between two [Rect]s, one inside the other.
EdgeInsets paddingBetween({ required Rect parent, required Rect child }) {
assert (parent.intersect(child) == child);
return EdgeInsets.fromLTRB(
child.left - parent.left,
child.top - parent.top,
parent.right - child.right,
parent.bottom - child.bottom,
);
}
for (final double textScaleFactor in textScaleFactorOptions) {
for (final TextDirection textDirection in textDirectionOptions) {
for (final Widget? icon in iconOptions) {
final String testName = <String>[
'OutlinedButton, text scale $textScaleFactor',
if (icon != null)
'with icon',
if (textDirection == TextDirection.rtl)
'RTL',
].join(', ');
testWidgets(testName, (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: false,
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(minimumSize: const Size(64, 36)),
),
),
home: Builder(
builder: (BuildContext context) {
return MediaQuery.withClampedTextScaling(
minScaleFactor: textScaleFactor,
maxScaleFactor: textScaleFactor,
child: Directionality(
textDirection: textDirection,
child: Scaffold(
body: Center(
child: icon == null
? OutlinedButton(
key: buttonKey,
onPressed: () {},
child: const Text('button', key: labelKey),
)
: OutlinedButton.icon(
key: buttonKey,
onPressed: () {},
icon: icon,
label: const Text('button', key: labelKey),
),
),
),
),
);
},
),
),
);
final Element paddingElement = tester.element(
find.descendant(
of: find.byKey(buttonKey),
matching: find.byType(Padding),
),
);
expect(Directionality.of(paddingElement), textDirection);
final Padding paddingWidget = paddingElement.widget as Padding;
// Compute expected padding, and check.
final double expectedPaddingTop = paddingVertical[textScaleFactor]!;
final double expectedPaddingBottom = paddingVertical[textScaleFactor]!;
final double expectedPaddingStart = paddingHorizontal[textScaleFactor]!;
final double expectedPaddingEnd = expectedPaddingStart;
final EdgeInsets expectedPadding = EdgeInsetsDirectional.fromSTEB(
expectedPaddingStart,
expectedPaddingTop,
expectedPaddingEnd,
expectedPaddingBottom,
).resolve(textDirection);
expect(paddingWidget.padding.resolve(textDirection), expectedPadding);
// Measure padding in terms of the difference between the button and its label child
// and check that.
final RenderBox labelRenderBox = tester.renderObject<RenderBox>(find.byKey(labelKey));
final Rect labelBounds = globalBounds(labelRenderBox);
final RenderBox? iconRenderBox = icon == null ? null : tester.renderObject<RenderBox>(find.byKey(iconKey));
final Rect? iconBounds = icon == null ? null : globalBounds(iconRenderBox!);
final Rect childBounds = icon == null ? labelBounds : labelBounds.expandToInclude(iconBounds!);
// We measure the `InkResponse` descendant of the button
// element, because the button has a larger `RenderBox`
// which accommodates the minimum tap target with a height
// of 48.
final RenderBox buttonRenderBox = tester.renderObject<RenderBox>(
find.descendant(
of: find.byKey(buttonKey),
matching: find.byWidgetPredicate(
(Widget widget) => widget is InkResponse,
),
),
);
final Rect buttonBounds = globalBounds(buttonRenderBox);
final EdgeInsets visuallyMeasuredPadding = paddingBetween(
parent: buttonBounds,
child: childBounds,
);
// Since there is a requirement of a minimum width of 64
// and a minimum height of 36 on material buttons, the visual
// padding of smaller buttons may not match their settings.
// Therefore, we only test buttons that are large enough.
if (buttonBounds.width > 64) {
expect(
visuallyMeasuredPadding.left,
expectedPadding.left,
);
expect(
visuallyMeasuredPadding.right,
expectedPadding.right,
);
}
if (buttonBounds.height > 36) {
expect(
visuallyMeasuredPadding.top,
expectedPadding.top,
);
expect(
visuallyMeasuredPadding.bottom,
expectedPadding.bottom,
);
}
// Check the gap between the icon and the label
if (icon != null) {
final double gapWidth = textDirection == TextDirection.ltr
? labelBounds.left - iconBounds!.right
: iconBounds!.left - labelBounds.right;
expect(gapWidth, paddingWithIconGap[textScaleFactor]);
}
// Check the text's height - should be consistent with the textScaleFactor.
final RenderBox textRenderObject = tester.renderObject<RenderBox>(
find.descendant(
of: find.byKey(labelKey),
matching: find.byElementPredicate(
(Element element) => element.widget is RichText,
),
),
);
final double textHeight = textRenderObject.paintBounds.size.height;
final double expectedTextHeight = 14 * textScaleFactor;
expect(textHeight, moreOrLessEquals(expectedTextHeight, epsilon: 0.5));
});
}
}
}
});
testWidgets('Override OutlinedButton default padding', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return MediaQuery.withClampedTextScaling(
minScaleFactor: 2,
maxScaleFactor: 2,
child: Scaffold(
body: Center(
child: OutlinedButton(
style: OutlinedButton.styleFrom(padding: const EdgeInsets.all(22)),
onPressed: () {},
child: const Text('OutlinedButton'),
),
),
),
);
},
),
),
);
final Padding paddingWidget = tester.widget<Padding>(
find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(Padding),
),
);
expect(paddingWidget.padding, const EdgeInsets.all(22));
});
testWidgets('Override theme fontSize changes padding', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(
colorScheme: const ColorScheme.light(),
textTheme: const TextTheme(labelLarge: TextStyle(fontSize: 28.0)),
),
home: Builder(
builder: (BuildContext context) {
return Scaffold(
body: Center(
child: OutlinedButton(
onPressed: () {},
child: const Text('text'),
),
),
);
},
),
),
);
final Padding paddingWidget = tester.widget<Padding>(
find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(Padding),
),
);
expect(paddingWidget.padding, const EdgeInsets.symmetric(horizontal: 12));
});
testWidgets('M3 OutlinedButton has correct padding', (WidgetTester tester) async {
final Key key = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: Scaffold(
body: Center(
child: OutlinedButton(
key: key,
onPressed: () {},
child: const Text('OutlinedButton'),
),
),
),
),
);
final Padding paddingWidget = tester.widget<Padding>(
find.descendant(
of: find.byKey(key),
matching: find.byType(Padding),
),
);
expect(paddingWidget.padding, const EdgeInsets.symmetric(horizontal: 24));
});
testWidgets('M3 OutlinedButton.icon has correct padding', (WidgetTester tester) async {
final Key key = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true),
home: Scaffold(
body: Center(
child: OutlinedButton.icon(
key: key,
icon: const Icon(Icons.favorite),
onPressed: () {},
label: const Text('OutlinedButton'),
),
),
),
),
);
final Padding paddingWidget = tester.widget<Padding>(
find.descendant(
of: find.byKey(key),
matching: find.byType(Padding),
),
);
expect(paddingWidget.padding, const EdgeInsetsDirectional.fromSTEB(16.0, 0.0, 24.0, 0.0));
});
testWidgets('Fixed size OutlinedButtons', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
OutlinedButton(
style: OutlinedButton.styleFrom(fixedSize: const Size(100, 100)),
onPressed: () {},
child: const Text('100x100'),
),
OutlinedButton(
style: OutlinedButton.styleFrom(fixedSize: const Size.fromWidth(200)),
onPressed: () {},
child: const Text('200xh'),
),
OutlinedButton(
style: OutlinedButton.styleFrom(fixedSize: const Size.fromHeight(200)),
onPressed: () {},
child: const Text('wx200'),
),
],
),
),
),
);
expect(tester.getSize(find.widgetWithText(OutlinedButton, '100x100')), const Size(100, 100));
expect(tester.getSize(find.widgetWithText(OutlinedButton, '200xh')).width, 200);
expect(tester.getSize(find.widgetWithText(OutlinedButton, 'wx200')).height, 200);
});
testWidgets('OutlinedButton with NoSplash splashFactory paints nothing', (WidgetTester tester) async {
Widget buildFrame({ InteractiveInkFeatureFactory? splashFactory }) {
return MaterialApp(
home: Scaffold(
body: Center(
child: OutlinedButton(
style: OutlinedButton.styleFrom(
splashFactory: splashFactory,
),
onPressed: () { },
child: const Text('test'),
),
),
),
);
}
// NoSplash.splashFactory, no splash circles drawn
await tester.pumpWidget(buildFrame(splashFactory: NoSplash.splashFactory));
{
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('test')));
final MaterialInkController material = Material.of(tester.element(find.text('test')));
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 0));
await gesture.up();
await tester.pumpAndSettle();
}
// InkRipple.splashFactory, one splash circle drawn.
await tester.pumpWidget(buildFrame(splashFactory: InkRipple.splashFactory));
{
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('test')));
final MaterialInkController material = Material.of(tester.element(find.text('test')));
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
await gesture.up();
await tester.pumpAndSettle();
}
});
testWidgets('OutlinedButton uses InkSparkle only for Android non-web when useMaterial3 is true', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Center(
child: OutlinedButton(
onPressed: () { },
child: const Text('button'),
),
),
),
);
final InkWell buttonInkWell = tester.widget<InkWell>(find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(InkWell),
));
if (debugDefaultTargetPlatformOverride! == TargetPlatform.android && !kIsWeb) {
expect(buttonInkWell.splashFactory, equals(InkSparkle.splashFactory));
} else {
expect(buttonInkWell.splashFactory, equals(InkRipple.splashFactory));
}
}, variant: TargetPlatformVariant.all());
testWidgets('OutlinedButton uses InkRipple when useMaterial3 is false', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Center(
child: OutlinedButton(
onPressed: () { },
child: const Text('button'),
),
),
),
);
final InkWell buttonInkWell = tester.widget<InkWell>(find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(InkWell),
));
expect(buttonInkWell.splashFactory, equals(InkRipple.splashFactory));
}, variant: TargetPlatformVariant.all());
testWidgets('OutlinedButton.icon does not overflow', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/77815
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 200,
child: OutlinedButton.icon(
onPressed: () {},
icon: const Icon(Icons.add),
label: const Text( // Much wider than 200
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a euismod nibh. Morbi laoreet purus.',
),
),
),
),
),
);
expect(tester.takeException(), null);
});
testWidgets('OutlinedButton.icon icon,label layout', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
final Key iconKey = UniqueKey();
final Key labelKey = UniqueKey();
final ButtonStyle style = OutlinedButton.styleFrom(
padding: EdgeInsets.zero,
visualDensity: VisualDensity.standard, // dx=0, dy=0
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 200,
child: OutlinedButton.icon(
key: buttonKey,
style: style,
onPressed: () {},
icon: SizedBox(key: iconKey, width: 50, height: 100),
label: SizedBox(key: labelKey, width: 50, height: 100),
),
),
),
),
);
// The button's label and icon are separated by a gap of 8:
// 46 [icon 50] 8 [label 50] 46
// The overall button width is 200. So:
// icon.x = 46
// label.x = 46 + 50 + 8 = 104
expect(tester.getRect(find.byKey(buttonKey)), const Rect.fromLTRB(0.0, 0.0, 200.0, 100.0));
expect(tester.getRect(find.byKey(iconKey)), const Rect.fromLTRB(46.0, 0.0, 96.0, 100.0));
expect(tester.getRect(find.byKey(labelKey)), const Rect.fromLTRB(104.0, 0.0, 154.0, 100.0));
});
testWidgets('OutlinedButton maximumSize', (WidgetTester tester) async {
final Key key0 = UniqueKey();
final Key key1 = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
OutlinedButton(
key: key0,
style: OutlinedButton.styleFrom(
minimumSize: const Size(24, 36),
maximumSize: const Size.fromWidth(64),
),
onPressed: () { },
child: const Text('A B C D E F G H I J K L M N O P'),
),
OutlinedButton.icon(
key: key1,
style: OutlinedButton.styleFrom(
minimumSize: const Size(24, 36),
maximumSize: const Size.fromWidth(104),
),
onPressed: () {},
icon: Container(color: Colors.red, width: 32, height: 32),
label: const Text('A B C D E F G H I J K L M N O P'),
),
],
),
),
),
),
);
expect(tester.getSize(find.byKey(key0)), const Size(64.0, 224.0));
expect(tester.getSize(find.byKey(key1)), const Size(104.0, 224.0));
});
testWidgets('Fixed size OutlinedButton, same as minimumSize == maximumSize', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
OutlinedButton(
style: OutlinedButton.styleFrom(fixedSize: const Size(200, 200)),
onPressed: () { },
child: const Text('200x200'),
),
OutlinedButton(
style: OutlinedButton.styleFrom(
minimumSize: const Size(200, 200),
maximumSize: const Size(200, 200),
),
onPressed: () { },
child: const Text('200,200'),
),
],
),
),
),
);
expect(tester.getSize(find.widgetWithText(OutlinedButton, '200x200')), const Size(200, 200));
expect(tester.getSize(find.widgetWithText(OutlinedButton, '200,200')), const Size(200, 200));
});
testWidgets('OutlinedButton changes mouse cursor when hovered', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
enabledMouseCursor: SystemMouseCursors.text,
disabledMouseCursor: SystemMouseCursors.grab,
),
onPressed: () {},
child: const Text('button'),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: Offset.zero);
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test cursor when disabled
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
enabledMouseCursor: SystemMouseCursors.text,
disabledMouseCursor: SystemMouseCursors.grab,
),
onPressed: null,
child: const Text('button'),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab);
// Test default cursor
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: OutlinedButton(
onPressed: () {},
child: const Text('button'),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test default cursor when disabled
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: OutlinedButton(
onPressed: null,
child: Text('button'),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('OutlinedButton in SelectionArea 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: OutlinedButton(
style: OutlinedButton.styleFrom(
enabledMouseCursor: SystemMouseCursors.click,
disabledMouseCursor: SystemMouseCursors.grab,
),
onPressed: () {},
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);
});
testWidgets('OutlinedButton.styleFrom can be used to set foreground and background colors', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: OutlinedButton(
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: Colors.purple,
),
onPressed: () {},
child: const Text('button'),
),
),
),
);
final Material material = tester.widget<Material>(find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(Material),
));
expect(material.color, Colors.purple);
expect(material.textStyle!.color, Colors.white);
});
Future<void> testStatesController(Widget? icon, WidgetTester tester) async {
int count = 0;
void valueChanged() {
count += 1;
}
final MaterialStatesController controller = MaterialStatesController();
addTearDown(controller.dispose);
controller.addListener(valueChanged);
await tester.pumpWidget(
MaterialApp(
home: Center(
child: icon == null
? OutlinedButton(
statesController: controller,
onPressed: () { },
child: const Text('button'),
)
: OutlinedButton.icon(
statesController: controller,
onPressed: () { },
icon: icon,
label: const Text('button'),
),
),
),
);
expect(controller.value, <MaterialState>{});
expect(count, 0);
final Offset center = tester.getCenter(find.byType(Text));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(controller.value, <MaterialState>{MaterialState.hovered});
expect(count, 1);
await gesture.moveTo(Offset.zero);
await tester.pumpAndSettle();
expect(controller.value, <MaterialState>{});
expect(count, 2);
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(controller.value, <MaterialState>{MaterialState.hovered});
expect(count, 3);
await gesture.down(center);
await tester.pumpAndSettle();
expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed});
expect(count, 4);
await gesture.up();
await tester.pumpAndSettle();
expect(controller.value, <MaterialState>{MaterialState.hovered});
expect(count, 5);
await gesture.moveTo(Offset.zero);
await tester.pumpAndSettle();
expect(controller.value, <MaterialState>{});
expect(count, 6);
await gesture.down(center);
await tester.pumpAndSettle();
expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed});
expect(count, 8); // adds hovered and pressed - two changes
// If the button is rebuilt disabled, then the pressed state is
// removed.
await tester.pumpWidget(
MaterialApp(
home: Center(
child: icon == null
? OutlinedButton(
statesController: controller,
onPressed: null,
child: const Text('button'),
)
: OutlinedButton.icon(
statesController: controller,
onPressed: null,
icon: icon,
label: const Text('button'),
),
),
),
);
await tester.pumpAndSettle();
expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.disabled});
expect(count, 10); // removes pressed and adds disabled - two changes
await gesture.moveTo(Offset.zero);
await tester.pumpAndSettle();
expect(controller.value, <MaterialState>{MaterialState.disabled});
expect(count, 11);
await gesture.removePointer();
}
testWidgets('OutlinedButton statesController', (WidgetTester tester) async {
testStatesController(null, tester);
});
testWidgets('OutlinedButton.icon statesController', (WidgetTester tester) async {
testStatesController(const Icon(Icons.add), tester);
});
testWidgets('Disabled OutlinedButton statesController', (WidgetTester tester) async {
int count = 0;
void valueChanged() {
count += 1;
}
final MaterialStatesController controller = MaterialStatesController();
addTearDown(controller.dispose);
controller.addListener(valueChanged);
await tester.pumpWidget(
MaterialApp(
home: Center(
child: OutlinedButton(
statesController: controller,
onPressed: null,
child: const Text('button'),
),
),
),
);
expect(controller.value, <MaterialState>{MaterialState.disabled});
expect(count, 1);
});
testWidgets("OutlinedButton.styleFrom doesn't throw exception on passing only one cursor", (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/118071.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
enabledMouseCursor: SystemMouseCursors.text,
),
onPressed: () {},
child: const Text('button'),
),
),
);
expect(tester.takeException(), isNull);
});
testWidgets('OutlinedButton backgroundBuilder and foregroundBuilder', (WidgetTester tester) async {
const Color backgroundColor = Color(0xFF000011);
const Color foregroundColor = Color(0xFF000022);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return DecoratedBox(
decoration: const BoxDecoration(
color: backgroundColor,
),
child: child,
);
},
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return DecoratedBox(
decoration: const BoxDecoration(
color: foregroundColor,
),
child: child,
);
},
),
onPressed: () { },
child: const Text('button'),
),
),
);
BoxDecoration boxDecorationOf(Finder finder) {
return tester.widget<DecoratedBox>(finder).decoration as BoxDecoration;
}
final Finder decorations = find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(DecoratedBox),
);
expect(boxDecorationOf(decorations.at(0)).color, backgroundColor);
expect(boxDecorationOf(decorations.at(1)).color, foregroundColor);
Text textChildOf(Finder finder) {
return tester.widget<Text>(
find.descendant(
of: finder,
matching: find.byType(Text),
),
);
}
expect(textChildOf(decorations.at(0)).data, 'button');
expect(textChildOf(decorations.at(1)).data, 'button');
});
testWidgets('OutlinedButton backgroundBuilder drops button child and foregroundBuilder return value', (WidgetTester tester) async {
const Color backgroundColor = Color(0xFF000011);
const Color foregroundColor = Color(0xFF000022);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return const DecoratedBox(
decoration: BoxDecoration(
color: backgroundColor,
),
);
},
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return const DecoratedBox(
decoration: BoxDecoration(
color: foregroundColor,
),
);
},
),
onPressed: () { },
child: const Text('button'),
),
),
);
final Finder background = find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(DecoratedBox),
);
expect(background, findsOneWidget);
expect(find.text('button'), findsNothing);
});
testWidgets('OutlinedButton foregroundBuilder drops button child', (WidgetTester tester) async {
const Color foregroundColor = Color(0xFF000022);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
return const DecoratedBox(
decoration: BoxDecoration(
color: foregroundColor,
),
);
},
),
onPressed: () { },
child: const Text('button'),
),
),
);
final Finder foreground = find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(DecoratedBox),
);
expect(foreground, findsOneWidget);
expect(find.text('button'), findsNothing);
});
testWidgets('OutlinedButton foreground and background builders are applied to the correct states', (WidgetTester tester) async {
Set<MaterialState> foregroundStates = <MaterialState>{};
Set<MaterialState> backgroundStates = <MaterialState>{};
final FocusNode focusNode = FocusNode();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: OutlinedButton(
style: ButtonStyle(
backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
backgroundStates = states;
return child!;
},
foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) {
foregroundStates = states;
return child!;
},
),
onPressed: () {},
focusNode: focusNode,
child: const Text('button'),
),
),
),
),
);
// Default.
expect(backgroundStates.isEmpty, isTrue);
expect(foregroundStates.isEmpty, isTrue);
const Set<MaterialState> focusedStates = <MaterialState>{MaterialState.focused};
const Set<MaterialState> focusedHoveredStates = <MaterialState>{MaterialState.focused, MaterialState.hovered};
const Set<MaterialState> focusedHoveredPressedStates = <MaterialState>{MaterialState.focused, MaterialState.hovered, MaterialState.pressed};
bool sameStates(Set<MaterialState> expectedValue, Set<MaterialState> actualValue) {
return expectedValue.difference(actualValue).isEmpty && actualValue.difference(expectedValue).isEmpty;
}
// Focused.
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(sameStates(focusedStates, backgroundStates), isTrue);
expect(sameStates(focusedStates, foregroundStates), isTrue);
// Hovered.
final Offset center = tester.getCenter(find.byType(OutlinedButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(sameStates(focusedHoveredStates, backgroundStates), isTrue);
expect(sameStates(focusedHoveredStates, foregroundStates), isTrue);
// Highlighted (pressed).
await gesture.down(center);
await tester.pump(); // Start the splash and highlight animations.
await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way.
expect(sameStates(focusedHoveredPressedStates, backgroundStates), isTrue);
expect(sameStates(focusedHoveredPressedStates, foregroundStates), isTrue);
focusNode.dispose();
});
testWidgets('OutlinedButton styleFrom backgroundColor special case', (WidgetTester tester) async {
// Regression test for an internal Google issue: b/323399158
const Color backgroundColor = Color(0xFF000022);
Widget buildFrame({ VoidCallback? onPressed }) {
return Directionality(
textDirection: TextDirection.ltr,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: backgroundColor,
),
onPressed: () { },
child: const Text('button'),
),
);
}
await tester.pumpWidget(buildFrame(onPressed: () { })); // enabled
final Material material = tester.widget<Material>(find.descendant(
of: find.byType(OutlinedButton),
matching: find.byType(Material),
));
expect(material.color, backgroundColor);
await tester.pumpWidget(buildFrame()); // onPressed: null - disabled
expect(material.color, backgroundColor);
});
testWidgets('Default iconAlignment', (WidgetTester tester) async {
Widget buildWidget({ required TextDirection textDirection }) {
return MaterialApp(
home: Directionality(
textDirection: textDirection,
child: Center(
child: OutlinedButton.icon(
onPressed: () {},
icon: const Icon(Icons.add),
label: const Text('button'),
),
),
),
);
}
// Test default iconAlignment when textDirection is ltr.
await tester.pumpWidget(buildWidget(textDirection: TextDirection.ltr));
final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last);
final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add));
// The icon is aligned to the left of the button.
expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); // 16.0 - padding between icon and button edge.
// Test default iconAlignment when textDirection is rtl.
await tester.pumpWidget(buildWidget(textDirection: TextDirection.rtl));
final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last);
final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add));
// The icon is aligned to the right of the button.
expect(buttonTopRight.dx, iconTopRight.dx + 16.0); // 16.0 - padding between icon and button edge.
});
testWidgets('iconAlignment can be customized', (WidgetTester tester) async {
Widget buildWidget({
required TextDirection textDirection,
required IconAlignment iconAlignment,
}) {
return MaterialApp(
home: Directionality(
textDirection: textDirection,
child: Center(
child: OutlinedButton.icon(
onPressed: () {},
icon: const Icon(Icons.add),
label: const Text('button'),
iconAlignment: iconAlignment,
),
),
),
);
}
// Test iconAlignment when textDirection is ltr.
await tester.pumpWidget(
buildWidget(
textDirection: TextDirection.ltr,
iconAlignment: IconAlignment.start,
),
);
Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last);
Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add));
// The icon is aligned to the left of the button.
expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); // 16.0 - padding between icon and button edge.
// Test iconAlignment when textDirection is ltr.
await tester.pumpWidget(
buildWidget(
textDirection: TextDirection.ltr,
iconAlignment: IconAlignment.end,
),
);
Offset buttonTopRight = tester.getTopRight(find.byType(Material).last);
Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add));
// The icon is aligned to the right of the button.
expect(buttonTopRight.dx, iconTopRight.dx + 24.0); // 24.0 - padding between icon and button edge.
// Test iconAlignment when textDirection is rtl.
await tester.pumpWidget(
buildWidget(
textDirection: TextDirection.rtl,
iconAlignment: IconAlignment.start,
),
);
buttonTopRight = tester.getTopRight(find.byType(Material).last);
iconTopRight = tester.getTopRight(find.byIcon(Icons.add));
// The icon is aligned to the right of the button.
expect(buttonTopRight.dx, iconTopRight.dx + 16.0); // 16.0 - padding between icon and button edge.
// Test iconAlignment when textDirection is rtl.
await tester.pumpWidget(
buildWidget(
textDirection: TextDirection.rtl,
iconAlignment: IconAlignment.end,
),
);
buttonTopLeft = tester.getTopLeft(find.byType(Material).last);
iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add));
// The icon is aligned to the left of the button.
expect(buttonTopLeft.dx, iconTopLeft.dx - 24.0); // 24.0 - padding between icon and button edge.
});
}
TextStyle _iconStyle(WidgetTester tester, IconData icon) {
final RichText iconRichText = tester.widget<RichText>(
find.descendant(of: find.byIcon(icon), matching: find.byType(RichText)),
);
return iconRichText.text.style!;
}
| flutter/packages/flutter/test/material/outlined_button_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/outlined_button_test.dart",
"repo_id": "flutter",
"token_count": 36122
} | 668 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.