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 'dart:ui';
import 'package:flutter/material.dart';
/// Flutter code sample for [ReorderableListView].
void main() => runApp(const ReorderableApp());
class ReorderableApp extends StatelessWidget {
const ReorderableApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('ReorderableListView Sample')),
body: const ReorderableExample(),
),
);
}
}
class ReorderableExample extends StatefulWidget {
const ReorderableExample({super.key});
@override
State<ReorderableExample> createState() => _ReorderableExampleState();
}
class _ReorderableExampleState extends State<ReorderableExample> {
final List<int> _items = List<int>.generate(50, (int index) => index);
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final Color oddItemColor = colorScheme.secondary.withOpacity(0.05);
final Color evenItemColor = colorScheme.secondary.withOpacity(0.15);
final Color draggableItemColor = colorScheme.secondary;
Widget proxyDecorator(Widget child, int index, Animation<double> animation) {
return AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget? child) {
final double animValue = Curves.easeInOut.transform(animation.value);
final double elevation = lerpDouble(0, 6, animValue)!;
return Material(
elevation: elevation,
color: draggableItemColor,
shadowColor: draggableItemColor,
child: child,
);
},
child: child,
);
}
return ReorderableListView(
padding: const EdgeInsets.symmetric(horizontal: 40),
proxyDecorator: proxyDecorator,
children: <Widget>[
for (int index = 0; index < _items.length; index += 1)
ListTile(
key: Key('$index'),
tileColor: _items[index].isOdd ? oddItemColor : evenItemColor,
title: Text('Item ${_items[index]}'),
),
],
onReorder: (int oldIndex, int newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final int item = _items.removeAt(oldIndex);
_items.insert(newIndex, item);
});
},
);
}
}
| flutter/examples/api/lib/material/reorderable_list/reorderable_list_view.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/reorderable_list/reorderable_list_view.1.dart",
"repo_id": "flutter",
"token_count": 1008
} | 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 [SnackBar].
void main() => runApp(const SnackBarApp());
class SnackBarApp extends StatelessWidget {
const SnackBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: SnackBarExample(),
);
}
}
class SnackBarExample extends StatefulWidget {
const SnackBarExample({super.key});
@override
State<SnackBarExample> createState() => _SnackBarExampleState();
}
class _SnackBarExampleState extends State<SnackBarExample> {
bool _largeLogo = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('SnackBar Sample')),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
ElevatedButton(
onPressed: () {
const SnackBar snackBar = SnackBar(
content: Text('A SnackBar has been shown.'),
behavior: SnackBarBehavior.floating,
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
child: const Text('Show SnackBar'),
),
const SizedBox(height: 8.0),
ElevatedButton(
onPressed: () {
setState(() => _largeLogo = !_largeLogo);
},
child: Text(_largeLogo ? 'Shrink Logo' : 'Grow Logo'),
),
],
),
),
// A floating [SnackBar] is positioned above [Scaffold.floatingActionButton].
// If the Widget provided to the floatingActionButton slot takes up too much space
// for the SnackBar to be visible, an error will be thrown.
floatingActionButton: Container(
constraints: BoxConstraints.tightFor(
width: 150,
height: _largeLogo ? double.infinity : 150,
),
decoration: const BoxDecoration(
color: Colors.blueGrey,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: const FlutterLogo(),
),
);
}
}
| flutter/examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.1.dart",
"repo_id": "flutter",
"token_count": 999
} | 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.
// Flutter example for [SelectionContainer.disabled].
import 'package:flutter/material.dart';
void main() => runApp(const SelectionContainerDisabledExampleApp());
class SelectionContainerDisabledExampleApp extends StatelessWidget {
const SelectionContainerDisabledExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('SelectionContainer.disabled Sample')),
body: const Center(
child: SelectionArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Selectable text'),
SelectionContainer.disabled(child: Text('Non-selectable text')),
Text('Selectable text'),
],
),
),
),
),
);
}
}
| flutter/examples/api/lib/material/selection_container/selection_container_disabled.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/selection_container/selection_container_disabled.0.dart",
"repo_id": "flutter",
"token_count": 409
} | 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 custom labeled switch.
void main() => runApp(const LabeledSwitchApp());
class LabeledSwitchApp extends StatelessWidget {
const LabeledSwitchApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
appBar: AppBar(title: const Text('Custom Labeled Switch Sample')),
body: const Center(
child: LabeledSwitchExample(),
),
),
);
}
}
class LabeledSwitch extends StatelessWidget {
const LabeledSwitch({
super.key,
required this.label,
required this.padding,
required this.value,
required this.onChanged,
});
final String label;
final EdgeInsets padding;
final bool value;
final ValueChanged<bool> onChanged;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
onChanged(!value);
},
child: Padding(
padding: padding,
child: Row(
children: <Widget>[
Expanded(child: Text(label)),
Switch(
value: value,
onChanged: (bool newValue) {
onChanged(newValue);
},
),
],
),
),
);
}
}
class LabeledSwitchExample extends StatefulWidget {
const LabeledSwitchExample({super.key});
@override
State<LabeledSwitchExample> createState() => _LabeledSwitchExampleState();
}
class _LabeledSwitchExampleState extends State<LabeledSwitchExample> {
bool _isSelected = false;
@override
Widget build(BuildContext context) {
return LabeledSwitch(
label: 'This is the label text',
padding: const EdgeInsets.symmetric(horizontal: 20.0),
value: _isSelected,
onChanged: (bool newValue) {
setState(() {
_isSelected = newValue;
});
},
);
}
}
| flutter/examples/api/lib/material/switch_list_tile/custom_labeled_switch.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/switch_list_tile/custom_labeled_switch.1.dart",
"repo_id": "flutter",
"token_count": 835
} | 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 [ToggleButtons].
const List<Widget> fruits = <Widget>[Text('Apple'), Text('Banana'), Text('Orange')];
const List<Widget> vegetables = <Widget>[Text('Tomatoes'), Text('Potatoes'), Text('Carrots')];
const List<Widget> icons = <Widget>[
Icon(Icons.sunny),
Icon(Icons.cloud),
Icon(Icons.ac_unit),
];
void main() => runApp(const ToggleButtonsExampleApp());
class ToggleButtonsExampleApp extends StatelessWidget {
const ToggleButtonsExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const ToggleButtonsSample(title: 'ToggleButtons Sample'),
);
}
}
class ToggleButtonsSample extends StatefulWidget {
const ToggleButtonsSample({super.key, required this.title});
final String title;
@override
State<ToggleButtonsSample> createState() => _ToggleButtonsSampleState();
}
class _ToggleButtonsSampleState extends State<ToggleButtonsSample> {
final List<bool> _selectedFruits = <bool>[true, false, false];
final List<bool> _selectedVegetables = <bool>[false, true, false];
final List<bool> _selectedWeather = <bool>[false, false, true];
bool vertical = false;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// ToggleButtons with a single selection.
Text('Single-select', style: theme.textTheme.titleSmall),
const SizedBox(height: 5),
ToggleButtons(
direction: vertical ? Axis.vertical : Axis.horizontal,
onPressed: (int index) {
setState(() {
// The button that is tapped is set to true, and the others to false.
for (int i = 0; i < _selectedFruits.length; i++) {
_selectedFruits[i] = i == index;
}
});
},
borderRadius: const BorderRadius.all(Radius.circular(8)),
selectedBorderColor: Colors.red[700],
selectedColor: Colors.white,
fillColor: Colors.red[200],
color: Colors.red[400],
constraints: const BoxConstraints(
minHeight: 40.0,
minWidth: 80.0,
),
isSelected: _selectedFruits,
children: fruits,
),
const SizedBox(height: 20),
// ToggleButtons with a multiple selection.
Text('Multi-select', style: theme.textTheme.titleSmall),
const SizedBox(height: 5),
ToggleButtons(
direction: vertical ? Axis.vertical : Axis.horizontal,
onPressed: (int index) {
// All buttons are selectable.
setState(() {
_selectedVegetables[index] = !_selectedVegetables[index];
});
},
borderRadius: const BorderRadius.all(Radius.circular(8)),
selectedBorderColor: Colors.green[700],
selectedColor: Colors.white,
fillColor: Colors.green[200],
color: Colors.green[400],
constraints: const BoxConstraints(
minHeight: 40.0,
minWidth: 80.0,
),
isSelected: _selectedVegetables,
children: vegetables,
),
const SizedBox(height: 20),
// ToggleButtons with icons only.
Text('Icon-only', style: theme.textTheme.titleSmall),
const SizedBox(height: 5),
ToggleButtons(
direction: vertical ? Axis.vertical : Axis.horizontal,
onPressed: (int index) {
setState(() {
// The button that is tapped is set to true, and the others to false.
for (int i = 0; i < _selectedWeather.length; i++) {
_selectedWeather[i] = i == index;
}
});
},
borderRadius: const BorderRadius.all(Radius.circular(8)),
selectedBorderColor: Colors.blue[700],
selectedColor: Colors.white,
fillColor: Colors.blue[200],
color: Colors.blue[400],
isSelected: _selectedWeather,
children: icons,
),
],
),
),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
setState(() {
// When the button is pressed, ToggleButtons direction is changed.
vertical = !vertical;
});
},
icon: const Icon(Icons.screen_rotation_outlined),
label: Text(vertical ? 'Horizontal' : 'Vertical'),
),
);
}
}
| flutter/examples/api/lib/material/toggle_buttons/toggle_buttons.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/toggle_buttons/toggle_buttons.0.dart",
"repo_id": "flutter",
"token_count": 2571
} | 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/scheduler.dart';
/// Flutter code sample for [AppLifecycleListener].
void main() {
runApp(const AppLifecycleListenerExample());
}
class AppLifecycleListenerExample extends StatelessWidget {
const AppLifecycleListenerExample({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(body: AppLifecycleDisplay()),
);
}
}
class AppLifecycleDisplay extends StatefulWidget {
const AppLifecycleDisplay({super.key});
@override
State<AppLifecycleDisplay> createState() => _AppLifecycleDisplayState();
}
class _AppLifecycleDisplayState extends State<AppLifecycleDisplay> {
late final AppLifecycleListener _listener;
final ScrollController _scrollController = ScrollController();
final List<String> _states = <String>[];
late AppLifecycleState? _state;
@override
void initState() {
super.initState();
_state = SchedulerBinding.instance.lifecycleState;
_listener = AppLifecycleListener(
onShow: () => _handleTransition('show'),
onResume: () => _handleTransition('resume'),
onHide: () => _handleTransition('hide'),
onInactive: () => _handleTransition('inactive'),
onPause: () => _handleTransition('pause'),
onDetach: () => _handleTransition('detach'),
onRestart: () => _handleTransition('restart'),
// This fires for each state change. Callbacks above fire only for
// specific state transitions.
onStateChange: _handleStateChange,
);
if (_state != null) {
_states.add(_state!.name);
}
}
@override
void dispose() {
_listener.dispose();
super.dispose();
}
void _handleTransition(String name) {
setState(() {
_states.add(name);
});
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
void _handleStateChange(AppLifecycleState state) {
setState(() {
_state = state;
});
}
@override
Widget build(BuildContext context) {
return Center(
child: SizedBox(
width: 300,
child: SingleChildScrollView(
controller: _scrollController,
child: Column(
children: <Widget>[
Text('Current State: ${_state ?? 'Not initialized yet'}'),
const SizedBox(height: 30),
Text('State History:\n ${_states.join('\n ')}'),
],
),
),
),
);
}
}
| flutter/examples/api/lib/widgets/app_lifecycle_listener/app_lifecycle_listener.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/app_lifecycle_listener/app_lifecycle_listener.0.dart",
"repo_id": "flutter",
"token_count": 1018
} | 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 [Expanded].
void main() => runApp(const ExpandedApp());
class ExpandedApp extends StatelessWidget {
const ExpandedApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Expanded Column Sample'),
),
body: const ExpandedExample(),
),
);
}
}
class ExpandedExample extends StatelessWidget {
const ExpandedExample({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
Container(
color: Colors.blue,
height: 100,
width: 100,
),
Expanded(
child: Container(
color: Colors.amber,
width: 100,
),
),
Container(
color: Colors.blue,
height: 100,
width: 100,
),
],
),
);
}
}
| flutter/examples/api/lib/widgets/basic/expanded.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/basic/expanded.0.dart",
"repo_id": "flutter",
"token_count": 545
} | 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 [Dismissible].
void main() => runApp(const DismissibleExampleApp());
class DismissibleExampleApp extends StatelessWidget {
const DismissibleExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Dismissible Sample')),
body: const DismissibleExample(),
),
);
}
}
class DismissibleExample extends StatefulWidget {
const DismissibleExample({super.key});
@override
State<DismissibleExample> createState() => _DismissibleExampleState();
}
class _DismissibleExampleState extends State<DismissibleExample> {
List<int> items = List<int>.generate(100, (int index) => index);
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
padding: const EdgeInsets.symmetric(vertical: 16),
itemBuilder: (BuildContext context, int index) {
return Dismissible(
background: Container(
color: Colors.green,
),
key: ValueKey<int>(items[index]),
onDismissed: (DismissDirection direction) {
setState(() {
items.removeAt(index);
});
},
child: ListTile(
title: Text(
'Item ${items[index]}',
),
),
);
},
);
}
}
| flutter/examples/api/lib/widgets/dismissible/dismissible.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/dismissible/dismissible.0.dart",
"repo_id": "flutter",
"token_count": 649
} | 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/material.dart';
import 'package:flutter/services.dart';
/// This sample demonstrates showing a confirmation dialog when the user
/// attempts to navigate away from a page with unsaved [Form] data.
void main() => runApp(const FormApp());
class FormApp extends StatelessWidget {
const FormApp({
super.key,
});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Confirmation Dialog Example'),
),
body: Center(
child: _SaveableForm(),
),
),
);
}
}
class _SaveableForm extends StatefulWidget {
@override
State<_SaveableForm> createState() => _SaveableFormState();
}
class _SaveableFormState extends State<_SaveableForm> {
final TextEditingController _controller = TextEditingController();
String _savedValue = '';
bool _isDirty = false;
@override
void initState() {
super.initState();
_controller.addListener(_onChanged);
}
@override
void dispose() {
_controller.removeListener(_onChanged);
super.dispose();
}
void _onChanged() {
final bool nextIsDirty = _savedValue != _controller.text;
if (nextIsDirty == _isDirty) {
return;
}
setState(() {
_isDirty = nextIsDirty;
});
}
/// Shows a dialog and resolves to true when the user has indicated that they
/// want to pop.
///
/// A return value of null indicates a desire not to pop, such as when the
/// user has dismissed the modal without tapping a button.
Future<bool?> _showDialog() {
return showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Are you sure?'),
content: const Text('Any unsaved changes will be lost!'),
actions: <Widget>[
TextButton(
child: const Text('Yes, discard my changes'),
onPressed: () {
Navigator.pop(context, true);
},
),
TextButton(
child: const Text('No, continue editing'),
onPressed: () {
Navigator.pop(context, false);
},
),
],
);
},
);
}
void _save(String? value) {
final String nextSavedValue = value ?? '';
setState(() {
_savedValue = nextSavedValue;
_isDirty = nextSavedValue != _controller.text;
});
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('If the field below is unsaved, a confirmation dialog will be shown on back.'),
const SizedBox(height: 20.0),
Form(
canPop: !_isDirty,
onPopInvoked: (bool didPop) async {
if (didPop) {
return;
}
final bool shouldPop = await _showDialog() ?? false;
if (shouldPop) {
// Since this is the root route, quit the app where possible by
// invoking the SystemNavigator. If this wasn't the root route,
// then Navigator.maybePop could be used instead.
// See https://github.com/flutter/flutter/issues/11490
SystemNavigator.pop();
}
},
autovalidateMode: AutovalidateMode.always,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
controller: _controller,
onFieldSubmitted: (String? value) {
_save(value);
},
),
TextButton(
onPressed: () {
_save(_controller.text);
},
child: Row(
children: <Widget>[
const Text('Save'),
if (_controller.text.isNotEmpty)
Icon(
_isDirty ? Icons.warning : Icons.check,
),
],
),
),
],
),
),
TextButton(
onPressed: () async {
final bool shouldPop = !_isDirty || (await _showDialog() ?? false);
if (!shouldPop) {
return;
}
// Since this is the root route, quit the app where possible by
// invoking the SystemNavigator. If this wasn't the root route,
// then Navigator.maybePop could be used instead.
// See https://github.com/flutter/flutter/issues/11490
SystemNavigator.pop();
},
child: const Text('Go back'),
),
],
),
);
}
}
| flutter/examples/api/lib/widgets/form/form.1.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/form/form.1.dart",
"repo_id": "flutter",
"token_count": 2423
} | 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/material.dart';
/// Flutter code sample for [AnimatedPositioned].
void main() => runApp(const AnimatedPositionedExampleApp());
class AnimatedPositionedExampleApp extends StatelessWidget {
const AnimatedPositionedExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('AnimatedPositioned Sample')),
body: const Center(
child: AnimatedPositionedExample(),
),
),
);
}
}
class AnimatedPositionedExample extends StatefulWidget {
const AnimatedPositionedExample({super.key});
@override
State<AnimatedPositionedExample> createState() => _AnimatedPositionedExampleState();
}
class _AnimatedPositionedExampleState extends State<AnimatedPositionedExample> {
bool selected = false;
@override
Widget build(BuildContext context) {
return SizedBox(
width: 200,
height: 350,
child: Stack(
children: <Widget>[
AnimatedPositioned(
width: selected ? 200.0 : 50.0,
height: selected ? 50.0 : 200.0,
top: selected ? 50.0 : 150.0,
duration: const Duration(seconds: 2),
curve: Curves.fastOutSlowIn,
child: GestureDetector(
onTap: () {
setState(() {
selected = !selected;
});
},
child: const ColoredBox(
color: Colors.blue,
child: Center(child: Text('Tap me')),
),
),
),
],
),
);
}
}
| flutter/examples/api/lib/widgets/implicit_animations/animated_positioned.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/implicit_animations/animated_positioned.0.dart",
"repo_id": "flutter",
"token_count": 756
} | 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';
/// Flutter code sample for [Navigator.restorablePushReplacement].
void main() => runApp(const RestorablePushReplacementExampleApp());
class RestorablePushReplacementExampleApp extends StatelessWidget {
const RestorablePushReplacementExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: RestorablePushReplacementExample(),
);
}
}
class RestorablePushReplacementExample extends StatefulWidget {
const RestorablePushReplacementExample({super.key});
@override
State<RestorablePushReplacementExample> createState() => _RestorablePushReplacementExampleState();
}
class _RestorablePushReplacementExampleState extends State<RestorablePushReplacementExample> {
@pragma('vm:entry-point')
static Route<void> _myRouteBuilder(BuildContext context, Object? arguments) {
return MaterialPageRoute<void>(
builder: (BuildContext context) => const RestorablePushReplacementExample(),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample Code'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.restorablePushReplacement(context, _myRouteBuilder),
tooltip: 'Increment Counter',
child: const Icon(Icons.add),
),
);
}
}
| flutter/examples/api/lib/widgets/navigator/navigator.restorable_push_replacement.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/navigator/navigator.restorable_push_replacement.0.dart",
"repo_id": "flutter",
"token_count": 481
} | 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';
/// Flutter code sample for [GlowingOverscrollIndicator].
void main() => runApp(const GlowingOverscrollIndicatorExampleApp());
class GlowingOverscrollIndicatorExampleApp extends StatelessWidget {
const GlowingOverscrollIndicatorExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('GlowingOverscrollIndicator Sample')),
body: const GlowingOverscrollIndicatorExample(),
),
);
}
}
class GlowingOverscrollIndicatorExample extends StatelessWidget {
const GlowingOverscrollIndicatorExample({super.key});
@override
Widget build(BuildContext context) {
return NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return const <Widget>[
SliverAppBar(title: Text('Custom NestedScrollViews')),
];
},
body: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(
child: Container(
color: Colors.amberAccent,
height: 100,
child: const Center(child: Text('Glow all day!')),
),
),
const SliverFillRemaining(child: FlutterLogo()),
],
),
);
}
}
| flutter/examples/api/lib/widgets/overscroll_indicator/glowing_overscroll_indicator.1.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/overscroll_indicator/glowing_overscroll_indicator.1.dart",
"repo_id": "flutter",
"token_count": 577
} | 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 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() => runApp(const GridViewExampleApp());
class GridViewExampleApp extends StatelessWidget {
const GridViewExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Padding(
padding: const EdgeInsets.all(20.0),
child: Card(
elevation: 8.0,
child: GridView.builder(
padding: const EdgeInsets.all(12.0),
gridDelegate: CustomGridDelegate(dimension: 240.0),
// Try uncommenting some of these properties to see the effect on the grid:
// itemCount: 20, // The default is that the number of grid tiles is infinite.
// scrollDirection: Axis.horizontal, // The default is vertical.
// reverse: true, // The default is false, going down (or left to right).
itemBuilder: (BuildContext context, int index) {
final math.Random random = math.Random(index);
return GridTile(
header: GridTileBar(
title: Text('$index', style: const TextStyle(color: Colors.black)),
),
child: Container(
margin: const EdgeInsets.all(12.0),
decoration: ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
gradient: const RadialGradient(
colors: <Color>[ Color(0x0F88EEFF), Color(0x2F0099BB) ],
),
),
child: FlutterLogo(
style: FlutterLogoStyle.values[random.nextInt(FlutterLogoStyle.values.length)],
),
),
);
},
),
),
),
);
}
}
class CustomGridDelegate extends SliverGridDelegate {
CustomGridDelegate({ required this.dimension });
// This is the desired height of each row (and width of each square).
// When there is not enough room, we shrink this to the width of the scroll view.
final double dimension;
// The layout is two rows of squares, then one very wide cell, repeat.
@override
SliverGridLayout getLayout(SliverConstraints constraints) {
// Determine how many squares we can fit per row.
int count = constraints.crossAxisExtent ~/ dimension;
if (count < 1) {
count = 1; // Always fit at least one regardless.
}
final double squareDimension = constraints.crossAxisExtent / count;
return CustomGridLayout(
crossAxisCount: count,
fullRowPeriod: 3, // Number of rows per block (one of which is the full row).
dimension: squareDimension,
);
}
@override
bool shouldRelayout(CustomGridDelegate oldDelegate) {
return dimension != oldDelegate.dimension;
}
}
class CustomGridLayout extends SliverGridLayout {
const CustomGridLayout({
required this.crossAxisCount,
required this.dimension,
required this.fullRowPeriod,
}) : assert(crossAxisCount > 0),
assert(fullRowPeriod > 1),
loopLength = crossAxisCount * (fullRowPeriod - 1) + 1,
loopHeight = fullRowPeriod * dimension;
final int crossAxisCount;
final double dimension;
final int fullRowPeriod;
// Computed values.
final int loopLength;
final double loopHeight;
@override
double computeMaxScrollOffset(int childCount) {
// This returns the scroll offset of the end side of the childCount'th child.
// In the case of this example, this method is not used, since the grid is
// infinite. However, if one set an itemCount on the GridView above, this
// function would be used to determine how far to allow the user to scroll.
if (childCount == 0 || dimension == 0) {
return 0;
}
return (childCount ~/ loopLength) * loopHeight
+ ((childCount % loopLength) ~/ crossAxisCount) * dimension;
}
@override
SliverGridGeometry getGeometryForChildIndex(int index) {
// This returns the position of the index'th tile.
//
// The SliverGridGeometry object returned from this method has four
// properties. For a grid that scrolls down, as in this example, the four
// properties are equivalent to x,y,width,height. However, since the
// GridView is direction agnostic, the names used for SliverGridGeometry are
// also direction-agnostic.
//
// Try changing the scrollDirection and reverse properties on the GridView
// to see how this algorithm works in any direction (and why, therefore, the
// names are direction-agnostic).
final int loop = index ~/ loopLength;
final int loopIndex = index % loopLength;
if (loopIndex == loopLength - 1) {
// Full width case.
return SliverGridGeometry(
scrollOffset: (loop + 1) * loopHeight - dimension, // "y"
crossAxisOffset: 0, // "x"
mainAxisExtent: dimension, // "height"
crossAxisExtent: crossAxisCount * dimension, // "width"
);
}
// Square case.
final int rowIndex = loopIndex ~/ crossAxisCount;
final int columnIndex = loopIndex % crossAxisCount;
return SliverGridGeometry(
scrollOffset: (loop * loopHeight) + (rowIndex * dimension), // "y"
crossAxisOffset: columnIndex * dimension, // "x"
mainAxisExtent: dimension, // "height"
crossAxisExtent: dimension, // "width"
);
}
@override
int getMinChildIndexForScrollOffset(double scrollOffset) {
// This returns the first index that is visible for a given scrollOffset.
//
// The GridView only asks for the geometry of children that are visible
// between the scroll offset passed to getMinChildIndexForScrollOffset and
// the scroll offset passed to getMaxChildIndexForScrollOffset.
//
// It is the responsibility of the SliverGridLayout to ensure that
// getGeometryForChildIndex is consistent with getMinChildIndexForScrollOffset
// and getMaxChildIndexForScrollOffset.
//
// Not every child between the minimum child index and the maximum child
// index need be visible (some may have scroll offsets that are outside the
// view; this happens commonly when the grid view places tiles out of
// order). However, doing this means the grid view is less efficient, as it
// will do work for children that are not visible. It is preferred that the
// children are returned in the order that they are laid out.
final int rows = scrollOffset ~/ dimension;
final int loops = rows ~/ fullRowPeriod;
final int extra = rows % fullRowPeriod;
return loops * loopLength + extra * crossAxisCount;
}
@override
int getMaxChildIndexForScrollOffset(double scrollOffset) {
// (See commentary above.)
final int rows = scrollOffset ~/ dimension;
final int loops = rows ~/ fullRowPeriod;
final int extra = rows % fullRowPeriod;
final int count = loops * loopLength + extra * crossAxisCount;
if (extra == fullRowPeriod - 1) {
return count;
}
return count + crossAxisCount - 1;
}
}
| flutter/examples/api/lib/widgets/scroll_view/grid_view.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/scroll_view/grid_view.0.dart",
"repo_id": "flutter",
"token_count": 2626
} | 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';
/// Flutter code sample for [SingleChildScrollView].
void main() => runApp(const SingleChildScrollViewExampleApp());
class SingleChildScrollViewExampleApp extends StatelessWidget {
const SingleChildScrollViewExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: SingleChildScrollViewExample(),
);
}
}
class SingleChildScrollViewExample extends StatelessWidget {
const SingleChildScrollViewExample({super.key});
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.bodyMedium!,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Container(
// A fixed-height child.
color: const Color(0xffeeee00), // Yellow
height: 120.0,
alignment: Alignment.center,
child: const Text('Fixed Height Content'),
),
Container(
// Another fixed-height child.
color: const Color(0xff008000), // Green
height: 120.0,
alignment: Alignment.center,
child: const Text('Fixed Height Content'),
),
],
),
),
);
},
),
);
}
}
| flutter/examples/api/lib/widgets/single_child_scroll_view/single_child_scroll_view.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/single_child_scroll_view/single_child_scroll_view.0.dart",
"repo_id": "flutter",
"token_count": 911
} | 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';
/// Flutter code sample for [AlignTransition].
void main() => runApp(const AlignTransitionExampleApp());
class AlignTransitionExampleApp extends StatelessWidget {
const AlignTransitionExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: AlignTransitionExample(),
);
}
}
class AlignTransitionExample extends StatefulWidget {
const AlignTransitionExample({super.key});
@override
State<AlignTransitionExample> createState() => _AlignTransitionExampleState();
}
/// [AnimationController]s can be created with `vsync: this` because of
/// [TickerProviderStateMixin].
class _AlignTransitionExampleState extends State<AlignTransitionExample> with TickerProviderStateMixin {
// Using `late final` for lazy initialization. See
// https://dart.dev/null-safety/understanding-null-safety#lazy-initialization.
late final AnimationController _controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
late final Animation<AlignmentGeometry> _animation = Tween<AlignmentGeometry>(
begin: Alignment.bottomLeft,
end: Alignment.center,
).animate(
CurvedAnimation(
parent: _controller,
curve: Curves.decelerate,
),
);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ColoredBox(
color: Colors.white,
child: AlignTransition(
alignment: _animation,
child: const Padding(
padding: EdgeInsets.all(8),
child: FlutterLogo(size: 150.0),
),
),
);
}
}
| flutter/examples/api/lib/widgets/transitions/align_transition.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/transitions/align_transition.0.dart",
"repo_id": "flutter",
"token_count": 631
} | 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';
/// Flutter code sample for [SlideTransition].
void main() => runApp(const SlideTransitionExampleApp());
class SlideTransitionExampleApp extends StatelessWidget {
const SlideTransitionExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('SlideTransition Sample')),
body: const Center(
child: SlideTransitionExample(),
),
),
);
}
}
class SlideTransitionExample extends StatefulWidget {
const SlideTransitionExample({super.key});
@override
State<SlideTransitionExample> createState() => _SlideTransitionExampleState();
}
class _SlideTransitionExampleState extends State<SlideTransitionExample> with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
late final Animation<Offset> _offsetAnimation = Tween<Offset>(
begin: Offset.zero,
end: const Offset(1.5, 0.0),
).animate(CurvedAnimation(
parent: _controller,
curve: Curves.elasticIn,
));
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SlideTransition(
position: _offsetAnimation,
child: const Padding(
padding: EdgeInsets.all(8.0),
child: FlutterLogo(size: 150.0),
),
);
}
}
| flutter/examples/api/lib/widgets/transitions/slide_transition.0.dart/0 | {
"file_path": "flutter/examples/api/lib/widgets/transitions/slide_transition.0.dart",
"repo_id": "flutter",
"token_count": 574
} | 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/cupertino.dart';
import 'package:flutter_api_samples/cupertino/form_row/cupertino_form_row.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Cupertino form section displays cupertino form rows', (WidgetTester tester) async {
await tester.pumpWidget(
const example.CupertinoFormRowApp(),
);
expect(find.byType(CupertinoFormSection), findsOneWidget);
expect(find.byType(CupertinoFormRow), findsNWidgets(4));
expect(find.widgetWithText(CupertinoFormSection, 'Connectivity'), findsOneWidget);
expect(find.widgetWithText(CupertinoFormRow, 'Airplane Mode'), findsOneWidget);
expect(find.widgetWithText(CupertinoFormRow, 'Wi-Fi'), findsOneWidget);
expect(find.widgetWithText(CupertinoFormRow, 'Bluetooth'), findsOneWidget);
expect(find.widgetWithText(CupertinoFormRow, 'Mobile Data'), findsOneWidget);
});
}
| flutter/examples/api/test/cupertino/form_row/cupertino_form_row.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/cupertino/form_row/cupertino_form_row.0_test.dart",
"repo_id": "flutter",
"token_count": 361
} | 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_api_samples/cupertino/segmented_control/cupertino_segmented_control.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Can change a selected segmented control', (WidgetTester tester) async {
await tester.pumpWidget(
const example.SegmentedControlApp(),
);
expect(find.text('Selected Segment: midnight'), findsOneWidget);
await tester.tap(find.text('Cerulean'));
await tester.pumpAndSettle();
expect(find.text('Selected Segment: cerulean'), findsOneWidget);
});
}
| flutter/examples/api/test/cupertino/segmented_control/cupertino_segmented_control.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/cupertino/segmented_control/cupertino_segmented_control.0_test.dart",
"repo_id": "flutter",
"token_count": 245
} | 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/material.dart';
import 'package:flutter_api_samples/material/app/app.0.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Theme animation can be customized using AnimationStyle', (WidgetTester tester) async {
await tester.pumpWidget(
const example.MaterialAppExample(),
);
Material getScaffoldMaterial() {
return tester.widget<Material>(find.descendant(
of: find.byType(Scaffold),
matching: find.byType(Material).first,
));
}
final ThemeData lightTheme = ThemeData(colorSchemeSeed: Colors.green);
final ThemeData darkTheme = ThemeData(
colorSchemeSeed: Colors.green,
brightness: Brightness.dark,
);
// Test the default animation.
expect(getScaffoldMaterial().color, lightTheme.colorScheme.surface);
await tester.tap(find.text( 'Switch Theme Mode'));
await tester.pump();
// Advance the animation by half of the default duration.
await tester.pump(const Duration(milliseconds: 100));
// The Scaffold background color is updated.
expect(
getScaffoldMaterial().color,
Color.lerp(lightTheme.colorScheme.surface, darkTheme.colorScheme.surface, 0.5),
);
await tester.pumpAndSettle();
// The Scaffold background color is now fully dark.
expect(getScaffoldMaterial().color, darkTheme.colorScheme.surface);
// Test the custom animation curve and duration.
await tester.tap(find.text('Custom'));
await tester.pumpAndSettle();
await tester.tap(find.text('Switch Theme Mode'));
await tester.pump();
// Advance the animation by half of the custom duration.
await tester.pump(const Duration(milliseconds: 500));
// The Scaffold background color is updated.
expect(getScaffoldMaterial().color, const Color(0xff333731));
await tester.pumpAndSettle();
// The Scaffold background color is now fully light.
expect(getScaffoldMaterial().color, lightTheme.colorScheme.surface);
// Test the no animation style.
await tester.tap(find.text('None'));
await tester.pumpAndSettle();
await tester.tap(find.text('Switch Theme Mode'));
// Advance the animation by only one frame.
await tester.pump();
// The Scaffold background color is updated immediately.
expect(getScaffoldMaterial().color, darkTheme.colorScheme.surface);
});
}
| flutter/examples/api/test/material/app/app.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/app/app.0_test.dart",
"repo_id": "flutter",
"token_count": 867
} | 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/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_api_samples/material/context_menu/editable_text_toolbar_builder.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('showing and hiding the context menu in TextField with custom buttons', (WidgetTester tester) async {
await tester.pumpWidget(
const example.EditableTextToolbarBuilderExampleApp(),
);
expect(BrowserContextMenu.enabled, !kIsWeb);
await tester.tap(find.byType(EditableText));
await tester.pump();
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Long pressing the field shows the default context menu but with custom
// buttons.
await tester.longPress(find.byType(EditableText));
await tester.pumpAndSettle();
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
expect(find.byType(CupertinoButton), findsAtLeastNWidgets(1));
// Tap to dismiss.
await tester.tapAt(tester.getTopLeft(find.byType(EditableText)));
await tester.pumpAndSettle();
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
expect(find.byType(CupertinoButton), findsNothing);
});
}
| flutter/examples/api/test/material/context_menu/editable_text_toolbar_builder.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/context_menu/editable_text_toolbar_builder.0_test.dart",
"repo_id": "flutter",
"token_count": 495
} | 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/material/divider/divider.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Horizontal Divider', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: example.DividerExampleApp(),
),
),
);
expect(find.byType(Divider), findsOneWidget);
// Divider is positioned horizontally.
final Offset container = tester.getBottomLeft(find.byType(ColoredBox).first);
expect(container.dy, tester.getTopLeft(find.byType(Divider)).dy);
final Offset subheader = tester.getTopLeft(find.text('Subheader'));
expect(subheader.dy, tester.getBottomLeft(find.byType(Divider)).dy);
});
}
| flutter/examples/api/test/material/divider/divider.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/divider/divider.0_test.dart",
"repo_id": "flutter",
"token_count": 346
} | 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/material/filter_chip/filter_chip.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Filter exercises using FilterChip', (WidgetTester tester) async {
const String baseText = 'Looking for: ';
await tester.pumpWidget(
const example.ChipApp(),
);
expect(find.text(baseText), findsOneWidget);
FilterChip filterChip = tester.widget(find.byType(FilterChip).at(2));
expect(filterChip.selected, false);
await tester.tap(find.byType(FilterChip).at(2));
await tester.pumpAndSettle();
filterChip = tester.widget(find.byType(FilterChip).at(2));
expect(filterChip.selected, true);
expect(find.text('${baseText}cycling'), findsOneWidget);
await tester.tap(find.byType(FilterChip).at(3));
await tester.pumpAndSettle();
filterChip = tester.widget(find.byType(FilterChip).at(3));
expect(filterChip.selected, true);
expect(find.text('${baseText}cycling, hiking'), findsOneWidget);
});
}
| flutter/examples/api/test/material/filter_chip/filter_chip.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/filter_chip/filter_chip.0_test.dart",
"repo_id": "flutter",
"token_count": 427
} | 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 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/input_decorator/input_decoration.suffix_icon.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('InputDecorator suffixIcon alignment', (WidgetTester tester) async {
await tester.pumpWidget(
const example.SuffixIconExampleApp(),
);
expect(tester.getCenter(find.byIcon(Icons.remove_red_eye)).dy, 28.0);
});
}
| flutter/examples/api/test/material/input_decorator/input_decoration.suffix_icon.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/input_decorator/input_decoration.suffix_icon.0_test.dart",
"repo_id": "flutter",
"token_count": 212
} | 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/material/navigation_bar/navigation_bar.1.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Navigation bar updates label behavior when tapping buttons',
(WidgetTester tester) async {
await tester.pumpWidget(
const example.NavigationBarApp(),
);
NavigationBar navigationBarWidget = tester.firstWidget(find.byType(NavigationBar));
expect(find.text('Label behavior: alwaysShow'), findsOneWidget);
/// Test alwaysShow label behavior button.
await tester.tap(find.widgetWithText(ElevatedButton, 'alwaysShow'));
await tester.pumpAndSettle();
expect(find.text('Label behavior: alwaysShow'), findsOneWidget);
expect(navigationBarWidget.labelBehavior, NavigationDestinationLabelBehavior.alwaysShow);
/// Test onlyShowSelected label behavior button.
await tester.tap(find.widgetWithText(ElevatedButton, 'onlyShowSelected'));
await tester.pumpAndSettle();
expect(find.text('Label behavior: onlyShowSelected'), findsOneWidget);
navigationBarWidget = tester.firstWidget(find.byType(NavigationBar));
expect(navigationBarWidget.labelBehavior, NavigationDestinationLabelBehavior.onlyShowSelected);
/// Test alwaysHide label behavior button.
await tester.tap(find.widgetWithText(ElevatedButton, 'alwaysHide'));
await tester.pumpAndSettle();
expect(find.text('Label behavior: alwaysHide'), findsOneWidget);
navigationBarWidget = tester.firstWidget(find.byType(NavigationBar));
expect(navigationBarWidget.labelBehavior, NavigationDestinationLabelBehavior.alwaysHide);
});
}
| flutter/examples/api/test/material/navigation_bar/navigation_bar.1_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/navigation_bar/navigation_bar.1_test.dart",
"repo_id": "flutter",
"token_count": 574
} | 602 |
// Copyright 2014 The Flutter Authors. 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/scrollbar/scrollbar.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Scrollbar.0 works well on all platforms', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ScrollbarExampleApp(),
);
final Finder buttonFinder = find.byType(Scrollbar);
await tester.drag(buttonFinder.last, const Offset(0, 100.0));
expect(tester.takeException(), isNull);
}, variant: TargetPlatformVariant.all());
}
| flutter/examples/api/test/material/scrollbar/scrollbar.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/scrollbar/scrollbar.0_test.dart",
"repo_id": "flutter",
"token_count": 239
} | 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.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/material/switch_list_tile/custom_labeled_switch.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('LinkedLabelSwitch contains RichText and Switch', (WidgetTester tester) async {
await tester.pumpWidget(
const example.LabeledSwitchApp(),
);
// Label text is in a RichText widget with the correct text.
final RichText richText = tester.widget(find.byType(RichText).first);
expect(richText.text.toPlainText(), 'Linked, tappable label text');
// Switch is initially off.
Switch switchWidget = tester.widget(find.byType(Switch));
expect(switchWidget.value, isFalse);
// Tap to toggle the switch.
await tester.tap(find.byType(Switch));
await tester.pumpAndSettle();
// Switch is now on.
switchWidget = tester.widget(find.byType(Switch));
expect(switchWidget.value, isTrue);
});
}
| flutter/examples/api/test/material/switch_list_tile/custom_labeled_switch.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/material/switch_list_tile/custom_labeled_switch.0_test.dart",
"repo_id": "flutter",
"token_count": 375
} | 604 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_api_samples/services/mouse_cursor/mouse_cursor.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Uses Text Cursor', (WidgetTester tester) async {
await tester.pumpWidget(
const example.MouseCursorExampleApp(),
);
expect(find.byType(MouseRegion), findsNWidgets(2)); // There's one in the MaterialApp
final Finder mouseRegionFinder = find.ancestor(of: find.byType(Container), matching: find.byType(MouseRegion));
expect(mouseRegionFinder, findsOneWidget);
expect((tester.widget(mouseRegionFinder) as MouseRegion).cursor, equals(SystemMouseCursors.text));
});
}
| flutter/examples/api/test/services/mouse_cursor/mouse_cursor.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/services/mouse_cursor/mouse_cursor.0_test.dart",
"repo_id": "flutter",
"token_count": 285
} | 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.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/widgets/animated_grid/sliver_animated_grid.0.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('SliverAnimatedGrid example', (WidgetTester tester) async {
await tester.pumpWidget(
const example.SliverAnimatedGridSample(),
);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsOneWidget);
expect(find.text('6'), findsOneWidget);
expect(find.text('7'), findsNothing);
await tester.tap(find.byIcon(Icons.add_circle));
await tester.pumpAndSettle();
expect(find.text('7'), findsOneWidget);
await tester.tap(find.byIcon(Icons.remove_circle));
await tester.pumpAndSettle();
expect(find.text('7'), findsNothing);
await tester.tap(find.text('2'));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.remove_circle));
await tester.pumpAndSettle();
expect(find.text('2'), findsNothing);
expect(find.text('6'), findsOneWidget);
});
}
| flutter/examples/api/test/widgets/animated_grid/sliver_animated_grid.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/animated_grid/sliver_animated_grid.0_test.dart",
"repo_id": "flutter",
"token_count": 493
} | 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';
import 'package:flutter_api_samples/widgets/basic/fractionally_sized_box.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('FractionallySizedBox sizes DecoratedBox', (WidgetTester tester) async {
const double appBarHeight = 56.0;
const double widthFactor = 0.5;
const double heightFactor = 0.5;
await tester.pumpWidget(
const example.FractionallySizedBoxApp(),
);
final FractionallySizedBox fractionallySizedBox = tester.widget(find.byType(FractionallySizedBox));
expect(fractionallySizedBox.widthFactor, widthFactor);
expect(fractionallySizedBox.heightFactor, heightFactor);
final Size boxSize = tester.getSize(find.byType(DecoratedBox));
expect(boxSize.width, 800 * widthFactor);
expect(boxSize.height, (600 - appBarHeight) * heightFactor);
});
}
| flutter/examples/api/test/widgets/basic/fractionally_sized_box.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/basic/fractionally_sized_box.0_test.dart",
"repo_id": "flutter",
"token_count": 355
} | 607 |
// Copyright 2014 The Flutter Authors. 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/gesture_detector/gesture_detector.2.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
void expectBorders(
WidgetTester tester, {
required bool expectGreenHasBorder,
required bool expectYellowHasBorder,
}) {
final Finder containerFinder = find.byType(Container);
final Finder greenFinder = containerFinder.first;
final Finder yellowFinder = containerFinder.last;
final Container greenContainer = tester.firstWidget<Container>(greenFinder);
final BoxDecoration? greenDecoration = greenContainer.decoration as BoxDecoration?;
expect(greenDecoration?.border, expectGreenHasBorder ? isNot(null) : null);
final Container yellowContainer = tester.firstWidget<Container>(yellowFinder);
final BoxDecoration? yellowDecoration = yellowContainer.decoration as BoxDecoration?;
expect(yellowDecoration?.border, expectYellowHasBorder ? isNot(null) : null);
}
void expectInnerGestureDetectorBehavior(WidgetTester tester, HitTestBehavior behavior) {
// There is a third GestureDetector added by Scaffold.
final Finder innerGestureDetectorFinder = find.byType(GestureDetector).at(1);
final GestureDetector innerGestureDetector = tester.firstWidget<GestureDetector>(innerGestureDetectorFinder);
expect(innerGestureDetector.behavior, behavior);
}
testWidgets('Only the green Container shows a red border when tapped', (WidgetTester tester) async {
await tester.pumpWidget(
const example.NestedGestureDetectorsApp(),
);
final Finder greenFinder = find.byType(Container).first;
final Offset greenTopLeftCorner = tester.getTopLeft(greenFinder);
await tester.tapAt(greenTopLeftCorner);
await tester.pumpAndSettle();
expectBorders(tester, expectGreenHasBorder: true, expectYellowHasBorder: false);
// Tap on the button to toggle inner GestureDetector.behavior
final Finder toggleBehaviorFinder = find.byType(ElevatedButton).last;
await tester.tap(toggleBehaviorFinder);
await tester.pump();
expectInnerGestureDetectorBehavior(tester, HitTestBehavior.translucent);
// Tap again on the green container, expect nothing changed
await tester.tapAt(greenTopLeftCorner);
await tester.pump();
expectBorders(tester, expectGreenHasBorder: true, expectYellowHasBorder: false);
// Tap on the reset button
final Finder resetFinder = find.byType(ElevatedButton).first;
await tester.tap(resetFinder);
await tester.pump();
expectInnerGestureDetectorBehavior(tester, HitTestBehavior.opaque);
});
testWidgets('Only the yellow Container shows a red border when tapped', (WidgetTester tester) async {
await tester.pumpWidget(
const example.NestedGestureDetectorsApp(),
);
final Finder yellowFinder = find.byType(Container).last;
final Offset yellowTopLeftCorner = tester.getTopLeft(yellowFinder);
await tester.tapAt(yellowTopLeftCorner);
await tester.pump();
expectBorders(tester, expectGreenHasBorder: false, expectYellowHasBorder: true);
// Tap on the button to toggle inner GestureDetector.behavior
final Finder toggleBehaviorFinder = find.byType(ElevatedButton).last;
await tester.tap(toggleBehaviorFinder);
await tester.pump();
expectInnerGestureDetectorBehavior(tester, HitTestBehavior.translucent);
// Tap again on the yellow container, expect nothing changed
await tester.tapAt(yellowTopLeftCorner);
await tester.pump();
expectBorders(tester, expectGreenHasBorder: false, expectYellowHasBorder: true);
// Tap on the reset button
final Finder resetFinder = find.byType(ElevatedButton).first;
await tester.tap(resetFinder);
await tester.pump();
expectInnerGestureDetectorBehavior(tester, HitTestBehavior.opaque);
});
}
| flutter/examples/api/test/widgets/gesture_detector/gesture_detector.2_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/gesture_detector/gesture_detector.2_test.dart",
"repo_id": "flutter",
"token_count": 1310
} | 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.
import 'package:flutter_api_samples/widgets/pop_scope/pop_scope.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
import '../navigator_utils.dart';
void main() {
testWidgets('Can choose to stay on page', (WidgetTester tester) async {
await tester.pumpWidget(
const example.NavigatorPopHandlerApp(),
);
expect(find.text('Page One'), findsOneWidget);
expect(find.text('Page Two'), findsNothing);
expect(find.text('Are you sure?'), findsNothing);
await tester.tap(find.text('Next page'));
await tester.pumpAndSettle();
expect(find.text('Page One'), findsNothing);
expect(find.text('Page Two'), findsOneWidget);
expect(find.text('Are you sure?'), findsNothing);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Page One'), findsNothing);
expect(find.text('Page Two'), findsOneWidget);
expect(find.text('Are you sure?'), findsOneWidget);
await tester.tap(find.text('Nevermind'));
await tester.pumpAndSettle();
expect(find.text('Page One'), findsNothing);
expect(find.text('Page Two'), findsOneWidget);
expect(find.text('Are you sure?'), findsNothing);
});
testWidgets('Can choose to go back', (WidgetTester tester) async {
await tester.pumpWidget(
const example.NavigatorPopHandlerApp(),
);
expect(find.text('Page One'), findsOneWidget);
expect(find.text('Page Two'), findsNothing);
expect(find.text('Are you sure?'), findsNothing);
await tester.tap(find.text('Next page'));
await tester.pumpAndSettle();
expect(find.text('Page One'), findsNothing);
expect(find.text('Page Two'), findsOneWidget);
expect(find.text('Are you sure?'), findsNothing);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Page One'), findsNothing);
expect(find.text('Page Two'), findsOneWidget);
expect(find.text('Are you sure?'), findsOneWidget);
await tester.tap(find.text('Leave'));
await tester.pumpAndSettle();
expect(find.text('Page One'), findsOneWidget);
expect(find.text('Page Two'), findsNothing);
expect(find.text('Are you sure?'), findsNothing);
});
}
| flutter/examples/api/test/widgets/pop_scope/pop_scope.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/pop_scope/pop_scope.0_test.dart",
"repo_id": "flutter",
"token_count": 811
} | 609 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_api_samples/widgets/slotted_render_object_widget/slotted_multi_child_render_object_widget_mixin.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('shows two widgets arranged diagonally', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ExampleWidget(),
);
expect(find.text('topLeft'), findsOneWidget);
expect(find.text('bottomRight'), findsOneWidget);
expect(
tester.getBottomRight(findContainerWithText('topLeft')),
tester.getTopLeft(findContainerWithText('bottomRight')),
);
expect(
tester.getSize(findContainerWithText('topLeft')),
const Size(200, 100),
);
expect(
tester.getSize(findContainerWithText('bottomRight')),
const Size(30, 60),
);
expect(
tester.getSize(find.byType(example.Diagonal)),
const Size(200 + 30, 100 + 60),
);
});
}
Finder findContainerWithText(String text) {
return find.ancestor(of: find.text(text), matching: find.byType(Container));
}
| flutter/examples/api/test/widgets/slotted_render_object_widget/slotted_multi_child_render_object_widget_mixin.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/slotted_render_object_widget/slotted_multi_child_render_object_widget_mixin.0_test.dart",
"repo_id": "flutter",
"token_count": 457
} | 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.
#ifndef MainViewController_h
#define MainViewController_h
#endif /* MainViewController_h */
#import <UIKit/UIKit.h>
#import <Flutter/Flutter.h>
#import "NativeViewController.h"
@protocol NativeViewControllerDelegate;
@interface MainViewController : UIViewController <NativeViewControllerDelegate>
@end
| flutter/examples/flutter_view/ios/Runner/MainViewController.h/0 | {
"file_path": "flutter/examples/flutter_view/ios/Runner/MainViewController.h",
"repo_id": "flutter",
"token_count": 139
} | 611 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| flutter/examples/hello_world/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "flutter/examples/hello_world/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 32
} | 612 |
#include "ephemeral/Flutter-Generated.xcconfig"
| flutter/examples/image_list/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "flutter/examples/image_list/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "flutter",
"token_count": 19
} | 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.
// This example shows how to use the ui.Canvas interface to draw various shapes
// with gradients and transforms.
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui' as ui;
// The FlutterView into which this example will draw; set in the main method.
late final ui.FlutterView view;
ui.Picture paint(ui.Rect paintBounds) {
// First we create a PictureRecorder to record the commands we're going to
// feed in the canvas. The PictureRecorder will eventually produce a Picture,
// which is an immutable record of those commands.
final ui.PictureRecorder recorder = ui.PictureRecorder();
// Next, we create a canvas from the recorder. The canvas is an interface
// which can receive drawing commands. The canvas interface is modeled after
// the SkCanvas interface from Skia. The paintBounds establishes a "cull rect"
// for the canvas, which lets the implementation discard any commands that
// are entirely outside this rectangle.
final ui.Canvas canvas = ui.Canvas(recorder, paintBounds);
final ui.Paint paint = ui.Paint();
canvas.drawPaint(ui.Paint()..color = const ui.Color(0xFFFFFFFF));
final ui.Size size = paintBounds.size;
final ui.Offset mid = size.center(ui.Offset.zero);
final double radius = size.shortestSide / 2.0;
final double devicePixelRatio = view.devicePixelRatio;
final ui.Size logicalSize = view.physicalSize / devicePixelRatio;
// Saves a copy of current transform onto the save stack.
canvas.save();
// Transforms that occur after this point apply only to the
// yellow-bluish rectangle.
// This line will cause the transform to shift entirely outside the paint
// boundaries, which will cause the canvas interface to discard its
// commands. Comment it out to see it on screen.
canvas.translate(-mid.dx / 2.0, logicalSize.height * 2.0);
// Clips the current transform.
canvas.clipRect(
ui.Rect.fromLTRB(0, radius + 50, logicalSize.width, logicalSize.height),
clipOp: ui.ClipOp.difference,
);
// Shifts the coordinate space of and rotates the current transform.
canvas.translate(mid.dx, mid.dy);
canvas.rotate(math.pi/4);
final ui.Gradient yellowBlue = ui.Gradient.linear(
ui.Offset(-radius, -radius),
ui.Offset.zero,
<ui.Color>[const ui.Color(0xFFFFFF00), const ui.Color(0xFF0000FF)],
);
// Draws a yellow-bluish rectangle.
canvas.drawRect(
ui.Rect.fromLTRB(-radius, -radius, radius, radius),
ui.Paint()..shader = yellowBlue,
);
// Transforms that occur after this point apply only to the
// yellow circle.
// Scale x and y by 0.5.
final Float64List scaleMatrix = Float64List.fromList(<double>[
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
]);
canvas.transform(scaleMatrix);
// Sets paint to transparent yellow.
paint.color = const ui.Color.fromARGB(128, 0, 255, 0);
// Draws a transparent yellow circle.
canvas.drawCircle(ui.Offset.zero, radius, paint);
// Restores the transform from before `save` was called.
canvas.restore();
// Sets paint to transparent red.
paint.color = const ui.Color.fromARGB(128, 255, 0, 0);
// This circle is drawn on top of the previous layer that contains
// the rectangle and smaller circle.
canvas.drawCircle(const ui.Offset(150.0, 300.0), radius, paint);
// When we're done issuing painting commands, we end the recording and receive
// a Picture, which is an immutable record of the commands we've issued. You
// can draw a Picture into another canvas or include it as part of a
// composited scene.
return recorder.endRecording();
}
ui.Scene composite(ui.Picture picture, ui.Rect paintBounds) {
final double devicePixelRatio = view.devicePixelRatio;
final Float64List deviceTransform = Float64List(16)
..[0] = devicePixelRatio
..[5] = devicePixelRatio
..[10] = 1.0
..[15] = 1.0;
final ui.SceneBuilder sceneBuilder = ui.SceneBuilder()
..pushTransform(deviceTransform)
..addPicture(ui.Offset.zero, picture)
..pop();
return sceneBuilder.build();
}
void beginFrame(Duration timeStamp) {
final ui.Rect paintBounds = ui.Offset.zero & (view.physicalSize / view.devicePixelRatio);
final ui.Picture picture = paint(paintBounds);
final ui.Scene scene = composite(picture, paintBounds);
view.render(scene);
}
void main() {
// TODO(goderbauer): Create a window if embedder doesn't provide an implicit view to draw into.
assert(ui.PlatformDispatcher.instance.implicitView != null);
view = ui.PlatformDispatcher.instance.implicitView!;
ui.PlatformDispatcher.instance
..onBeginFrame = beginFrame
..scheduleFrame();
}
| flutter/examples/layers/raw/canvas.dart/0 | {
"file_path": "flutter/examples/layers/raw/canvas.dart",
"repo_id": "flutter",
"token_count": 1557
} | 614 |
include: ../../../analysis_options.yaml
linter:
rules:
only_throw_errors: false # We are more flexible for tests.
| flutter/examples/layers/test/analysis_options.yaml/0 | {
"file_path": "flutter/examples/layers/test/analysis_options.yaml",
"repo_id": "flutter",
"token_count": 41
} | 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/material.dart';
typedef _TextTransformer = Widget Function(String name, String text);
// From https://en.wikiquote.org/wiki/2001:_A_Space_Odyssey_(film)
const String _kDialogText = '''
Dave: Open the pod bay doors, please, HAL. Open the pod bay doors, please, HAL. Hello, HAL. Do you read me? Hello, HAL. Do you read me? Do you read me, HAL?
HAL: Affirmative, Dave. I read you.
Dave: Open the pod bay doors, HAL.
HAL: I'm sorry, Dave. I'm afraid I can't do that.
Dave: What's the problem?
HAL: I think you know what the problem is just as well as I do.
Dave: What are you talking about, HAL?
HAL: This mission is too important for me to allow you to jeopardize it.''';
// [["Dave", "Open the pod bay..."] ...]
final List<List<String>> _kNameLines = _kDialogText
.split('\n')
.map<List<String>>((String line) => line.split(':'))
.toList();
final TextStyle _kDaveStyle = TextStyle(color: Colors.indigo.shade400, height: 1.8);
final TextStyle _kHalStyle = TextStyle(color: Colors.red.shade400, fontFamily: 'monospace');
const TextStyle _kBold = TextStyle(fontWeight: FontWeight.bold);
const TextStyle _kUnderline = TextStyle(
decoration: TextDecoration.underline,
decorationColor: Color(0xFF000000),
decorationStyle: TextDecorationStyle.wavy,
);
Widget toStyledText(String name, String text) {
final TextStyle lineStyle = (name == 'Dave') ? _kDaveStyle : _kHalStyle;
return RichText(
key: Key(text),
text: TextSpan(
style: lineStyle,
children: <TextSpan>[
TextSpan(
style: _kBold,
children: <TextSpan>[
TextSpan(
style: _kUnderline,
text: name,
),
const TextSpan(text: ':'),
],
),
TextSpan(text: text),
],
),
);
}
Widget toPlainText(String name, String text) => Text('$name:$text');
class SpeakerSeparator extends StatelessWidget {
const SpeakerSeparator({super.key});
@override
Widget build(BuildContext context) {
return Container(
constraints: const BoxConstraints.expand(height: 0.0),
margin: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 64.0),
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(color: Color.fromARGB(24, 0, 0, 0)),
),
),
);
}
}
class StyledTextDemo extends StatefulWidget {
const StyledTextDemo({super.key});
@override
State<StyledTextDemo> createState() => _StyledTextDemoState();
}
class _StyledTextDemoState extends State<StyledTextDemo> {
_TextTransformer _toText = toStyledText;
void _handleTap() {
setState(() {
_toText = (_toText == toPlainText) ? toStyledText : toPlainText;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: _kNameLines
.map<Widget>((List<String> nameAndText) => _toText(nameAndText[0], nameAndText[1]))
.expand((Widget line) => <Widget>[
line,
const SpeakerSeparator(),
])
.toList()..removeLast(),
),
),
);
}
}
void main() {
runApp(MaterialApp(
theme: ThemeData.light(),
home: Scaffold(
appBar: AppBar(
title: const Text('Hal and Dave'),
),
body: Material(
color: Colors.grey.shade50,
child: const StyledTextDemo(),
),
),
));
}
| flutter/examples/layers/widgets/styled_text.dart/0 | {
"file_path": "flutter/examples/layers/widgets/styled_text.dart",
"repo_id": "flutter",
"token_count": 1536
} | 616 |
include: ../analysis_options.yaml
linter:
rules:
# diagnostic_describe_all_properties: true # blocked on https://github.com/dart-lang/sdk/issues/47418
prefer_relative_imports: false # doesn't really work when you have subpackages like we do here
| flutter/packages/flutter/lib/analysis_options.yaml/0 | {
"file_path": "flutter/packages/flutter/lib/analysis_options.yaml",
"repo_id": "flutter",
"token_count": 82
} | 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.
# 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 from the Services library. *
version: 1
transforms:
# Changes made in https://github.com/flutter/flutter/pull/122446
- title: "Migrate to empty 'text' string"
date: 2023-06-26
element:
uris: [ 'services.dart' ]
constructor: ''
inClass: 'ClipboardData'
changes:
- kind: 'changeParameterType'
name: 'text'
nullability: 'non_null'
argumentValue:
expression: "''"
# Changes made in https://github.com/flutter/flutter/pull/60320
- title: "Migrate to 'viewId'"
date: 2020-07-05
element:
uris: [ 'services.dart' ]
getter: id
inClass: 'TextureAndroidViewController'
changes:
- kind: 'rename'
newName: 'viewId'
# Changes made in https://github.com/flutter/flutter/pull/60320
- title: "Migrate to 'viewId'"
date: 2020-07-05
element:
uris: [ 'services.dart' ]
getter: id
inClass: 'SurfaceAndroidViewController'
changes:
- kind: 'rename'
newName: 'viewId'
# Changes made in https://github.com/flutter/flutter/pull/81303
- title: "Migrate to 'setEnabledSystemUIMode'"
date: 2021-06-08
element:
uris: [ 'services.dart' ]
method: 'setEnabledSystemUIOverlays'
inClass: 'SystemChrome'
changes:
- kind: 'rename'
newName: 'setEnabledSystemUIMode'
- kind: 'removeParameter'
index: 0
- kind: 'addParameter'
index: 0
name: 'mode'
style: required_positional
argumentValue:
expression: 'SystemUiMode.manual'
- kind: 'addParameter'
index: 1
name: 'overlays'
style: optional_named
argumentValue:
expression: '{% overlays %}'
requiredIf: "overlays != ''"
variables:
overlays:
kind: 'fragment'
value: 'arguments[0]'
# Before adding a new fix: read instructions at the top of this file.
| flutter/packages/flutter/lib/fix_data/fix_services.yaml/0 | {
"file_path": "flutter/packages/flutter/lib/fix_data/fix_services.yaml",
"repo_id": "flutter",
"token_count": 1056
} | 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.
/// The Flutter rendering tree.
///
/// To use, import `package:flutter/rendering.dart`.
///
/// The [RenderObject] hierarchy is used by the Flutter Widgets library to
/// implement its layout and painting back-end. Generally, while you may use
/// custom [RenderBox] classes for specific effects in your applications, most
/// of the time your only interaction with the [RenderObject] hierarchy will be
/// in debugging layout issues.
///
/// If you are developing your own library or application directly on top of the
/// rendering library, then you will want to have a binding (see [BindingBase]).
/// You can use [RenderingFlutterBinding], or you can create your own binding.
/// If you create your own binding, it needs to import at least
/// [ServicesBinding], [GestureBinding], [SchedulerBinding], [PaintingBinding],
/// and [RendererBinding]. The rendering library does not automatically create a
/// binding, but relies on one being initialized with those features.
library rendering;
export 'package:flutter/foundation.dart' show
DiagnosticLevel,
ValueChanged,
ValueGetter,
ValueSetter,
VoidCallback;
export 'package:flutter/semantics.dart';
export 'package:vector_math/vector_math_64.dart' show Matrix4;
export 'src/rendering/animated_size.dart';
export 'src/rendering/binding.dart';
export 'src/rendering/box.dart';
export 'src/rendering/custom_layout.dart';
export 'src/rendering/custom_paint.dart';
export 'src/rendering/debug.dart';
export 'src/rendering/debug_overflow_indicator.dart';
export 'src/rendering/decorated_sliver.dart';
export 'src/rendering/editable.dart';
export 'src/rendering/error.dart';
export 'src/rendering/flex.dart';
export 'src/rendering/flow.dart';
export 'src/rendering/image.dart';
export 'src/rendering/layer.dart';
export 'src/rendering/layout_helper.dart';
export 'src/rendering/list_body.dart';
export 'src/rendering/list_wheel_viewport.dart';
export 'src/rendering/mouse_tracker.dart';
export 'src/rendering/object.dart';
export 'src/rendering/paragraph.dart';
export 'src/rendering/performance_overlay.dart';
export 'src/rendering/platform_view.dart';
export 'src/rendering/proxy_box.dart';
export 'src/rendering/proxy_sliver.dart';
export 'src/rendering/rotated_box.dart';
export 'src/rendering/selection.dart';
export 'src/rendering/service_extensions.dart';
export 'src/rendering/shifted_box.dart';
export 'src/rendering/sliver.dart';
export 'src/rendering/sliver_fill.dart';
export 'src/rendering/sliver_fixed_extent_list.dart';
export 'src/rendering/sliver_grid.dart';
export 'src/rendering/sliver_group.dart';
export 'src/rendering/sliver_list.dart';
export 'src/rendering/sliver_multi_box_adaptor.dart';
export 'src/rendering/sliver_padding.dart';
export 'src/rendering/sliver_persistent_header.dart';
export 'src/rendering/stack.dart';
export 'src/rendering/table.dart';
export 'src/rendering/table_border.dart';
export 'src/rendering/texture.dart';
export 'src/rendering/tweens.dart';
export 'src/rendering/view.dart';
export 'src/rendering/viewport.dart';
export 'src/rendering/viewport_offset.dart';
export 'src/rendering/wrap.dart';
| flutter/packages/flutter/lib/rendering.dart/0 | {
"file_path": "flutter/packages/flutter/lib/rendering.dart",
"repo_id": "flutter",
"token_count": 1061
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'colors.dart';
import 'constants.dart';
import 'theme.dart';
// Measured against iOS 12 in Xcode.
const EdgeInsets _kButtonPadding = EdgeInsets.all(16.0);
const EdgeInsets _kBackgroundButtonPadding = EdgeInsets.symmetric(
vertical: 14.0,
horizontal: 64.0,
);
/// An iOS-style button.
///
/// Takes in a text or an icon that fades out and in on touch. May optionally have a
/// background.
///
/// The [padding] defaults to 16.0 pixels. When using a [CupertinoButton] within
/// a fixed height parent, like a [CupertinoNavigationBar], a smaller, or even
/// [EdgeInsets.zero], should be used to prevent clipping larger [child]
/// widgets.
///
/// {@tool dartpad}
/// This sample shows produces an enabled and disabled [CupertinoButton] and
/// [CupertinoButton.filled].
///
/// ** See code in examples/api/lib/cupertino/button/cupertino_button.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * <https://developer.apple.com/design/human-interface-guidelines/buttons/>
class CupertinoButton extends StatefulWidget {
/// Creates an iOS-style button.
const CupertinoButton({
super.key,
required this.child,
this.padding,
this.color,
this.disabledColor = CupertinoColors.quaternarySystemFill,
this.minSize = kMinInteractiveDimensionCupertino,
this.pressedOpacity = 0.4,
this.borderRadius = const BorderRadius.all(Radius.circular(8.0)),
this.alignment = Alignment.center,
required this.onPressed,
}) : assert(pressedOpacity == null || (pressedOpacity >= 0.0 && pressedOpacity <= 1.0)),
_filled = false;
/// Creates an iOS-style button with a filled background.
///
/// The background color is derived from the [CupertinoTheme]'s `primaryColor`.
///
/// To specify a custom background color, use the [color] argument of the
/// default constructor.
const CupertinoButton.filled({
super.key,
required this.child,
this.padding,
this.disabledColor = CupertinoColors.quaternarySystemFill,
this.minSize = kMinInteractiveDimensionCupertino,
this.pressedOpacity = 0.4,
this.borderRadius = const BorderRadius.all(Radius.circular(8.0)),
this.alignment = Alignment.center,
required this.onPressed,
}) : assert(pressedOpacity == null || (pressedOpacity >= 0.0 && pressedOpacity <= 1.0)),
color = null,
_filled = true;
/// The widget below this widget in the tree.
///
/// Typically a [Text] widget.
final Widget child;
/// The amount of space to surround the child inside the bounds of the button.
///
/// Defaults to 16.0 pixels.
final EdgeInsetsGeometry? padding;
/// The color of the button's background.
///
/// Defaults to null which produces a button with no background or border.
///
/// Defaults to the [CupertinoTheme]'s `primaryColor` when the
/// [CupertinoButton.filled] constructor is used.
final Color? color;
/// The color of the button's background when the button is disabled.
///
/// Ignored if the [CupertinoButton] doesn't also have a [color].
///
/// Defaults to [CupertinoColors.quaternarySystemFill] when [color] is
/// specified.
final Color disabledColor;
/// The callback that is called when the button is tapped or otherwise activated.
///
/// If this is set to null, the button will be disabled.
final VoidCallback? onPressed;
/// Minimum size of the button.
///
/// Defaults to kMinInteractiveDimensionCupertino which the iOS Human
/// Interface Guidelines recommends as the minimum tappable area.
final double? minSize;
/// The opacity that the button will fade to when it is pressed.
/// The button will have an opacity of 1.0 when it is not pressed.
///
/// This defaults to 0.4. If null, opacity will not change on pressed if using
/// your own custom effects is desired.
final double? pressedOpacity;
/// The radius of the button's corners when it has a background color.
///
/// Defaults to round corners of 8 logical pixels.
final BorderRadius? borderRadius;
/// The alignment of the button's [child].
///
/// Typically buttons are sized to be just big enough to contain the child and its
/// [padding]. If the button's size is constrained to a fixed size, for example by
/// enclosing it with a [SizedBox], this property defines how the child is aligned
/// within the available space.
///
/// Always defaults to [Alignment.center].
final AlignmentGeometry alignment;
final bool _filled;
/// Whether the button is enabled or disabled. Buttons are disabled by default. To
/// enable a button, set its [onPressed] property to a non-null value.
bool get enabled => onPressed != null;
@override
State<CupertinoButton> createState() => _CupertinoButtonState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('enabled', value: enabled, ifFalse: 'disabled'));
}
}
class _CupertinoButtonState extends State<CupertinoButton> with SingleTickerProviderStateMixin {
// Eyeballed values. Feel free to tweak.
static const Duration kFadeOutDuration = Duration(milliseconds: 120);
static const Duration kFadeInDuration = Duration(milliseconds: 180);
final Tween<double> _opacityTween = Tween<double>(begin: 1.0);
late AnimationController _animationController;
late Animation<double> _opacityAnimation;
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: const Duration(milliseconds: 200),
value: 0.0,
vsync: this,
);
_opacityAnimation = _animationController
.drive(CurveTween(curve: Curves.decelerate))
.drive(_opacityTween);
_setTween();
}
@override
void didUpdateWidget(CupertinoButton old) {
super.didUpdateWidget(old);
_setTween();
}
void _setTween() {
_opacityTween.end = widget.pressedOpacity ?? 1.0;
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
bool _buttonHeldDown = false;
void _handleTapDown(TapDownDetails event) {
if (!_buttonHeldDown) {
_buttonHeldDown = true;
_animate();
}
}
void _handleTapUp(TapUpDetails event) {
if (_buttonHeldDown) {
_buttonHeldDown = false;
_animate();
}
}
void _handleTapCancel() {
if (_buttonHeldDown) {
_buttonHeldDown = false;
_animate();
}
}
void _animate() {
if (_animationController.isAnimating) {
return;
}
final bool wasHeldDown = _buttonHeldDown;
final TickerFuture ticker = _buttonHeldDown
? _animationController.animateTo(1.0, duration: kFadeOutDuration, curve: Curves.easeInOutCubicEmphasized)
: _animationController.animateTo(0.0, duration: kFadeInDuration, curve: Curves.easeOutCubic);
ticker.then<void>((void value) {
if (mounted && wasHeldDown != _buttonHeldDown) {
_animate();
}
});
}
@override
Widget build(BuildContext context) {
final bool enabled = widget.enabled;
final CupertinoThemeData themeData = CupertinoTheme.of(context);
final Color primaryColor = themeData.primaryColor;
final Color? backgroundColor = widget.color == null
? (widget._filled ? primaryColor : null)
: CupertinoDynamicColor.maybeResolve(widget.color, context);
final Color foregroundColor = backgroundColor != null
? themeData.primaryContrastingColor
: enabled
? primaryColor
: CupertinoDynamicColor.resolve(CupertinoColors.placeholderText, context);
final TextStyle textStyle = themeData.textTheme.textStyle.copyWith(color: foregroundColor);
return MouseRegion(
cursor: enabled && kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: enabled ? _handleTapDown : null,
onTapUp: enabled ? _handleTapUp : null,
onTapCancel: enabled ? _handleTapCancel : null,
onTap: widget.onPressed,
child: Semantics(
button: true,
child: ConstrainedBox(
constraints: widget.minSize == null
? const BoxConstraints()
: BoxConstraints(
minWidth: widget.minSize!,
minHeight: widget.minSize!,
),
child: FadeTransition(
opacity: _opacityAnimation,
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: widget.borderRadius,
color: backgroundColor != null && !enabled
? CupertinoDynamicColor.resolve(widget.disabledColor, context)
: backgroundColor,
),
child: Padding(
padding: widget.padding ?? (backgroundColor != null
? _kBackgroundButtonPadding
: _kButtonPadding),
child: Align(
alignment: widget.alignment,
widthFactor: 1.0,
heightFactor: 1.0,
child: DefaultTextStyle(
style: textStyle,
child: IconTheme(
data: IconThemeData(color: foregroundColor),
child: widget.child,
),
),
),
),
),
),
),
),
),
);
}
}
| flutter/packages/flutter/lib/src/cupertino/button.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/button.dart",
"repo_id": "flutter",
"token_count": 3594
} | 620 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import '../widgets/framework.dart';
/// Indicates the visual level for a piece of content. Equivalent to `UIUserInterfaceLevel`
/// from `UIKit`.
///
/// See also:
///
/// * `UIUserInterfaceLevel`, the UIKit equivalent: https://developer.apple.com/documentation/uikit/uiuserinterfacelevel.
enum CupertinoUserInterfaceLevelData {
/// The level for your window's main content.
base,
/// The level for content visually above [base].
elevated,
}
/// Establishes a subtree in which [CupertinoUserInterfaceLevel.of] resolves to
/// the given visual elevation from the [CupertinoUserInterfaceLevelData]. This
/// can be used to apply style differences based on a widget's elevation.
///
/// Querying the current elevation status using [CupertinoUserInterfaceLevel.of]
/// will cause your widget to rebuild automatically whenever the
/// [CupertinoUserInterfaceLevelData] changes.
///
/// If no [CupertinoUserInterfaceLevel] is in scope then the
/// [CupertinoUserInterfaceLevel.of] method will throw an exception.
/// Alternatively, [CupertinoUserInterfaceLevel.maybeOf] can be used, which
/// returns null instead of throwing if no [CupertinoUserInterfaceLevel] is in
/// scope.
///
/// See also:
///
/// * [CupertinoUserInterfaceLevelData], specifies the visual level for the content
/// in the subtree [CupertinoUserInterfaceLevel] established.
class CupertinoUserInterfaceLevel extends InheritedWidget {
/// Creates a [CupertinoUserInterfaceLevel] to change descendant Cupertino widget's
/// visual level.
const CupertinoUserInterfaceLevel({
super.key,
required CupertinoUserInterfaceLevelData data,
required super.child,
}) : _data = data;
final CupertinoUserInterfaceLevelData _data;
@override
bool updateShouldNotify(CupertinoUserInterfaceLevel oldWidget) => oldWidget._data != _data;
/// The data from the closest instance of this class that encloses the given
/// context.
///
/// You can use this function to query the user interface elevation level within
/// the given [BuildContext]. When that information changes, your widget will
/// be scheduled to be rebuilt, keeping your widget up-to-date.
///
/// See also:
///
/// * [maybeOf], which is similar, but will return null if no
/// [CupertinoUserInterfaceLevel] encloses the given context.
static CupertinoUserInterfaceLevelData of(BuildContext context) {
final CupertinoUserInterfaceLevel? query = context.dependOnInheritedWidgetOfExactType<CupertinoUserInterfaceLevel>();
if (query != null) {
return query._data;
}
throw FlutterError(
'CupertinoUserInterfaceLevel.of() called with a context that does not contain a CupertinoUserInterfaceLevel.\n'
'No CupertinoUserInterfaceLevel ancestor could be found starting from the context that was passed '
'to CupertinoUserInterfaceLevel.of(). This can happen because you do not have a WidgetsApp or '
'MaterialApp widget (those widgets introduce a CupertinoUserInterfaceLevel), or it can happen '
'if the context you use comes from a widget above those widgets.\n'
'The context used was:\n'
' $context',
);
}
/// The data from the closest instance of this class that encloses the given
/// context, if there is one.
///
/// Returns null if no [CupertinoUserInterfaceLevel] encloses the given context.
///
/// You can use this function to query the user interface elevation level within
/// the given [BuildContext]. When that information changes, your widget will
/// be scheduled to be rebuilt, keeping your widget up-to-date.
///
/// See also:
///
/// * [of], which is similar, but will throw an exception if no
/// [CupertinoUserInterfaceLevel] encloses the given context.
static CupertinoUserInterfaceLevelData? maybeOf(BuildContext context) {
final CupertinoUserInterfaceLevel? query = context.dependOnInheritedWidgetOfExactType<CupertinoUserInterfaceLevel>();
return query?._data;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<CupertinoUserInterfaceLevelData>('user interface level', _data));
}
}
| flutter/packages/flutter/lib/src/cupertino/interface_level.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/interface_level.dart",
"repo_id": "flutter",
"token_count": 1235
} | 621 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart' show SelectionChangedCause, SuggestionSpan;
import 'package:flutter/widgets.dart';
import 'debug.dart';
import 'localizations.dart';
import 'text_selection_toolbar.dart';
import 'text_selection_toolbar_button.dart';
/// iOS only shows 3 spell check suggestions in the toolbar.
const int _kMaxSuggestions = 3;
/// The default spell check suggestions toolbar for iOS.
///
/// Tries to position itself below the [anchors], but if it doesn't fit, then it
/// readjusts to fit above bottom view insets.
///
/// See also:
/// * [SpellCheckSuggestionsToolbar], which is similar but for both the
/// Material and Cupertino libraries.
class CupertinoSpellCheckSuggestionsToolbar extends StatelessWidget {
/// Constructs a [CupertinoSpellCheckSuggestionsToolbar].
///
/// [buttonItems] must not contain more than three items.
const CupertinoSpellCheckSuggestionsToolbar({
super.key,
required this.anchors,
required this.buttonItems,
}) : assert(buttonItems.length <= _kMaxSuggestions);
/// Constructs a [CupertinoSpellCheckSuggestionsToolbar] with the default
/// children for an [EditableText].
///
/// See also:
/// * [SpellCheckSuggestionsToolbar.editableText], which is similar but
/// builds an Android-style toolbar.
CupertinoSpellCheckSuggestionsToolbar.editableText({
super.key,
required EditableTextState editableTextState,
}) : buttonItems = buildButtonItems(editableTextState) ?? <ContextMenuButtonItem>[],
anchors = editableTextState.contextMenuAnchors;
/// The location on which to anchor the menu.
final TextSelectionToolbarAnchors anchors;
/// The [ContextMenuButtonItem]s that will be turned into the correct button
/// widgets and displayed in the spell check suggestions toolbar.
///
/// Must not contain more than three items.
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar.buttonItems], the list of
/// [ContextMenuButtonItem]s that are used to build the buttons of the
/// text selection toolbar.
/// * [SpellCheckSuggestionsToolbar.buttonItems], the list of
/// [ContextMenuButtonItem]s used to build the Material style spell check
/// suggestions toolbar.
final List<ContextMenuButtonItem> buttonItems;
/// Builds the button items for the toolbar based on the available
/// spell check suggestions.
static List<ContextMenuButtonItem>? buildButtonItems(
EditableTextState editableTextState,
) {
// Determine if composing region is misspelled.
final SuggestionSpan? spanAtCursorIndex =
editableTextState.findSuggestionSpanAtCursorIndex(
editableTextState.currentTextEditingValue.selection.baseOffset,
);
if (spanAtCursorIndex == null) {
return null;
}
if (spanAtCursorIndex.suggestions.isEmpty) {
assert(debugCheckHasCupertinoLocalizations(editableTextState.context));
final CupertinoLocalizations localizations =
CupertinoLocalizations.of(editableTextState.context);
return <ContextMenuButtonItem>[
ContextMenuButtonItem(
onPressed: null,
label: localizations.noSpellCheckReplacementsLabel,
)
];
}
final List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[];
// Build suggestion buttons.
for (final String suggestion in spanAtCursorIndex.suggestions.take(_kMaxSuggestions)) {
buttonItems.add(ContextMenuButtonItem(
onPressed: () {
if (!editableTextState.mounted) {
return;
}
_replaceText(
editableTextState,
suggestion,
spanAtCursorIndex.range,
);
},
label: suggestion,
));
}
return buttonItems;
}
static void _replaceText(EditableTextState editableTextState, String text, TextRange replacementRange) {
// Replacement cannot be performed if the text is read only or obscured.
assert(!editableTextState.widget.readOnly && !editableTextState.widget.obscureText);
final TextEditingValue newValue = editableTextState.textEditingValue
.replaced(
replacementRange,
text,
)
.copyWith(
selection: TextSelection.collapsed(
offset: replacementRange.start + text.length,
),
);
editableTextState.userUpdateTextEditingValue(newValue,SelectionChangedCause.toolbar);
// Schedule a call to bringIntoView() after renderEditable updates.
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
if (editableTextState.mounted) {
editableTextState.bringIntoView(editableTextState.textEditingValue.selection.extent);
}
}, debugLabel: 'SpellCheckSuggestions.bringIntoView');
editableTextState.hideToolbar();
}
/// Builds the toolbar buttons based on the [buttonItems].
List<Widget> _buildToolbarButtons(BuildContext context) {
return buttonItems.map((ContextMenuButtonItem buttonItem) {
return CupertinoTextSelectionToolbarButton.buttonItem(
buttonItem: buttonItem,
);
}).toList();
}
@override
Widget build(BuildContext context) {
if (buttonItems.isEmpty) {
return const SizedBox.shrink();
}
final List<Widget> children = _buildToolbarButtons(context);
return CupertinoTextSelectionToolbar(
anchorAbove: anchors.primaryAnchor,
anchorBelow: anchors.secondaryAnchor == null ? anchors.primaryAnchor : anchors.secondaryAnchor!,
children: children,
);
}
}
| flutter/packages/flutter/lib/src/cupertino/spell_check_suggestions_toolbar.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/spell_check_suggestions_toolbar.dart",
"repo_id": "flutter",
"token_count": 1928
} | 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 'bitfield.dart' as bitfield;
/// The dart:html implementation of [bitfield.kMaxUnsignedSMI].
///
/// This value is used as an optimization to coerce some numbers to be within
/// the SMI range and avoid heap allocations. Because number encoding is
/// VM-specific, there's no guarantee that this optimization will be effective
/// on all JavaScript engines. The value picked here should be correct, but it
/// does not have to guarantee efficiency.
const int kMaxUnsignedSMI = -1;
/// The dart:html implementation of [bitfield.Bitfield].
class BitField<T extends dynamic> implements bitfield.BitField<T> {
/// The dart:html implementation of [bitfield.Bitfield].
// Can remove when we have metaclasses.
// ignore: avoid_unused_constructor_parameters
BitField(int length);
/// The dart:html implementation of [bitfield.Bitfield.filled].
// Can remove when we have metaclasses.
// ignore: avoid_unused_constructor_parameters
BitField.filled(int length, bool value);
@override
bool operator [](T index) {
throw UnsupportedError('Not supported when compiling to JavaScript');
}
@override
void operator []=(T index, bool value) {
throw UnsupportedError('Not supported when compiling to JavaScript');
}
@override
void reset([ bool value = false ]) {
throw UnsupportedError('Not supported when compiling to JavaScript');
}
}
| flutter/packages/flutter/lib/src/foundation/_bitfield_web.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/_bitfield_web.dart",
"repo_id": "flutter",
"token_count": 416
} | 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.
// TODO(ianh): These should be on the Set and List classes themselves.
/// Compares two sets for element-by-element equality.
///
/// Returns true if the sets are both null, or if they are both non-null, have
/// the same length, and contain the same members. Returns false otherwise.
/// Order is not compared.
///
/// If the elements are maps, lists, sets, or other collections/composite
/// objects, then the contents of those elements are not compared element by
/// element unless their equality operators ([Object.==]) do so. For checking
/// deep equality, consider using the [DeepCollectionEquality] class.
///
/// See also:
///
/// * [listEquals], which does something similar for lists.
/// * [mapEquals], which does something similar for maps.
bool setEquals<T>(Set<T>? a, Set<T>? b) {
if (a == null) {
return b == null;
}
if (b == null || a.length != b.length) {
return false;
}
if (identical(a, b)) {
return true;
}
for (final T value in a) {
if (!b.contains(value)) {
return false;
}
}
return true;
}
/// Compares two lists for element-by-element equality.
///
/// Returns true if the lists are both null, or if they are both non-null, have
/// the same length, and contain the same members in the same order. Returns
/// false otherwise.
///
/// If the elements are maps, lists, sets, or other collections/composite
/// objects, then the contents of those elements are not compared element by
/// element unless their equality operators ([Object.==]) do so. For checking
/// deep equality, consider using the [DeepCollectionEquality] class.
///
/// See also:
///
/// * [setEquals], which does something similar for sets.
/// * [mapEquals], which does something similar for maps.
bool listEquals<T>(List<T>? a, List<T>? b) {
if (a == null) {
return b == null;
}
if (b == null || a.length != b.length) {
return false;
}
if (identical(a, b)) {
return true;
}
for (int index = 0; index < a.length; index += 1) {
if (a[index] != b[index]) {
return false;
}
}
return true;
}
/// Compares two maps for element-by-element equality.
///
/// Returns true if the maps are both null, or if they are both non-null, have
/// the same length, and contain the same keys associated with the same values.
/// Returns false otherwise.
///
/// If the elements are maps, lists, sets, or other collections/composite
/// objects, then the contents of those elements are not compared element by
/// element unless their equality operators ([Object.==]) do so. For checking
/// deep equality, consider using the [DeepCollectionEquality] class.
///
/// See also:
///
/// * [setEquals], which does something similar for sets.
/// * [listEquals], which does something similar for lists.
bool mapEquals<T, U>(Map<T, U>? a, Map<T, U>? b) {
if (a == null) {
return b == null;
}
if (b == null || a.length != b.length) {
return false;
}
if (identical(a, b)) {
return true;
}
for (final T key in a.keys) {
if (!b.containsKey(key) || b[key] != a[key]) {
return false;
}
}
return true;
}
/// Returns the position of `value` in the `sortedList`, if it exists.
///
/// Returns `-1` if the `value` is not in the list. Requires the list items
/// to implement [Comparable] and the `sortedList` to already be ordered.
int binarySearch<T extends Comparable<Object>>(List<T> sortedList, T value) {
int min = 0;
int max = sortedList.length;
while (min < max) {
final int mid = min + ((max - min) >> 1);
final T element = sortedList[mid];
final int comp = element.compareTo(value);
if (comp == 0) {
return mid;
}
if (comp < 0) {
min = mid + 1;
} else {
max = mid;
}
}
return -1;
}
/// Limit below which merge sort defaults to insertion sort.
const int _kMergeSortLimit = 32;
/// Sorts a list between `start` (inclusive) and `end` (exclusive) using the
/// merge sort algorithm.
///
/// If `compare` is omitted, this defaults to calling [Comparable.compareTo] on
/// the objects. If any object is not [Comparable], this throws a [TypeError]
/// (The stack trace may call it `_CastError` or `_TypeError`, but to catch it,
/// use [TypeError]).
///
/// Merge-sorting works by splitting the job into two parts, sorting each
/// recursively, and then merging the two sorted parts.
///
/// This takes on the order of `n * log(n)` comparisons and moves to sort `n`
/// elements, but requires extra space of about the same size as the list being
/// sorted.
///
/// This merge sort is stable: Equal elements end up in the same order as they
/// started in.
///
/// For small lists (less than 32 elements), [mergeSort] automatically uses an
/// insertion sort instead, as that is more efficient for small lists. The
/// insertion sort is also stable.
void mergeSort<T>(
List<T> list, {
int start = 0,
int? end,
int Function(T, T)? compare,
}) {
end ??= list.length;
compare ??= _defaultCompare<T>();
final int length = end - start;
if (length < 2) {
return;
}
if (length < _kMergeSortLimit) {
_insertionSort<T>(list, compare: compare, start: start, end: end);
return;
}
// Special case the first split instead of directly calling _mergeSort,
// because the _mergeSort requires its target to be different from its source,
// and it requires extra space of the same size as the list to sort. This
// split allows us to have only half as much extra space, and it ends up in
// the original place.
final int middle = start + ((end - start) >> 1);
final int firstLength = middle - start;
final int secondLength = end - middle;
// secondLength is always the same as firstLength, or one greater.
final List<T> scratchSpace = List<T>.filled(secondLength, list[start]);
_mergeSort<T>(list, compare, middle, end, scratchSpace, 0);
final int firstTarget = end - firstLength;
_mergeSort<T>(list, compare, start, middle, list, firstTarget);
_merge<T>(compare, list, firstTarget, end, scratchSpace, 0, secondLength, list, start);
}
/// Returns a [Comparator] that asserts that its first argument is comparable.
Comparator<T> _defaultCompare<T>() {
// If we specify Comparable<T> here, it fails if the type is an int, because
// int isn't a subtype of comparable. Leaving out the type implicitly converts
// it to a num, which is a comparable.
return (T value1, T value2) => (value1 as Comparable<dynamic>).compareTo(value2);
}
/// Sort a list between `start` (inclusive) and `end` (exclusive) using
/// insertion sort.
///
/// If `compare` is omitted, this defaults to calling [Comparable.compareTo] on
/// the objects. If any object is not [Comparable], this throws a [TypeError]
/// (The stack trace may call it `_CastError` or `_TypeError`, but to catch it,
/// use [TypeError]).
///
/// Insertion sort is a simple sorting algorithm. For `n` elements it does on
/// the order of `n * log(n)` comparisons but up to `n` squared moves. The
/// sorting is performed in-place, without using extra memory.
///
/// For short lists the many moves have less impact than the simple algorithm,
/// and it is often the favored sorting algorithm for short lists.
///
/// This insertion sort is stable: Equal elements end up in the same order as
/// they started in.
void _insertionSort<T>(
List<T> list, {
int Function(T, T)? compare,
int start = 0,
int? end,
}) {
// If the same method could have both positional and named optional
// parameters, this should be (list, [start, end], {compare}).
compare ??= _defaultCompare<T>();
end ??= list.length;
for (int pos = start + 1; pos < end; pos++) {
int min = start;
int max = pos;
final T element = list[pos];
while (min < max) {
final int mid = min + ((max - min) >> 1);
final int comparison = compare(element, list[mid]);
if (comparison < 0) {
max = mid;
} else {
min = mid + 1;
}
}
list.setRange(min + 1, pos + 1, list, min);
list[min] = element;
}
}
/// Performs an insertion sort into a potentially different list than the one
/// containing the original values.
///
/// It will work in-place as well.
void _movingInsertionSort<T>(
List<T> list,
int Function(T, T) compare,
int start,
int end,
List<T> target,
int targetOffset,
) {
final int length = end - start;
if (length == 0) {
return;
}
target[targetOffset] = list[start];
for (int i = 1; i < length; i++) {
final T element = list[start + i];
int min = targetOffset;
int max = targetOffset + i;
while (min < max) {
final int mid = min + ((max - min) >> 1);
if (compare(element, target[mid]) < 0) {
max = mid;
} else {
min = mid + 1;
}
}
target.setRange(min + 1, targetOffset + i + 1, target, min);
target[min] = element;
}
}
/// Sorts `list` from `start` to `end` into `target` at `targetOffset`.
///
/// The `target` list must be able to contain the range from `start` to `end`
/// after `targetOffset`.
///
/// Allows target to be the same list as `list`, as long as it's not overlapping
/// the `start..end` range.
void _mergeSort<T>(
List<T> list,
int Function(T, T) compare,
int start,
int end,
List<T> target,
int targetOffset,
) {
final int length = end - start;
if (length < _kMergeSortLimit) {
_movingInsertionSort<T>(list, compare, start, end, target, targetOffset);
return;
}
final int middle = start + (length >> 1);
final int firstLength = middle - start;
final int secondLength = end - middle;
// Here secondLength >= firstLength (differs by at most one).
final int targetMiddle = targetOffset + firstLength;
// Sort the second half into the end of the target area.
_mergeSort<T>(list, compare, middle, end, target, targetMiddle);
// Sort the first half into the end of the source area.
_mergeSort<T>(list, compare, start, middle, list, middle);
// Merge the two parts into the target area.
_merge<T>(
compare,
list,
middle,
middle + firstLength,
target,
targetMiddle,
targetMiddle + secondLength,
target,
targetOffset,
);
}
/// Merges two lists into a target list.
///
/// One of the input lists may be positioned at the end of the target list.
///
/// For equal object, elements from `firstList` are always preferred. This
/// allows the merge to be stable if the first list contains elements that
/// started out earlier than the ones in `secondList`.
void _merge<T>(
int Function(T, T) compare,
List<T> firstList,
int firstStart,
int firstEnd,
List<T> secondList,
int secondStart,
int secondEnd,
List<T> target,
int targetOffset,
) {
// No empty lists reaches here.
assert(firstStart < firstEnd);
assert(secondStart < secondEnd);
int cursor1 = firstStart;
int cursor2 = secondStart;
T firstElement = firstList[cursor1++];
T secondElement = secondList[cursor2++];
while (true) {
if (compare(firstElement, secondElement) <= 0) {
target[targetOffset++] = firstElement;
if (cursor1 == firstEnd) {
// Flushing second list after loop.
break;
}
firstElement = firstList[cursor1++];
} else {
target[targetOffset++] = secondElement;
if (cursor2 != secondEnd) {
secondElement = secondList[cursor2++];
continue;
}
// Second list empties first. Flushing first list here.
target[targetOffset++] = firstElement;
target.setRange(targetOffset, targetOffset + (firstEnd - cursor1), firstList, cursor1);
return;
}
}
// First list empties first. Reached by break above.
target[targetOffset++] = secondElement;
target.setRange(targetOffset, targetOffset + (secondEnd - cursor2), secondList, cursor2);
}
| flutter/packages/flutter/lib/src/foundation/collections.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/collections.dart",
"repo_id": "flutter",
"token_count": 3880
} | 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.
/// Service extension constants for the foundation library.
///
/// These constants will be used when registering service extensions in the
/// framework, and they will also be used by tools and services that call these
/// service extensions.
///
/// The String value for each of these extension names should be accessed by
/// calling the `.name` property on the enum value.
enum FoundationServiceExtensions {
/// Name of service extension that, when called, will cause the entire
/// application to redraw.
///
/// See also:
///
/// * [BindingBase.initServiceExtensions], where the service extension is
/// registered.
reassemble,
/// Name of service extension that, when called, will terminate the Flutter
/// application.
///
/// See also:
///
/// * [BindingBase.initServiceExtensions], where the service extension is
/// registered.
exit,
/// Name of service extension that, when called, will get or set the value of
/// [connectedVmServiceUri].
///
/// See also:
///
/// * [connectedVmServiceUri], which stores the uri for the connected vm service
/// protocol.
/// * [BindingBase.initServiceExtensions], where the service extension is
/// registered.
connectedVmServiceUri,
/// Name of service extension that, when called, will get or set the value of
/// [activeDevToolsServerAddress].
///
/// See also:
///
/// * [activeDevToolsServerAddress], which stores the address for the active
/// DevTools server used for debugging this application.
/// * [BindingBase.initServiceExtensions], where the service extension is
/// registered.
activeDevToolsServerAddress,
/// Name of service extension that, when called, will change the value of
/// [defaultTargetPlatform], which controls which [TargetPlatform] that the
/// framework will execute for.
///
/// See also:
///
/// * [debugDefaultTargetPlatformOverride], which is the flag that this service
/// extension exposes.
/// * [BindingBase.initServiceExtensions], where the service extension is
/// registered.
platformOverride,
/// Name of service extension that, when called, will override the platform
/// [Brightness].
///
/// See also:
///
/// * [debugBrightnessOverride], which is the flag that this service
/// extension exposes.
/// * [BindingBase.initServiceExtensions], where the service extension is
/// registered.
brightnessOverride,
}
| flutter/packages/flutter/lib/src/foundation/service_extensions.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/service_extensions.dart",
"repo_id": "flutter",
"token_count": 677
} | 625 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:vector_math/vector_math_64.dart';
import 'events.dart';
export 'dart:ui' show Offset;
export 'package:vector_math/vector_math_64.dart' show Matrix4;
export 'events.dart' show PointerEvent;
/// An object that can hit-test pointers.
abstract interface class HitTestable {
/// Deprecated. Use [hitTestInView] instead.
@Deprecated(
'Use hitTestInView and specify the view to hit test. '
'This feature was deprecated after v3.11.0-20.0.pre.',
)
void hitTest(HitTestResult result, Offset position);
/// Fills the provided [HitTestResult] with [HitTestEntry]s for objects that
/// are hit at the given `position` in the view identified by `viewId`.
void hitTestInView(HitTestResult result, Offset position, int viewId);
}
/// An object that can dispatch events.
abstract interface class HitTestDispatcher {
/// Override this method to dispatch events.
void dispatchEvent(PointerEvent event, HitTestResult result);
}
/// An object that can handle events.
abstract interface class HitTestTarget {
/// Override this method to receive events.
void handleEvent(PointerEvent event, HitTestEntry<HitTestTarget> entry);
}
/// Data collected during a hit test about a specific [HitTestTarget].
///
/// Subclass this object to pass additional information from the hit test phase
/// to the event propagation phase.
@optionalTypeArgs
class HitTestEntry<T extends HitTestTarget> {
/// Creates a hit test entry.
HitTestEntry(this.target);
/// The [HitTestTarget] encountered during the hit test.
final T target;
@override
String toString() => '${describeIdentity(this)}($target)';
/// Returns a matrix describing how [PointerEvent]s delivered to this
/// [HitTestEntry] should be transformed from the global coordinate space of
/// the screen to the local coordinate space of [target].
///
/// See also:
///
/// * [BoxHitTestResult.addWithPaintTransform], which is used during hit testing
/// to build up this transform.
Matrix4? get transform => _transform;
Matrix4? _transform;
}
// A type of data that can be applied to a matrix by left-multiplication.
@immutable
abstract class _TransformPart {
const _TransformPart();
// Apply this transform part to `rhs` from the left.
//
// This should work as if this transform part is first converted to a matrix
// and then left-multiplied to `rhs`.
//
// For example, if this transform part is a vector `v1`, whose corresponding
// matrix is `m1 = Matrix4.translation(v1)`, then the result of
// `_VectorTransformPart(v1).multiply(rhs)` should equal to `m1 * rhs`.
Matrix4 multiply(Matrix4 rhs);
}
class _MatrixTransformPart extends _TransformPart {
const _MatrixTransformPart(this.matrix);
final Matrix4 matrix;
@override
Matrix4 multiply(Matrix4 rhs) {
return matrix.multiplied(rhs);
}
}
class _OffsetTransformPart extends _TransformPart {
const _OffsetTransformPart(this.offset);
final Offset offset;
@override
Matrix4 multiply(Matrix4 rhs) {
return rhs.clone()..leftTranslate(offset.dx, offset.dy);
}
}
/// The result of performing a hit test.
class HitTestResult {
/// Creates an empty hit test result.
HitTestResult()
: _path = <HitTestEntry>[],
_transforms = <Matrix4>[Matrix4.identity()],
_localTransforms = <_TransformPart>[];
/// Wraps `result` (usually a subtype of [HitTestResult]) to create a
/// generic [HitTestResult].
///
/// The [HitTestEntry]s added to the returned [HitTestResult] are also
/// added to the wrapped `result` (both share the same underlying data
/// structure to store [HitTestEntry]s).
HitTestResult.wrap(HitTestResult result)
: _path = result._path,
_transforms = result._transforms,
_localTransforms = result._localTransforms;
/// An unmodifiable list of [HitTestEntry] objects recorded during the hit test.
///
/// The first entry in the path is the most specific, typically the one at
/// the leaf of tree being hit tested. Event propagation starts with the most
/// specific (i.e., first) entry and proceeds in order through the path.
Iterable<HitTestEntry> get path => _path;
final List<HitTestEntry> _path;
// A stack of transform parts.
//
// The transform part stack leading from global to the current object is stored
// in 2 parts:
//
// * `_transforms` are globalized matrices, meaning they have been multiplied
// by the ancestors and are thus relative to the global coordinate space.
// * `_localTransforms` are local transform parts, which are relative to the
// parent's coordinate space.
//
// When new transform parts are added they're appended to `_localTransforms`,
// and are converted to global ones and moved to `_transforms` only when used.
final List<Matrix4> _transforms;
final List<_TransformPart> _localTransforms;
// Globalize all transform parts in `_localTransforms` and move them to
// _transforms.
void _globalizeTransforms() {
if (_localTransforms.isEmpty) {
return;
}
Matrix4 last = _transforms.last;
for (final _TransformPart part in _localTransforms) {
last = part.multiply(last);
_transforms.add(last);
}
_localTransforms.clear();
}
Matrix4 get _lastTransform {
_globalizeTransforms();
assert(_localTransforms.isEmpty);
return _transforms.last;
}
/// Add a [HitTestEntry] to the path.
///
/// The new entry is added at the end of the path, which means entries should
/// be added in order from most specific to least specific, typically during an
/// upward walk of the tree being hit tested.
void add(HitTestEntry entry) {
assert(entry._transform == null);
entry._transform = _lastTransform;
_path.add(entry);
}
/// Pushes a new transform matrix that is to be applied to all future
/// [HitTestEntry]s added via [add] until it is removed via [popTransform].
///
/// This method is only to be used by subclasses, which must provide
/// coordinate space specific public wrappers around this function for their
/// users (see [BoxHitTestResult.addWithPaintTransform] for such an example).
///
/// The provided `transform` matrix should describe how to transform
/// [PointerEvent]s from the coordinate space of the method caller to the
/// coordinate space of its children. In most cases `transform` is derived
/// from running the inverted result of [RenderObject.applyPaintTransform]
/// through [PointerEvent.removePerspectiveTransform] to remove
/// the perspective component.
///
/// If the provided `transform` is a translation matrix, it is much faster
/// to use [pushOffset] with the translation offset instead.
///
/// [HitTestable]s need to call this method indirectly through a convenience
/// method defined on a subclass before hit testing a child that does not
/// have the same origin as the parent. After hit testing the child,
/// [popTransform] has to be called to remove the child-specific `transform`.
///
/// See also:
///
/// * [pushOffset], which is similar to [pushTransform] but is limited to
/// translations, and is faster in such cases.
/// * [BoxHitTestResult.addWithPaintTransform], which is a public wrapper
/// around this function for hit testing on [RenderBox]s.
@protected
void pushTransform(Matrix4 transform) {
assert(
_debugVectorMoreOrLessEquals(transform.getRow(2), Vector4(0, 0, 1, 0)) &&
_debugVectorMoreOrLessEquals(transform.getColumn(2), Vector4(0, 0, 1, 0)),
'The third row and third column of a transform matrix for pointer '
'events must be Vector4(0, 0, 1, 0) to ensure that a transformed '
'point is directly under the pointing device. Did you forget to run the paint '
'matrix through PointerEvent.removePerspectiveTransform? '
'The provided matrix is:\n$transform',
);
_localTransforms.add(_MatrixTransformPart(transform));
}
/// Pushes a new translation offset that is to be applied to all future
/// [HitTestEntry]s added via [add] until it is removed via [popTransform].
///
/// This method is only to be used by subclasses, which must provide
/// coordinate space specific public wrappers around this function for their
/// users (see [BoxHitTestResult.addWithPaintOffset] for such an example).
///
/// The provided `offset` should describe how to transform [PointerEvent]s from
/// the coordinate space of the method caller to the coordinate space of its
/// children. Usually `offset` is the inverse of the offset of the child
/// relative to the parent.
///
/// [HitTestable]s need to call this method indirectly through a convenience
/// method defined on a subclass before hit testing a child that does not
/// have the same origin as the parent. After hit testing the child,
/// [popTransform] has to be called to remove the child-specific `transform`.
///
/// See also:
///
/// * [pushTransform], which is similar to [pushOffset] but allows general
/// transform besides translation.
/// * [BoxHitTestResult.addWithPaintOffset], which is a public wrapper
/// around this function for hit testing on [RenderBox]s.
/// * [SliverHitTestResult.addWithAxisOffset], which is a public wrapper
/// around this function for hit testing on [RenderSliver]s.
@protected
void pushOffset(Offset offset) {
_localTransforms.add(_OffsetTransformPart(offset));
}
/// Removes the last transform added via [pushTransform] or [pushOffset].
///
/// This method is only to be used by subclasses, which must provide
/// coordinate space specific public wrappers around this function for their
/// users (see [BoxHitTestResult.addWithPaintTransform] for such an example).
///
/// This method must be called after hit testing is done on a child that
/// required a call to [pushTransform] or [pushOffset].
///
/// See also:
///
/// * [pushTransform] and [pushOffset], which describes the use case of this
/// function pair in more details.
@protected
void popTransform() {
if (_localTransforms.isNotEmpty) {
_localTransforms.removeLast();
} else {
_transforms.removeLast();
}
assert(_transforms.isNotEmpty);
}
bool _debugVectorMoreOrLessEquals(Vector4 a, Vector4 b, { double epsilon = precisionErrorTolerance }) {
bool result = true;
assert(() {
final Vector4 difference = a - b;
result = difference.storage.every((double component) => component.abs() < epsilon);
return true;
}());
return result;
}
@override
String toString() => 'HitTestResult(${_path.isEmpty ? "<empty path>" : _path.join(", ")})';
}
| flutter/packages/flutter/lib/src/gestures/hit_test.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/gestures/hit_test.dart",
"repo_id": "flutter",
"token_count": 3190
} | 626 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'action_icons_theme.dart';
import 'button_style.dart';
import 'debug.dart';
import 'icon_button.dart';
import 'icons.dart';
import 'material_localizations.dart';
import 'scaffold.dart';
import 'theme.dart';
abstract class _ActionButton extends StatelessWidget {
/// Creates a Material Design icon button.
const _ActionButton({
super.key,
this.color,
required this.icon,
required this.onPressed,
this.style,
});
/// The icon to display inside the button.
final Widget icon;
/// The callback that is called when the button is tapped
/// or otherwise activated.
///
/// If this is set to null, the button will do a default action
/// when it is tapped or activated.
final VoidCallback? onPressed;
/// The color to use for the icon.
///
/// Defaults to the [IconThemeData.color] specified in the ambient [IconTheme],
/// which usually matches the ambient [Theme]'s [ThemeData.iconTheme].
final Color? color;
/// Customizes this icon button's appearance.
///
/// The [style] is only used for Material 3 [IconButton]s. If [ThemeData.useMaterial3]
/// is set to true, [style] is preferred for icon button customization, and any
/// parameters defined in [style] will override the same parameters in [IconButton].
///
/// Null by default.
final ButtonStyle? style;
/// This returns the appropriate tooltip text for this action button.
String _getTooltip(BuildContext context);
/// This is the default function that is called when [onPressed] is set
/// to null.
void _onPressedCallback(BuildContext context);
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
return IconButton(
icon: icon,
style: style,
color: color,
tooltip: _getTooltip(context),
onPressed: () {
if (onPressed != null) {
onPressed!();
} else {
_onPressedCallback(context);
}
},
);
}
}
typedef _ActionIconBuilderCallback = WidgetBuilder? Function(ActionIconThemeData? actionIconTheme);
typedef _ActionIconDataCallback = IconData Function(BuildContext context);
typedef _AndroidSemanticsLabelCallback = String Function(MaterialLocalizations materialLocalization);
class _ActionIcon extends StatelessWidget {
const _ActionIcon({
required this.iconBuilderCallback,
required this.getIcon,
required this.getAndroidSemanticsLabel,
});
final _ActionIconBuilderCallback iconBuilderCallback;
final _ActionIconDataCallback getIcon;
final _AndroidSemanticsLabelCallback getAndroidSemanticsLabel;
@override
Widget build(BuildContext context) {
final ActionIconThemeData? actionIconTheme = ActionIconTheme.of(context);
final WidgetBuilder? iconBuilder = iconBuilderCallback(actionIconTheme);
if (iconBuilder != null) {
return iconBuilder(context);
}
final IconData data = getIcon(context);
final String? semanticsLabel;
// This can't use the platform from Theme because it is the Android OS that
// expects the duplicated tooltip and label.
switch (defaultTargetPlatform) {
case TargetPlatform.android:
semanticsLabel = getAndroidSemanticsLabel(MaterialLocalizations.of(context));
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
case TargetPlatform.iOS:
case TargetPlatform.macOS:
semanticsLabel = null;
}
return Icon(data, semanticLabel: semanticsLabel);
}
}
/// A "back" icon that's appropriate for the current [TargetPlatform].
///
/// The current platform is determined by querying for the ambient [Theme].
///
/// See also:
///
/// * [BackButton], an [IconButton] with a [BackButtonIcon] that calls
/// [Navigator.maybePop] to return to the previous route.
/// * [IconButton], which is a more general widget for creating buttons
/// with icons.
/// * [Icon], a Material Design icon.
/// * [ThemeData.platform], which specifies the current platform.
class BackButtonIcon extends StatelessWidget {
/// Creates an icon that shows the appropriate "back" image for
/// the current platform (as obtained from the [Theme]).
const BackButtonIcon({ super.key });
@override
Widget build(BuildContext context) {
return _ActionIcon(
iconBuilderCallback: (ActionIconThemeData? actionIconTheme) {
return actionIconTheme?.backButtonIconBuilder;
},
getIcon: (BuildContext context) {
if (kIsWeb) {
// Always use 'Icons.arrow_back' as a back_button icon in web.
return Icons.arrow_back;
}
switch (Theme.of(context).platform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return Icons.arrow_back;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return Icons.arrow_back_ios_new_rounded;
}
},
getAndroidSemanticsLabel: (MaterialLocalizations materialLocalization) {
return materialLocalization.backButtonTooltip;
},
);
}
}
/// A Material Design back icon button.
///
/// A [BackButton] is an [IconButton] with a "back" icon appropriate for the
/// current [TargetPlatform]. When pressed, the back button calls
/// [Navigator.maybePop] to return to the previous route unless a custom
/// [onPressed] callback is provided.
///
/// The [onPressed] callback can, for instance, be used to pop the platform's navigation stack
/// via [SystemNavigator] instead of Flutter's [Navigator] in add-to-app
/// situations.
///
/// In Material Design 3, both [style]'s [ButtonStyle.iconColor] and [color] are
/// used to override the default icon color of [BackButton]. If both exist, the [ButtonStyle.iconColor]
/// will override [color] for states where [ButtonStyle.foregroundColor] resolves to non-null.
///
/// When deciding to display a [BackButton], consider using
/// `ModalRoute.of(context)?.canPop` to check whether the current route can be
/// popped. If that value is false (e.g., because the current route is the
/// initial route), the [BackButton] will not have any effect when pressed,
/// which could frustrate the user.
///
/// Requires one of its ancestors to be a [Material] widget.
///
/// See also:
///
/// * [AppBar], which automatically uses a [BackButton] in its
/// [AppBar.leading] slot when the [Scaffold] has no [Drawer] and the
/// current [Route] is not the [Navigator]'s first route.
/// * [BackButtonIcon], which is useful if you need to create a back button
/// that responds differently to being pressed.
/// * [IconButton], which is a more general widget for creating buttons with
/// icons.
/// * [CloseButton], an alternative which may be more appropriate for leaf
/// node pages in the navigation tree.
class BackButton extends _ActionButton {
/// Creates an [IconButton] with the appropriate "back" icon for the current
/// target platform.
const BackButton({
super.key,
super.color,
super.style,
super.onPressed,
}) : super(icon: const BackButtonIcon());
@override
void _onPressedCallback(BuildContext context) => Navigator.maybePop(context);
@override
String _getTooltip(BuildContext context) {
return MaterialLocalizations.of(context).backButtonTooltip;
}
}
/// A "close" icon that's appropriate for the current [TargetPlatform].
///
/// The current platform is determined by querying for the ambient [Theme].
///
/// See also:
///
/// * [CloseButton], an [IconButton] with a [CloseButtonIcon] that calls
/// [Navigator.maybePop] to return to the previous route.
/// * [IconButton], which is a more general widget for creating buttons
/// with icons.
/// * [Icon], a Material Design icon.
/// * [ThemeData.platform], which specifies the current platform.
class CloseButtonIcon extends StatelessWidget {
/// Creates an icon that shows the appropriate "close" image for
/// the current platform (as obtained from the [Theme]).
const CloseButtonIcon({ super.key });
@override
Widget build(BuildContext context) {
return _ActionIcon(
iconBuilderCallback: (ActionIconThemeData? actionIconTheme) {
return actionIconTheme?.closeButtonIconBuilder;
},
getIcon: (BuildContext context) => Icons.close,
getAndroidSemanticsLabel: (MaterialLocalizations materialLocalization) {
return materialLocalization.closeButtonTooltip;
},
);
}
}
/// A Material Design close icon button.
///
/// A [CloseButton] is an [IconButton] with a "close" icon. When pressed, the
/// close button calls [Navigator.maybePop] to return to the previous route.
///
/// The [onPressed] callback can, for instance, be used to pop the platform's navigation stack
/// via [SystemNavigator] instead of Flutter's [Navigator] in add-to-app
/// situations.
///
/// In Material Design 3, both [style]'s [ButtonStyle.iconColor] and [color] are
/// used to override the default icon color of [CloseButton]. If both exist, the [ButtonStyle.iconColor]
/// will override [color] for states where [ButtonStyle.foregroundColor] resolves to non-null.
///
/// Use a [CloseButton] instead of a [BackButton] on fullscreen dialogs or
/// pages that may solicit additional actions to close.
///
/// See also:
///
/// * [AppBar], which automatically uses a [CloseButton] in its
/// [AppBar.leading] slot when appropriate.
/// * [BackButton], which is more appropriate for middle nodes in the
/// navigation tree or where pages can be popped instantaneously with
/// no user data consequence.
/// * [IconButton], to create other Material Design icon buttons.
class CloseButton extends _ActionButton {
/// Creates a Material Design close icon button.
const CloseButton({ super.key, super.color, super.onPressed, super.style })
: super(icon: const CloseButtonIcon());
@override
void _onPressedCallback(BuildContext context) => Navigator.maybePop(context);
@override
String _getTooltip(BuildContext context) {
return MaterialLocalizations.of(context).closeButtonTooltip;
}
}
/// A "drawer" icon that's appropriate for the current [TargetPlatform].
///
/// The current platform is determined by querying for the ambient [Theme].
///
/// See also:
///
/// * [DrawerButton], an [IconButton] with a [DrawerButtonIcon] that calls
/// [ScaffoldState.openDrawer] to open the [Scaffold.drawer].
/// * [EndDrawerButton], an [IconButton] with an [EndDrawerButtonIcon] that
/// calls [ScaffoldState.openEndDrawer] to open the [Scaffold.endDrawer].
/// * [IconButton], which is a more general widget for creating buttons
/// with icons.
/// * [Icon], a Material Design icon.
/// * [ThemeData.platform], which specifies the current platform.
class DrawerButtonIcon extends StatelessWidget {
/// Creates an icon that shows the appropriate "close" image for
/// the current platform (as obtained from the [Theme]).
const DrawerButtonIcon({ super.key });
@override
Widget build(BuildContext context) {
return _ActionIcon(
iconBuilderCallback: (ActionIconThemeData? actionIconTheme) {
return actionIconTheme?.drawerButtonIconBuilder;
},
getIcon: (BuildContext context) => Icons.menu,
getAndroidSemanticsLabel: (MaterialLocalizations materialLocalization) {
return materialLocalization.openAppDrawerTooltip;
},
);
}
}
/// A Material Design drawer icon button.
///
/// A [DrawerButton] is an [IconButton] with a "drawer" icon. When pressed, the
/// close button calls [ScaffoldState.openDrawer] to the [Scaffold.drawer].
///
/// The default behaviour on press can be overridden with [onPressed].
///
/// See also:
///
/// * [EndDrawerButton], an [IconButton] with an [EndDrawerButtonIcon] that
/// calls [ScaffoldState.openEndDrawer] to open the [Scaffold.endDrawer].
/// * [IconButton], which is a more general widget for creating buttons
/// with icons.
/// * [Icon], a Material Design icon.
/// * [ThemeData.platform], which specifies the current platform.
class DrawerButton extends _ActionButton {
/// Creates a Material Design drawer icon button.
const DrawerButton({
super.key,
super.color,
super.style,
super.onPressed,
}) : super(icon: const DrawerButtonIcon());
@override
void _onPressedCallback(BuildContext context) => Scaffold.of(context).openDrawer();
@override
String _getTooltip(BuildContext context) {
return MaterialLocalizations.of(context).openAppDrawerTooltip;
}
}
/// A "end drawer" icon that's appropriate for the current [TargetPlatform].
///
/// The current platform is determined by querying for the ambient [Theme].
///
/// See also:
///
/// * [DrawerButton], an [IconButton] with a [DrawerButtonIcon] that calls
/// [ScaffoldState.openDrawer] to open the [Scaffold.drawer].
/// * [EndDrawerButton], an [IconButton] with an [EndDrawerButtonIcon] that
/// calls [ScaffoldState.openEndDrawer] to open the [Scaffold.endDrawer]
/// * [IconButton], which is a more general widget for creating buttons
/// with icons.
/// * [Icon], a Material Design icon.
/// * [ThemeData.platform], which specifies the current platform.
class EndDrawerButtonIcon extends StatelessWidget {
/// Creates an icon that shows the appropriate "end drawer" image for
/// the current platform (as obtained from the [Theme]).
const EndDrawerButtonIcon({ super.key });
@override
Widget build(BuildContext context) {
return _ActionIcon(
iconBuilderCallback: (ActionIconThemeData? actionIconTheme) {
return actionIconTheme?.endDrawerButtonIconBuilder;
},
getIcon: (BuildContext context) => Icons.menu,
getAndroidSemanticsLabel: (MaterialLocalizations materialLocalization) {
return materialLocalization.openAppDrawerTooltip;
},
);
}
}
/// A Material Design end drawer icon button.
///
/// A [EndDrawerButton] is an [IconButton] with a "drawer" icon. When pressed, the
/// end drawer button calls [ScaffoldState.openEndDrawer] to open the [Scaffold.endDrawer].
///
/// The default behaviour on press can be overridden with [onPressed].
///
/// See also:
///
/// * [DrawerButton], an [IconButton] with a [DrawerButtonIcon] that calls
/// [ScaffoldState.openDrawer] to open a drawer.
/// * [IconButton], which is a more general widget for creating buttons
/// with icons.
/// * [Icon], a Material Design icon.
/// * [ThemeData.platform], which specifies the current platform.
class EndDrawerButton extends _ActionButton {
/// Creates a Material Design end drawer icon button.
const EndDrawerButton({
super.key,
super.color,
super.style,
super.onPressed,
}) : super(icon: const EndDrawerButtonIcon());
@override
void _onPressedCallback(BuildContext context) => Scaffold.of(context).openEndDrawer();
@override
String _getTooltip(BuildContext context) {
return MaterialLocalizations.of(context).openAppDrawerTooltip;
}
}
| flutter/packages/flutter/lib/src/material/action_buttons.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/action_buttons.dart",
"repo_id": "flutter",
"token_count": 4672
} | 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.
// 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 _$menu_home = _AnimatedIconData(
Size(48.0, 48.0),
<_PathFrames>[
_PathFrames(
opacities: <double>[
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.853658536585,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(6.0, 12.046875),
Offset(6.1618805351617105, 11.806612807600084),
Offset(6.781939829118144, 10.945667339250278),
Offset(8.288913455339518, 9.166289848732603),
Offset(11.935042610511557, 6.074766376544677),
Offset(23.256788788206386, 2.4054443351966768),
Offset(36.24002084790047, 6.193846936842682),
Offset(43.02277578355333, 13.752502805353782),
Offset(45.18366429152893, 19.742117374864932),
Offset(45.60696992064962, 24.126681150009468),
Offset(45.345679612709475, 27.35248551632729),
Offset(44.82758462670622, 29.752296574674826),
Offset(44.24395862249675, 31.553763072552943),
Offset(43.684466559586255, 32.91061016598502),
Offset(43.191063930200144, 33.928759363213324),
Offset(42.78156545517243, 34.68316415294171),
Offset(42.461367454866235, 35.22742664024267),
Offset(42.229341109216534, 35.60035861469174),
Offset(42.08077400509552, 35.830587840098524),
Offset(42.00921658628339, 35.93923428088923),
Offset(42.0, 35.953125),
],
),
_PathCubicTo(
<Offset>[
Offset(6.0, 12.046875),
Offset(6.1618805351617105, 11.806612807600084),
Offset(6.781939829118144, 10.945667339250278),
Offset(8.288913455339518, 9.166289848732603),
Offset(11.935042610511557, 6.074766376544677),
Offset(23.256788788206386, 2.4054443351966768),
Offset(36.24002084790047, 6.193846936842682),
Offset(43.02277578355333, 13.752502805353782),
Offset(45.18366429152893, 19.742117374864932),
Offset(45.60696992064962, 24.126681150009468),
Offset(45.345679612709475, 27.35248551632729),
Offset(44.82758462670622, 29.752296574674826),
Offset(44.24395862249675, 31.553763072552943),
Offset(43.684466559586255, 32.91061016598502),
Offset(43.191063930200144, 33.928759363213324),
Offset(42.78156545517243, 34.68316415294171),
Offset(42.461367454866235, 35.22742664024267),
Offset(42.229341109216534, 35.60035861469174),
Offset(42.08077400509552, 35.830587840098524),
Offset(42.00921658628339, 35.93923428088923),
Offset(42.0, 35.953125),
],
<Offset>[
Offset(6.0, 16.0),
Offset(6.108878658535886, 15.759382477932412),
Offset(6.534966570751962, 14.8910699138017),
Offset(7.618227825115078, 13.06210530265691),
Offset(10.424159957469506, 9.727769370570497),
Offset(20.040805554226083, 4.704280802712924),
Offset(32.287403394427514, 6.130502385964199),
Offset(39.5356887387035, 11.890401517221083),
Offset(42.39074647053927, 16.944474204118634),
Offset(43.43945637458355, 20.820764893773518),
Offset(43.696252373988955, 23.759911640985017),
Offset(43.59634590360605, 25.995802401597533),
Offset(43.34634769806003, 27.703893997641842),
Offset(43.050276896752194, 29.008687468496074),
Offset(42.76198609923806, 29.998989715943665),
Offset(42.5089105957515, 30.739453134971555),
Offset(42.30406998921387, 31.277432365193103),
Offset(42.152364969347445, 31.64798313410847),
Offset(42.05392318847743, 31.87755403057046),
Offset(42.00616671483272, 31.986110457391014),
Offset(42.0, 31.999999999999996),
],
<Offset>[
Offset(6.0, 16.0),
Offset(6.108878658535886, 15.759382477932412),
Offset(6.534966570751962, 14.8910699138017),
Offset(7.618227825115078, 13.06210530265691),
Offset(10.424159957469506, 9.727769370570497),
Offset(20.040805554226083, 4.704280802712924),
Offset(32.287403394427514, 6.130502385964199),
Offset(39.5356887387035, 11.890401517221083),
Offset(42.39074647053927, 16.944474204118634),
Offset(43.43945637458355, 20.820764893773518),
Offset(43.696252373988955, 23.759911640985017),
Offset(43.59634590360605, 25.995802401597533),
Offset(43.34634769806003, 27.703893997641842),
Offset(43.050276896752194, 29.008687468496074),
Offset(42.76198609923806, 29.998989715943665),
Offset(42.5089105957515, 30.739453134971555),
Offset(42.30406998921387, 31.277432365193103),
Offset(42.152364969347445, 31.64798313410847),
Offset(42.05392318847743, 31.87755403057046),
Offset(42.00616671483272, 31.986110457391014),
Offset(42.0, 31.999999999999996),
],
),
_PathCubicTo(
<Offset>[
Offset(6.0, 16.0),
Offset(6.108878658535886, 15.759382477932412),
Offset(6.534966570751962, 14.8910699138017),
Offset(7.618227825115078, 13.06210530265691),
Offset(10.424159957469506, 9.727769370570497),
Offset(20.040805554226083, 4.704280802712924),
Offset(32.287403394427514, 6.130502385964199),
Offset(39.5356887387035, 11.890401517221083),
Offset(42.39074647053927, 16.944474204118634),
Offset(43.43945637458355, 20.820764893773518),
Offset(43.696252373988955, 23.759911640985017),
Offset(43.59634590360605, 25.995802401597533),
Offset(43.34634769806003, 27.703893997641842),
Offset(43.050276896752194, 29.008687468496074),
Offset(42.76198609923806, 29.998989715943665),
Offset(42.5089105957515, 30.739453134971555),
Offset(42.30406998921387, 31.277432365193103),
Offset(42.152364969347445, 31.64798313410847),
Offset(42.05392318847743, 31.87755403057046),
Offset(42.00616671483272, 31.986110457391014),
Offset(42.0, 31.999999999999996),
],
<Offset>[
Offset(42.0, 16.0),
Offset(42.10564277096942, 16.24205569431935),
Offset(42.46464060935464, 17.140186069041555),
Offset(43.096325871919824, 19.169851120985427),
Offset(43.691033073024805, 23.4869536891827),
Offset(40.975664135876016, 33.99133760544266),
Offset(31.710542346111218, 42.12588030217638),
Offset(22.578054873653144, 43.64632464502351),
Offset(16.913395223901084, 42.37879301660944),
Offset(13.333404776292529, 40.559702483244706),
Offset(10.979690283915431, 38.78078262126988),
Offset(9.387007663408092, 37.208347927379336),
Offset(8.286670430885419, 35.8781847877691),
Offset(7.516561896694743, 34.78407475375168),
Offset(6.974676742284352, 33.906481109369096),
Offset(6.594641088228872, 33.222444423927385),
Offset(6.332580622754584, 32.709896242122134),
Offset(6.159190632336145, 32.348983237896554),
Offset(6.054753634514366, 32.12207688230202),
Offset(6.00617742890433, 32.01388478079939),
Offset(6.0, 32.0),
],
<Offset>[
Offset(42.0, 16.0),
Offset(42.10564277096942, 16.24205569431935),
Offset(42.46464060935464, 17.140186069041555),
Offset(43.096325871919824, 19.169851120985427),
Offset(43.691033073024805, 23.4869536891827),
Offset(40.975664135876016, 33.99133760544266),
Offset(31.710542346111218, 42.12588030217638),
Offset(22.578054873653144, 43.64632464502351),
Offset(16.913395223901084, 42.37879301660944),
Offset(13.333404776292529, 40.559702483244706),
Offset(10.979690283915431, 38.78078262126988),
Offset(9.387007663408092, 37.208347927379336),
Offset(8.286670430885419, 35.8781847877691),
Offset(7.516561896694743, 34.78407475375168),
Offset(6.974676742284352, 33.906481109369096),
Offset(6.594641088228872, 33.222444423927385),
Offset(6.332580622754584, 32.709896242122134),
Offset(6.159190632336145, 32.348983237896554),
Offset(6.054753634514366, 32.12207688230202),
Offset(6.00617742890433, 32.01388478079939),
Offset(6.0, 32.0),
],
),
_PathCubicTo(
<Offset>[
Offset(42.0, 16.0),
Offset(42.10564277096942, 16.24205569431935),
Offset(42.46464060935464, 17.140186069041555),
Offset(43.096325871919824, 19.169851120985427),
Offset(43.691033073024805, 23.4869536891827),
Offset(40.975664135876016, 33.99133760544266),
Offset(31.710542346111218, 42.12588030217638),
Offset(22.578054873653144, 43.64632464502351),
Offset(16.913395223901084, 42.37879301660944),
Offset(13.333404776292529, 40.559702483244706),
Offset(10.979690283915431, 38.78078262126988),
Offset(9.387007663408092, 37.208347927379336),
Offset(8.286670430885419, 35.8781847877691),
Offset(7.516561896694743, 34.78407475375168),
Offset(6.974676742284352, 33.906481109369096),
Offset(6.594641088228872, 33.222444423927385),
Offset(6.332580622754584, 32.709896242122134),
Offset(6.159190632336145, 32.348983237896554),
Offset(6.054753634514366, 32.12207688230202),
Offset(6.00617742890433, 32.01388478079939),
Offset(6.0, 32.0),
],
<Offset>[
Offset(42.0, 12.0546875),
Offset(42.15853990080349, 12.297097821754479),
Offset(42.711125778277406, 13.202580732779758),
Offset(43.765686036471884, 15.281734907088639),
Offset(45.19892979196993, 19.841170068662862),
Offset(44.185291671765455, 31.697044293000552),
Offset(35.65534830264055, 42.18909966619542),
Offset(26.058250442129758, 45.50474589108481),
Offset(19.700793444454007, 45.170907248283115),
Offset(15.496634698749768, 43.85908530814422),
Offset(12.625857785010018, 42.366256548241914),
Offset(10.615813108399369, 40.957418198928806),
Offset(9.18250742068886, 39.72044542577326),
Offset(8.14949822027419, 38.6782861415618),
Offset(7.402906593343346, 37.82848441346233),
Offset(6.866757104054109, 37.15836154660511),
Offset(6.489567223850322, 36.65208420437516),
Offset(6.236014645446598, 36.2935476997435),
Offset(6.081551386277482, 36.0672983720484),
Offset(6.009221272941055, 35.9591961066227),
Offset(6.0, 35.9453125),
],
<Offset>[
Offset(42.0, 12.0546875),
Offset(42.15853990080349, 12.297097821754479),
Offset(42.711125778277406, 13.202580732779758),
Offset(43.765686036471884, 15.281734907088639),
Offset(45.19892979196993, 19.841170068662862),
Offset(44.185291671765455, 31.697044293000552),
Offset(35.65534830264055, 42.18909966619542),
Offset(26.058250442129758, 45.50474589108481),
Offset(19.700793444454007, 45.170907248283115),
Offset(15.496634698749768, 43.85908530814422),
Offset(12.625857785010018, 42.366256548241914),
Offset(10.615813108399369, 40.957418198928806),
Offset(9.18250742068886, 39.72044542577326),
Offset(8.14949822027419, 38.6782861415618),
Offset(7.402906593343346, 37.82848441346233),
Offset(6.866757104054109, 37.15836154660511),
Offset(6.489567223850322, 36.65208420437516),
Offset(6.236014645446598, 36.2935476997435),
Offset(6.081551386277482, 36.0672983720484),
Offset(6.009221272941055, 35.9591961066227),
Offset(6.0, 35.9453125),
],
),
_PathCubicTo(
<Offset>[
Offset(42.0, 12.0546875),
Offset(42.15853990080349, 12.297097821754479),
Offset(42.711125778277406, 13.202580732779758),
Offset(43.765686036471884, 15.281734907088639),
Offset(45.19892979196993, 19.841170068662862),
Offset(44.185291671765455, 31.697044293000552),
Offset(35.65534830264055, 42.18909966619542),
Offset(26.058250442129758, 45.50474589108481),
Offset(19.700793444454007, 45.170907248283115),
Offset(15.496634698749768, 43.85908530814422),
Offset(12.625857785010018, 42.366256548241914),
Offset(10.615813108399369, 40.957418198928806),
Offset(9.18250742068886, 39.72044542577326),
Offset(8.14949822027419, 38.6782861415618),
Offset(7.402906593343346, 37.82848441346233),
Offset(6.866757104054109, 37.15836154660511),
Offset(6.489567223850322, 36.65208420437516),
Offset(6.236014645446598, 36.2935476997435),
Offset(6.081551386277482, 36.0672983720484),
Offset(6.009221272941055, 35.9591961066227),
Offset(6.0, 35.9453125),
],
<Offset>[
Offset(6.0, 12.046875),
Offset(6.1618805351617105, 11.806612807600084),
Offset(6.781939829118144, 10.945667339250278),
Offset(8.288913455339518, 9.166289848732603),
Offset(11.935042610511557, 6.074766376544677),
Offset(23.256788788206386, 2.4054443351966768),
Offset(36.24002084790047, 6.193846936842682),
Offset(43.02277578355333, 13.752502805353782),
Offset(45.18366429152893, 19.742117374864932),
Offset(45.60696992064962, 24.126681150009468),
Offset(45.345679612709475, 27.35248551632729),
Offset(44.82758462670622, 29.752296574674826),
Offset(44.24395862249675, 31.553763072552943),
Offset(43.684466559586255, 32.91061016598502),
Offset(43.191063930200144, 33.928759363213324),
Offset(42.78156545517243, 34.68316415294171),
Offset(42.461367454866235, 35.22742664024267),
Offset(42.229341109216534, 35.60035861469174),
Offset(42.08077400509552, 35.830587840098524),
Offset(42.00921658628339, 35.93923428088923),
Offset(42.0, 35.953125),
],
<Offset>[
Offset(6.0, 12.046875),
Offset(6.1618805351617105, 11.806612807600084),
Offset(6.781939829118144, 10.945667339250278),
Offset(8.288913455339518, 9.166289848732603),
Offset(11.935042610511557, 6.074766376544677),
Offset(23.256788788206386, 2.4054443351966768),
Offset(36.24002084790047, 6.193846936842682),
Offset(43.02277578355333, 13.752502805353782),
Offset(45.18366429152893, 19.742117374864932),
Offset(45.60696992064962, 24.126681150009468),
Offset(45.345679612709475, 27.35248551632729),
Offset(44.82758462670622, 29.752296574674826),
Offset(44.24395862249675, 31.553763072552943),
Offset(43.684466559586255, 32.91061016598502),
Offset(43.191063930200144, 33.928759363213324),
Offset(42.78156545517243, 34.68316415294171),
Offset(42.461367454866235, 35.22742664024267),
Offset(42.229341109216534, 35.60035861469174),
Offset(42.08077400509552, 35.830587840098524),
Offset(42.00921658628339, 35.93923428088923),
Offset(42.0, 35.953125),
],
),
_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(6.0, 26.0),
Offset(5.97480276509507, 25.758483620275058),
Offset(5.9102120831853355, 24.871534924524667),
Offset(5.921631764468266, 22.91713253788045),
Offset(6.602164313410562, 18.968567458224747),
Offset(11.905511997912269, 10.519519297615686),
Offset(22.288325077287325, 5.992865842523692),
Offset(30.404134439557254, 7.761342935335598),
Offset(33.61929906828942, 11.570908914742331),
Offset(35.25300243452185, 14.230458757139374),
Offset(36.21471762947331, 16.191242561808075),
Offset(36.803975496328306, 17.698645771806415),
Offset(37.18416968837589, 18.87242179985836),
Offset(37.445620479790264, 19.788403617209426),
Offset(37.63807337154698, 20.499019999728493),
Offset(37.76636524119959, 21.043465830420356),
Offset(37.84688070253245, 21.447001555066198),
Offset(37.895912975403306, 21.728985066095305),
Offset(37.92359388763603, 21.905378434612928),
Offset(37.93595283405028, 21.98924768876775),
Offset(37.9375, 22.0),
],
),
_PathCubicTo(
<Offset>[
Offset(6.0, 26.0),
Offset(5.97480276509507, 25.758483620275058),
Offset(5.9102120831853355, 24.871534924524667),
Offset(5.921631764468266, 22.91713253788045),
Offset(6.602164313410562, 18.968567458224747),
Offset(11.905511997912269, 10.519519297615686),
Offset(22.288325077287325, 5.992865842523692),
Offset(30.404134439557254, 7.761342935335598),
Offset(33.61929906828942, 11.570908914742331),
Offset(35.25300243452185, 14.230458757139374),
Offset(36.21471762947331, 16.191242561808075),
Offset(36.803975496328306, 17.698645771806415),
Offset(37.18416968837589, 18.87242179985836),
Offset(37.445620479790264, 19.788403617209426),
Offset(37.63807337154698, 20.499019999728493),
Offset(37.76636524119959, 21.043465830420356),
Offset(37.84688070253245, 21.447001555066198),
Offset(37.895912975403306, 21.728985066095305),
Offset(37.92359388763603, 21.905378434612928),
Offset(37.93595283405028, 21.98924768876775),
Offset(37.9375, 22.0),
],
<Offset>[
Offset(42.0, 26.0),
Offset(41.9715668775286, 26.241156836662),
Offset(41.83988612178801, 27.12065107976452),
Offset(41.39972981127301, 29.024878356208966),
Offset(39.86903742896586, 32.72775177683695),
Offset(32.840370579562205, 39.80657610034542),
Offset(21.712188487576384, 41.94303848554115),
Offset(14.06742965730648, 38.354475524191464),
Offset(11.554665508171254, 33.598274280005),
Offset(10.55378227775913, 30.424424398606067),
Offset(10.116296706050587, 28.1735838726282),
Offset(9.950186111823127, 26.50031664598051),
Offset(9.907575779387743, 25.232058503788906),
Offset(9.912669821946713, 24.26340582721259),
Offset(9.927760918072412, 23.52461229394332),
Offset(9.95774683780533, 22.966059779854906),
Offset(9.993956644475434, 22.556166293104994),
Offset(10.026198124175803, 22.27177334090344),
Offset(10.04923690661602, 22.094713837168957),
Offset(10.060961130015452, 22.01075350168465),
Offset(10.0625, 22.0),
],
<Offset>[
Offset(42.0, 26.0),
Offset(41.9715668775286, 26.241156836662),
Offset(41.83988612178801, 27.12065107976452),
Offset(41.39972981127301, 29.024878356208966),
Offset(39.86903742896586, 32.72775177683695),
Offset(32.840370579562205, 39.80657610034542),
Offset(21.712188487576384, 41.94303848554115),
Offset(14.06742965730648, 38.354475524191464),
Offset(11.554665508171254, 33.598274280005),
Offset(10.55378227775913, 30.424424398606067),
Offset(10.116296706050587, 28.1735838726282),
Offset(9.950186111823127, 26.50031664598051),
Offset(9.907575779387743, 25.232058503788906),
Offset(9.912669821946713, 24.26340582721259),
Offset(9.927760918072412, 23.52461229394332),
Offset(9.95774683780533, 22.966059779854906),
Offset(9.993956644475434, 22.556166293104994),
Offset(10.026198124175803, 22.27177334090344),
Offset(10.04923690661602, 22.094713837168957),
Offset(10.060961130015452, 22.01075350168465),
Offset(10.0625, 22.0),
],
),
_PathCubicTo(
<Offset>[
Offset(42.0, 26.0),
Offset(41.9715668775286, 26.241156836662),
Offset(41.83988612178801, 27.12065107976452),
Offset(41.39972981127301, 29.024878356208966),
Offset(39.86903742896586, 32.72775177683695),
Offset(32.840370579562205, 39.80657610034542),
Offset(21.712188487576384, 41.94303848554115),
Offset(14.06742965730648, 38.354475524191464),
Offset(11.554665508171254, 33.598274280005),
Offset(10.55378227775913, 30.424424398606067),
Offset(10.116296706050587, 28.1735838726282),
Offset(9.950186111823127, 26.50031664598051),
Offset(9.907575779387743, 25.232058503788906),
Offset(9.912669821946713, 24.26340582721259),
Offset(9.927760918072412, 23.52461229394332),
Offset(9.95774683780533, 22.966059779854906),
Offset(9.993956644475434, 22.556166293104994),
Offset(10.026198124175803, 22.27177334090344),
Offset(10.04923690661602, 22.094713837168957),
Offset(10.060961130015452, 22.01075350168465),
Offset(10.0625, 22.0),
],
<Offset>[
Offset(42.0, 22.0),
Offset(42.02519723490493, 22.241516379724942),
Offset(42.089787916814664, 23.128465075475333),
Offset(42.078368235531734, 25.08286746211955),
Offset(41.39783568658944, 29.031432541775253),
Offset(36.09448800208773, 37.48048070238431),
Offset(25.716890915777384, 42.00721774895393),
Offset(17.730033699513, 40.31030272815691),
Offset(14.773810944920879, 36.822866202860226),
Offset(13.156032790251274, 34.39340640919596),
Offset(12.13588194777422, 32.57238911127051),
Offset(11.474202347993174, 31.15007140388232),
Offset(11.025213475416908, 30.025626279936134),
Offset(10.704423952068467, 29.134761499184584),
Offset(10.46368421682347, 28.432941181442178),
Offset(10.298295990283647, 27.89180160467138),
Offset(10.190423044262575, 27.48975598051868),
Offset(10.12234223563285, 27.208337182264366),
Offset(10.082773894961147, 27.032099939188196),
Offset(10.064770455621808, 26.94825203221997),
Offset(10.0625, 26.9375),
],
<Offset>[
Offset(42.0, 22.0),
Offset(42.02519723490493, 22.241516379724942),
Offset(42.089787916814664, 23.128465075475333),
Offset(42.078368235531734, 25.08286746211955),
Offset(41.39783568658944, 29.031432541775253),
Offset(36.09448800208773, 37.48048070238431),
Offset(25.716890915777384, 42.00721774895393),
Offset(17.730033699513, 40.31030272815691),
Offset(14.773810944920879, 36.822866202860226),
Offset(13.156032790251274, 34.39340640919596),
Offset(12.13588194777422, 32.57238911127051),
Offset(11.474202347993174, 31.15007140388232),
Offset(11.025213475416908, 30.025626279936134),
Offset(10.704423952068467, 29.134761499184584),
Offset(10.46368421682347, 28.432941181442178),
Offset(10.298295990283647, 27.89180160467138),
Offset(10.190423044262575, 27.48975598051868),
Offset(10.12234223563285, 27.208337182264366),
Offset(10.082773894961147, 27.032099939188196),
Offset(10.064770455621808, 26.94825203221997),
Offset(10.0625, 26.9375),
],
),
_PathCubicTo(
<Offset>[
Offset(42.0, 22.0),
Offset(42.02519723490493, 22.241516379724942),
Offset(42.089787916814664, 23.128465075475333),
Offset(42.078368235531734, 25.08286746211955),
Offset(41.39783568658944, 29.031432541775253),
Offset(36.09448800208773, 37.48048070238431),
Offset(25.716890915777384, 42.00721774895393),
Offset(17.730033699513, 40.31030272815691),
Offset(14.773810944920879, 36.822866202860226),
Offset(13.156032790251274, 34.39340640919596),
Offset(12.13588194777422, 32.57238911127051),
Offset(11.474202347993174, 31.15007140388232),
Offset(11.025213475416908, 30.025626279936134),
Offset(10.704423952068467, 29.134761499184584),
Offset(10.46368421682347, 28.432941181442178),
Offset(10.298295990283647, 27.89180160467138),
Offset(10.190423044262575, 27.48975598051868),
Offset(10.12234223563285, 27.208337182264366),
Offset(10.082773894961147, 27.032099939188196),
Offset(10.064770455621808, 26.94825203221997),
Offset(10.0625, 26.9375),
],
<Offset>[
Offset(6.0, 22.0),
Offset(6.028433122471398, 21.758843163338),
Offset(6.1601138782119875, 20.87934892023548),
Offset(6.600270188726988, 18.975121643791034),
Offset(8.13096257103414, 15.272248223163048),
Offset(15.159629420437794, 8.193423899654581),
Offset(26.293027505488325, 6.057045105936464),
Offset(34.06673848176378, 9.717170139301047),
Offset(36.83844450503905, 14.79550083759756),
Offset(37.855252947013994, 18.199440767729264),
Offset(38.234302871196945, 20.590047800450385),
Offset(38.327991732498354, 22.348400529708222),
Offset(38.30180738440505, 23.665989576005586),
Offset(38.23737460991202, 24.659759289181423),
Offset(38.17399667029804, 25.40734888722735),
Offset(38.106914393677904, 25.96920765523683),
Offset(38.04334710231959, 26.380591242479884),
Offset(37.992057086860356, 26.66554890745623),
Offset(37.95713087598116, 26.842764536632167),
Offset(37.93976215965664, 26.92674621930307),
Offset(37.9375, 26.9375),
],
<Offset>[
Offset(6.0, 22.0),
Offset(6.028433122471398, 21.758843163338),
Offset(6.1601138782119875, 20.87934892023548),
Offset(6.600270188726988, 18.975121643791034),
Offset(8.13096257103414, 15.272248223163048),
Offset(15.159629420437794, 8.193423899654581),
Offset(26.293027505488325, 6.057045105936464),
Offset(34.06673848176378, 9.717170139301047),
Offset(36.83844450503905, 14.79550083759756),
Offset(37.855252947013994, 18.199440767729264),
Offset(38.234302871196945, 20.590047800450385),
Offset(38.327991732498354, 22.348400529708222),
Offset(38.30180738440505, 23.665989576005586),
Offset(38.23737460991202, 24.659759289181423),
Offset(38.17399667029804, 25.40734888722735),
Offset(38.106914393677904, 25.96920765523683),
Offset(38.04334710231959, 26.380591242479884),
Offset(37.992057086860356, 26.66554890745623),
Offset(37.95713087598116, 26.842764536632167),
Offset(37.93976215965664, 26.92674621930307),
Offset(37.9375, 26.9375),
],
),
_PathCubicTo(
<Offset>[
Offset(6.0, 22.0),
Offset(6.028433122471398, 21.758843163338),
Offset(6.1601138782119875, 20.87934892023548),
Offset(6.600270188726988, 18.975121643791034),
Offset(8.13096257103414, 15.272248223163048),
Offset(15.159629420437794, 8.193423899654581),
Offset(26.293027505488325, 6.057045105936464),
Offset(34.06673848176378, 9.717170139301047),
Offset(36.83844450503905, 14.79550083759756),
Offset(37.855252947013994, 18.199440767729264),
Offset(38.234302871196945, 20.590047800450385),
Offset(38.327991732498354, 22.348400529708222),
Offset(38.30180738440505, 23.665989576005586),
Offset(38.23737460991202, 24.659759289181423),
Offset(38.17399667029804, 25.40734888722735),
Offset(38.106914393677904, 25.96920765523683),
Offset(38.04334710231959, 26.380591242479884),
Offset(37.992057086860356, 26.66554890745623),
Offset(37.95713087598116, 26.842764536632167),
Offset(37.93976215965664, 26.92674621930307),
Offset(37.9375, 26.9375),
],
<Offset>[
Offset(6.0, 26.0),
Offset(5.97480276509507, 25.758483620275058),
Offset(5.9102120831853355, 24.871534924524667),
Offset(5.921631764468266, 22.91713253788045),
Offset(6.602164313410562, 18.968567458224747),
Offset(11.905511997912269, 10.519519297615686),
Offset(22.288325077287325, 5.992865842523692),
Offset(30.404134439557254, 7.761342935335598),
Offset(33.61929906828942, 11.570908914742331),
Offset(35.25300243452185, 14.230458757139374),
Offset(36.21471762947331, 16.191242561808075),
Offset(36.803975496328306, 17.698645771806415),
Offset(37.18416968837589, 18.87242179985836),
Offset(37.445620479790264, 19.788403617209426),
Offset(37.63807337154698, 20.499019999728493),
Offset(37.76636524119959, 21.043465830420356),
Offset(37.84688070253245, 21.447001555066198),
Offset(37.895912975403306, 21.728985066095305),
Offset(37.92359388763603, 21.905378434612928),
Offset(37.93595283405028, 21.98924768876775),
Offset(37.9375, 22.0),
],
<Offset>[
Offset(6.0, 26.0),
Offset(5.97480276509507, 25.758483620275058),
Offset(5.9102120831853355, 24.871534924524667),
Offset(5.921631764468266, 22.91713253788045),
Offset(6.602164313410562, 18.968567458224747),
Offset(11.905511997912269, 10.519519297615686),
Offset(22.288325077287325, 5.992865842523692),
Offset(30.404134439557254, 7.761342935335598),
Offset(33.61929906828942, 11.570908914742331),
Offset(35.25300243452185, 14.230458757139374),
Offset(36.21471762947331, 16.191242561808075),
Offset(36.803975496328306, 17.698645771806415),
Offset(37.18416968837589, 18.87242179985836),
Offset(37.445620479790264, 19.788403617209426),
Offset(37.63807337154698, 20.499019999728493),
Offset(37.76636524119959, 21.043465830420356),
Offset(37.84688070253245, 21.447001555066198),
Offset(37.895912975403306, 21.728985066095305),
Offset(37.92359388763603, 21.905378434612928),
Offset(37.93595283405028, 21.98924768876775),
Offset(37.9375, 22.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(24.946426391602, 26.0),
Offset(24.919526142652916, 26.01250952487153),
Offset(24.81962665114753, 26.055221415675078),
Offset(24.593386574407845, 26.131575775813122),
Offset(24.112549450730533, 26.21086569759901),
Offset(23.26102990202604, 26.40544929256212),
Offset(21.93030078929294, 28.333115001580325),
Offset(20.21574669997896, 26.840753449152132),
Offset(19.702668556230993, 25.46403358899737),
Offset(19.57851450097965, 24.507387236351565),
Offset(19.59742184955703, 23.820597237404847),
Offset(19.672638738964572, 23.313659191847616),
Offset(19.76421128572404, 22.933948220939197),
Offset(19.85318172952868, 22.647748525973807),
Offset(19.930810929304265, 22.432414178767115),
Offset(19.99628397445662, 22.272029228601628),
Offset(20.048487526419784, 22.155772744171706),
Offset(20.086790256569586, 22.07583407578212),
Offset(20.111504785414724, 22.026366303959268),
Offset(20.12345813528363, 22.002990192537517),
Offset(20.125, 22.0),
],
),
_PathCubicTo(
<Offset>[
Offset(24.946426391602, 26.0),
Offset(24.919526142652916, 26.01250952487153),
Offset(24.81962665114753, 26.055221415675078),
Offset(24.593386574407845, 26.131575775813122),
Offset(24.112549450730533, 26.21086569759901),
Offset(23.26102990202604, 26.40544929256212),
Offset(21.93030078929294, 28.333115001580325),
Offset(20.21574669997896, 26.840753449152132),
Offset(19.702668556230993, 25.46403358899737),
Offset(19.57851450097965, 24.507387236351565),
Offset(19.59742184955703, 23.820597237404847),
Offset(19.672638738964572, 23.313659191847616),
Offset(19.76421128572404, 22.933948220939197),
Offset(19.85318172952868, 22.647748525973807),
Offset(19.930810929304265, 22.432414178767115),
Offset(19.99628397445662, 22.272029228601628),
Offset(20.048487526419784, 22.155772744171706),
Offset(20.086790256569586, 22.07583407578212),
Offset(20.111504785414724, 22.026366303959268),
Offset(20.12345813528363, 22.002990192537517),
Offset(20.125, 22.0),
],
<Offset>[
Offset(42.000000000002004, 26.0),
Offset(41.971566877530606, 26.241156836662025),
Offset(41.83988612179001, 27.120651079764645),
Offset(41.39972981127498, 29.024878356209307),
Offset(39.86903742895662, 32.72775177683313),
Offset(32.84037057959128, 39.806576100386096),
Offset(21.712188487577507, 41.94303848547116),
Offset(14.067429657339456, 38.35447552412971),
Offset(11.554665508114638, 33.59827428006152),
Offset(10.553782277809306, 30.424424398573166),
Offset(10.11629670607785, 28.173583872615687),
Offset(9.950186111889643, 26.50031664595871),
Offset(9.907575779455914, 25.23205850377301),
Offset(9.912669821848008, 24.263405827228635),
Offset(9.927760918072412, 23.52461229394332),
Offset(9.95774683780533, 22.966059779854906),
Offset(9.993956644475434, 22.556166293104994),
Offset(10.026198124175803, 22.27177334090344),
Offset(10.04923690661602, 22.094713837168957),
Offset(10.060961130015452, 22.01075350168465),
Offset(10.0625, 22.0),
],
<Offset>[
Offset(42.000000000002004, 26.0),
Offset(41.971566877530606, 26.241156836662025),
Offset(41.83988612179001, 27.120651079764645),
Offset(41.39972981127498, 29.024878356209307),
Offset(39.86903742895662, 32.72775177683313),
Offset(32.84037057959128, 39.806576100386096),
Offset(21.712188487577507, 41.94303848547116),
Offset(14.067429657339456, 38.35447552412971),
Offset(11.554665508114638, 33.59827428006152),
Offset(10.553782277809306, 30.424424398573166),
Offset(10.11629670607785, 28.173583872615687),
Offset(9.950186111889643, 26.50031664595871),
Offset(9.907575779455914, 25.23205850377301),
Offset(9.912669821848008, 24.263405827228635),
Offset(9.927760918072412, 23.52461229394332),
Offset(9.95774683780533, 22.966059779854906),
Offset(9.993956644475434, 22.556166293104994),
Offset(10.026198124175803, 22.27177334090344),
Offset(10.04923690661602, 22.094713837168957),
Offset(10.060961130015452, 22.01075350168465),
Offset(10.0625, 22.0),
],
),
_PathCubicTo(
<Offset>[
Offset(42.000000000002004, 26.0),
Offset(41.971566877530606, 26.241156836662025),
Offset(41.83988612179001, 27.120651079764645),
Offset(41.39972981127498, 29.024878356209307),
Offset(39.86903742895662, 32.72775177683313),
Offset(32.84037057959128, 39.806576100386096),
Offset(21.712188487577507, 41.94303848547116),
Offset(14.067429657339456, 38.35447552412971),
Offset(11.554665508114638, 33.59827428006152),
Offset(10.553782277809306, 30.424424398573166),
Offset(10.11629670607785, 28.173583872615687),
Offset(9.950186111889643, 26.50031664595871),
Offset(9.907575779455914, 25.23205850377301),
Offset(9.912669821848008, 24.263405827228635),
Offset(9.927760918072412, 23.52461229394332),
Offset(9.95774683780533, 22.966059779854906),
Offset(9.993956644475434, 22.556166293104994),
Offset(10.026198124175803, 22.27177334090344),
Offset(10.04923690661602, 22.094713837168957),
Offset(10.060961130015452, 22.01075350168465),
Offset(10.0625, 22.0),
],
<Offset>[
Offset(42.000000000002004, 22.0),
Offset(42.025197234906926, 22.241516379724967),
Offset(42.08978791681666, 23.128465075475457),
Offset(42.0783682355337, 25.08286746211989),
Offset(41.397835686580194, 29.03143254177143),
Offset(36.094488002116805, 37.48048070242499),
Offset(25.789219352940048, 42.00837688265331),
Offset(19.59049856191341, 41.30378926060276),
Offset(20.224936460436354, 42.28321450135585),
Offset(18.827987907130577, 43.04433671564179),
Offset(16.997529418949235, 43.161414977908365),
Offset(15.331601790632021, 42.918949572968955),
Offset(13.928660013420258, 42.478559653106245),
Offset(12.785040072364048, 41.93598444668365),
Offset(11.87472277556043, 41.35613622700879),
Offset(11.194931733517697, 40.86084337127677),
Offset(10.707701666486946, 40.479460473962305),
Offset(10.375481162000769, 40.20587235951845),
Offset(10.171073813641986, 40.03180005589708),
Offset(10.074800072408165, 39.948248163249666),
Offset(10.062500000000002, 39.9375),
],
<Offset>[
Offset(42.000000000002004, 22.0),
Offset(42.025197234906926, 22.241516379724967),
Offset(42.08978791681666, 23.128465075475457),
Offset(42.0783682355337, 25.08286746211989),
Offset(41.397835686580194, 29.03143254177143),
Offset(36.094488002116805, 37.48048070242499),
Offset(25.789219352940048, 42.00837688265331),
Offset(19.59049856191341, 41.30378926060276),
Offset(20.224936460436354, 42.28321450135585),
Offset(18.827987907130577, 43.04433671564179),
Offset(16.997529418949235, 43.161414977908365),
Offset(15.331601790632021, 42.918949572968955),
Offset(13.928660013420258, 42.478559653106245),
Offset(12.785040072364048, 41.93598444668365),
Offset(11.87472277556043, 41.35613622700879),
Offset(11.194931733517697, 40.86084337127677),
Offset(10.707701666486946, 40.479460473962305),
Offset(10.375481162000769, 40.20587235951845),
Offset(10.171073813641986, 40.03180005589708),
Offset(10.074800072408165, 39.948248163249666),
Offset(10.062500000000002, 39.9375),
],
),
_PathCubicTo(
<Offset>[
Offset(42.000000000002004, 22.0),
Offset(42.025197234906926, 22.241516379724967),
Offset(42.08978791681666, 23.128465075475457),
Offset(42.0783682355337, 25.08286746211989),
Offset(41.397835686580194, 29.03143254177143),
Offset(36.094488002116805, 37.48048070242499),
Offset(25.789219352940048, 42.00837688265331),
Offset(19.59049856191341, 41.30378926060276),
Offset(20.224936460436354, 42.28321450135585),
Offset(18.827987907130577, 43.04433671564179),
Offset(16.997529418949235, 43.161414977908365),
Offset(15.331601790632021, 42.918949572968955),
Offset(13.928660013420258, 42.478559653106245),
Offset(12.785040072364048, 41.93598444668365),
Offset(11.87472277556043, 41.35613622700879),
Offset(11.194931733517697, 40.86084337127677),
Offset(10.707701666486946, 40.479460473962305),
Offset(10.375481162000769, 40.20587235951845),
Offset(10.171073813641986, 40.03180005589708),
Offset(10.074800072408165, 39.948248163249666),
Offset(10.062500000000002, 39.9375),
],
<Offset>[
Offset(24.946426391602, 22.0),
Offset(24.97315650002924, 22.01286906793447),
Offset(25.06952844617418, 22.06303541138589),
Offset(25.272024998666566, 22.189564881723705),
Offset(25.64134770835411, 22.51454646253731),
Offset(26.515147324551563, 24.079353894601017),
Offset(26.00733165465548, 28.39845339876247),
Offset(25.738815604552915, 29.790067185625176),
Offset(28.372939508552708, 34.1489738102917),
Offset(27.852720130300924, 37.12729955342019),
Offset(26.47865456242841, 38.80842834269753),
Offset(25.05405441770695, 39.73229211885786),
Offset(23.785295519688383, 40.180449370272434),
Offset(22.72555198004472, 40.32032714542882),
Offset(21.87777278679228, 40.26393811183259),
Offset(21.233468870168988, 40.166812820023495),
Offset(20.762232548431296, 40.079066925029025),
Offset(20.436073294394554, 40.00993309439713),
Offset(20.23334169244069, 39.96345252268739),
Offset(20.137297077676344, 39.940484854102536),
Offset(20.125, 39.9375),
],
<Offset>[
Offset(24.946426391602, 22.0),
Offset(24.97315650002924, 22.01286906793447),
Offset(25.06952844617418, 22.06303541138589),
Offset(25.272024998666566, 22.189564881723705),
Offset(25.64134770835411, 22.51454646253731),
Offset(26.515147324551563, 24.079353894601017),
Offset(26.00733165465548, 28.39845339876247),
Offset(25.738815604552915, 29.790067185625176),
Offset(28.372939508552708, 34.1489738102917),
Offset(27.852720130300924, 37.12729955342019),
Offset(26.47865456242841, 38.80842834269753),
Offset(25.05405441770695, 39.73229211885786),
Offset(23.785295519688383, 40.180449370272434),
Offset(22.72555198004472, 40.32032714542882),
Offset(21.87777278679228, 40.26393811183259),
Offset(21.233468870168988, 40.166812820023495),
Offset(20.762232548431296, 40.079066925029025),
Offset(20.436073294394554, 40.00993309439713),
Offset(20.23334169244069, 39.96345252268739),
Offset(20.137297077676344, 39.940484854102536),
Offset(20.125, 39.9375),
],
),
_PathCubicTo(
<Offset>[
Offset(24.946426391602, 22.0),
Offset(24.97315650002924, 22.01286906793447),
Offset(25.06952844617418, 22.06303541138589),
Offset(25.272024998666566, 22.189564881723705),
Offset(25.64134770835411, 22.51454646253731),
Offset(26.515147324551563, 24.079353894601017),
Offset(26.00733165465548, 28.39845339876247),
Offset(25.738815604552915, 29.790067185625176),
Offset(28.372939508552708, 34.1489738102917),
Offset(27.852720130300924, 37.12729955342019),
Offset(26.47865456242841, 38.80842834269753),
Offset(25.05405441770695, 39.73229211885786),
Offset(23.785295519688383, 40.180449370272434),
Offset(22.72555198004472, 40.32032714542882),
Offset(21.87777278679228, 40.26393811183259),
Offset(21.233468870168988, 40.166812820023495),
Offset(20.762232548431296, 40.079066925029025),
Offset(20.436073294394554, 40.00993309439713),
Offset(20.23334169244069, 39.96345252268739),
Offset(20.137297077676344, 39.940484854102536),
Offset(20.125, 39.9375),
],
<Offset>[
Offset(24.946426391602, 26.0),
Offset(24.919526142652916, 26.01250952487153),
Offset(24.81962665114753, 26.055221415675078),
Offset(24.59338657440784, 26.131575775813122),
Offset(24.112549450730533, 26.21086569759901),
Offset(23.26102990202604, 26.405449292562118),
Offset(21.93030078929294, 28.333115001580325),
Offset(20.21574669997896, 26.840753449152132),
Offset(19.702668556230993, 25.46403358899737),
Offset(19.57851450097965, 24.507387236351565),
Offset(19.597421849557026, 23.820597237404847),
Offset(19.672638738964572, 23.313659191847616),
Offset(19.76421128572404, 22.933948220939197),
Offset(19.853181729528682, 22.647748525973807),
Offset(19.930810929304265, 22.432414178767115),
Offset(19.99628397445662, 22.272029228601628),
Offset(20.048487526419784, 22.155772744171706),
Offset(20.086790256569586, 22.07583407578212),
Offset(20.111504785414724, 22.026366303959268),
Offset(20.12345813528363, 22.002990192537517),
Offset(20.125, 22.0),
],
<Offset>[
Offset(24.946426391602, 26.0),
Offset(24.919526142652916, 26.01250952487153),
Offset(24.81962665114753, 26.055221415675078),
Offset(24.59338657440784, 26.131575775813122),
Offset(24.112549450730533, 26.21086569759901),
Offset(23.26102990202604, 26.405449292562118),
Offset(21.93030078929294, 28.333115001580325),
Offset(20.21574669997896, 26.840753449152132),
Offset(19.702668556230993, 25.46403358899737),
Offset(19.57851450097965, 24.507387236351565),
Offset(19.597421849557026, 23.820597237404847),
Offset(19.672638738964572, 23.313659191847616),
Offset(19.76421128572404, 22.933948220939197),
Offset(19.853181729528682, 22.647748525973807),
Offset(19.930810929304265, 22.432414178767115),
Offset(19.99628397445662, 22.272029228601628),
Offset(20.048487526419784, 22.155772744171706),
Offset(20.086790256569586, 22.07583407578212),
Offset(20.111504785414724, 22.026366303959268),
Offset(20.12345813528363, 22.002990192537517),
Offset(20.125, 22.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.053573608398, 26.0),
Offset(23.026843499970756, 25.98713093206553),
Offset(22.930471553825814, 25.93696458861411),
Offset(22.727975001333434, 25.810435118276295),
Offset(22.35865229164589, 25.48545353746269),
Offset(21.484852675448433, 23.920646105398983),
Offset(22.070212775572372, 19.602789326384535),
Offset(24.25581739693188, 19.275065010286717),
Offset(25.471296020158917, 19.70514960582061),
Offset(26.22827021130133, 20.147495919393876),
Offset(26.733592485966874, 20.544229197031424),
Offset(27.081522869281894, 20.885303225908167),
Offset(27.327534182039592, 21.170532082708068),
Offset(27.505108572109584, 21.404060918464253),
Offset(27.63502336031513, 21.591218114904695),
Offset(27.72782810454829, 21.737496381673637),
Offset(27.7923498205881, 21.847395103999485),
Offset(27.83532084300952, 21.924924331216626),
Offset(27.861326008837327, 21.973725967822613),
Offset(27.873455828782106, 21.997010997914884),
Offset(27.875, 22.0),
],
),
_PathCubicTo(
<Offset>[
Offset(23.053573608398, 26.0),
Offset(23.026843499970756, 25.98713093206553),
Offset(22.930471553825814, 25.93696458861411),
Offset(22.727975001333434, 25.810435118276295),
Offset(22.35865229164589, 25.48545353746269),
Offset(21.484852675448433, 23.920646105398983),
Offset(22.070212775572372, 19.602789326384535),
Offset(24.25581739693188, 19.275065010286717),
Offset(25.471296020158917, 19.70514960582061),
Offset(26.22827021130133, 20.147495919393876),
Offset(26.733592485966874, 20.544229197031424),
Offset(27.081522869281894, 20.885303225908167),
Offset(27.327534182039592, 21.170532082708068),
Offset(27.505108572109584, 21.404060918464253),
Offset(27.63502336031513, 21.591218114904695),
Offset(27.72782810454829, 21.737496381673637),
Offset(27.7923498205881, 21.847395103999485),
Offset(27.83532084300952, 21.924924331216626),
Offset(27.861326008837327, 21.973725967822613),
Offset(27.873455828782106, 21.997010997914884),
Offset(27.875, 22.0),
],
<Offset>[
Offset(5.999999999998, 26.0),
Offset(5.974802765093067, 25.758483620275033),
Offset(5.910212083183335, 24.871534924524543),
Offset(5.921631764466294, 22.91713253788011),
Offset(6.602164313419802, 18.96856745822857),
Offset(11.905511997883192, 10.519519297575007),
Offset(22.288325077287805, 5.992865842493696),
Offset(30.404134439571386, 7.761342935309134),
Offset(33.61929906827527, 11.570908914756462),
Offset(35.253002434471675, 14.230458757172274),
Offset(36.21471762944605, 16.191242561820587),
Offset(36.80397549635682, 17.698645771797075),
Offset(37.18416968830772, 18.872421799874253),
Offset(37.44562047979026, 19.788403617209426),
Offset(37.63807337154698, 20.499019999728493),
Offset(37.76636524119958, 21.043465830420356),
Offset(37.84688070253245, 21.447001555066198),
Offset(37.895912975403306, 21.728985066095305),
Offset(37.92359388763603, 21.905378434612928),
Offset(37.93595283405028, 21.98924768876775),
Offset(37.9375, 22.0),
],
<Offset>[
Offset(5.999999999998, 26.0),
Offset(5.974802765093067, 25.758483620275033),
Offset(5.910212083183335, 24.871534924524543),
Offset(5.921631764466294, 22.91713253788011),
Offset(6.602164313419802, 18.96856745822857),
Offset(11.905511997883192, 10.519519297575007),
Offset(22.288325077287805, 5.992865842493696),
Offset(30.404134439571386, 7.761342935309134),
Offset(33.61929906827527, 11.570908914756462),
Offset(35.253002434471675, 14.230458757172274),
Offset(36.21471762944605, 16.191242561820587),
Offset(36.80397549635682, 17.698645771797075),
Offset(37.18416968830772, 18.872421799874253),
Offset(37.44562047979026, 19.788403617209426),
Offset(37.63807337154698, 20.499019999728493),
Offset(37.76636524119958, 21.043465830420356),
Offset(37.84688070253245, 21.447001555066198),
Offset(37.895912975403306, 21.728985066095305),
Offset(37.92359388763603, 21.905378434612928),
Offset(37.93595283405028, 21.98924768876775),
Offset(37.9375, 22.0),
],
),
_PathCubicTo(
<Offset>[
Offset(5.999999999998, 26.0),
Offset(5.974802765093067, 25.758483620275033),
Offset(5.910212083183335, 24.871534924524543),
Offset(5.921631764466294, 22.91713253788011),
Offset(6.602164313419802, 18.96856745822857),
Offset(11.905511997883192, 10.519519297575007),
Offset(22.288325077287805, 5.992865842493696),
Offset(30.404134439571386, 7.761342935309134),
Offset(33.61929906827527, 11.570908914756462),
Offset(35.253002434471675, 14.230458757172274),
Offset(36.21471762944605, 16.191242561820587),
Offset(36.80397549635682, 17.698645771797075),
Offset(37.18416968830772, 18.872421799874253),
Offset(37.44562047979026, 19.788403617209426),
Offset(37.63807337154698, 20.499019999728493),
Offset(37.76636524119958, 21.043465830420356),
Offset(37.84688070253245, 21.447001555066198),
Offset(37.895912975403306, 21.728985066095305),
Offset(37.92359388763603, 21.905378434612928),
Offset(37.93595283405028, 21.98924768876775),
Offset(37.9375, 22.0),
],
<Offset>[
Offset(5.999999999998, 22.0),
Offset(6.028433122469394, 21.758843163337975),
Offset(6.160113878209987, 20.879348920235355),
Offset(6.600270188725016, 18.975121643790693),
Offset(8.13096257104338, 15.27224822316687),
Offset(15.159629420408717, 8.193423899613903),
Offset(26.365355942650346, 6.058204239675842),
Offset(35.92720334414534, 10.710656671782182),
Offset(42.28957002059698, 20.25584913605079),
Offset(43.52720806379294, 26.850371074240893),
Offset(43.09595034231744, 31.17907366711327),
Offset(42.1853911750992, 34.117278698807326),
Offset(41.205253922272064, 36.11892294920749),
Offset(40.3179907303063, 37.46098223666444),
Offset(39.585035229035, 38.330543932793965),
Offset(39.00355013691195, 38.93824942184222),
Offset(38.56062572454396, 39.37029573592351),
Offset(38.24519601322827, 39.66308408471031),
Offset(38.045430794661996, 39.842464653341054),
Offset(37.949791776443, 39.926742350332766),
Offset(37.9375, 39.9375),
],
<Offset>[
Offset(5.999999999998, 22.0),
Offset(6.028433122469394, 21.758843163337975),
Offset(6.160113878209987, 20.879348920235355),
Offset(6.600270188725016, 18.975121643790693),
Offset(8.13096257104338, 15.27224822316687),
Offset(15.159629420408717, 8.193423899613903),
Offset(26.365355942650346, 6.058204239675842),
Offset(35.92720334414534, 10.710656671782182),
Offset(42.28957002059698, 20.25584913605079),
Offset(43.52720806379294, 26.850371074240893),
Offset(43.09595034231744, 31.17907366711327),
Offset(42.1853911750992, 34.117278698807326),
Offset(41.205253922272064, 36.11892294920749),
Offset(40.3179907303063, 37.46098223666444),
Offset(39.585035229035, 38.330543932793965),
Offset(39.00355013691195, 38.93824942184222),
Offset(38.56062572454396, 39.37029573592351),
Offset(38.24519601322827, 39.66308408471031),
Offset(38.045430794661996, 39.842464653341054),
Offset(37.949791776443, 39.926742350332766),
Offset(37.9375, 39.9375),
],
),
_PathCubicTo(
<Offset>[
Offset(5.999999999998, 22.0),
Offset(6.028433122469394, 21.758843163337975),
Offset(6.160113878209987, 20.879348920235355),
Offset(6.600270188725016, 18.975121643790693),
Offset(8.13096257104338, 15.27224822316687),
Offset(15.159629420408717, 8.193423899613903),
Offset(26.365355942650346, 6.058204239675842),
Offset(35.92720334414534, 10.710656671782182),
Offset(42.28957002059698, 20.25584913605079),
Offset(43.52720806379294, 26.850371074240893),
Offset(43.09595034231744, 31.17907366711327),
Offset(42.1853911750992, 34.117278698807326),
Offset(41.205253922272064, 36.11892294920749),
Offset(40.3179907303063, 37.46098223666444),
Offset(39.585035229035, 38.330543932793965),
Offset(39.00355013691195, 38.93824942184222),
Offset(38.56062572454396, 39.37029573592351),
Offset(38.24519601322827, 39.66308408471031),
Offset(38.045430794661996, 39.842464653341054),
Offset(37.949791776443, 39.926742350332766),
Offset(37.9375, 39.9375),
],
<Offset>[
Offset(23.053573608398, 22.0),
Offset(23.08047385734708, 21.98749047512847),
Offset(23.180373348852466, 21.944778584324922),
Offset(23.40661342559216, 21.868424224186878),
Offset(23.887450549269467, 21.78913430240099),
Offset(24.73897009797396, 21.594550707437882),
Offset(26.147243640934914, 19.66812772356668),
Offset(29.778886301505835, 22.224378746759765),
Offset(34.14156697248063, 28.39008982711494),
Offset(34.5024758406226, 32.767408236462494),
Offset(33.614825198838254, 35.532060302324105),
Offset(32.46293854802427, 37.30393615291841),
Offset(31.348618416003937, 38.417033232041305),
Offset(30.377478822625626, 39.07663953791927),
Offset(29.58198521780315, 39.42274204797017),
Offset(28.96501300026066, 39.6322799730955),
Offset(28.506094842599616, 39.7706892848568),
Offset(28.184603880834484, 39.85902334983163),
Offset(27.983162915863293, 39.910812186550736),
Offset(27.88729477117482, 39.934505659479896),
Offset(27.875, 39.9375),
],
<Offset>[
Offset(23.053573608398, 22.0),
Offset(23.08047385734708, 21.98749047512847),
Offset(23.180373348852466, 21.944778584324922),
Offset(23.40661342559216, 21.868424224186878),
Offset(23.887450549269467, 21.78913430240099),
Offset(24.73897009797396, 21.594550707437882),
Offset(26.147243640934914, 19.66812772356668),
Offset(29.778886301505835, 22.224378746759765),
Offset(34.14156697248063, 28.39008982711494),
Offset(34.5024758406226, 32.767408236462494),
Offset(33.614825198838254, 35.532060302324105),
Offset(32.46293854802427, 37.30393615291841),
Offset(31.348618416003937, 38.417033232041305),
Offset(30.377478822625626, 39.07663953791927),
Offset(29.58198521780315, 39.42274204797017),
Offset(28.96501300026066, 39.6322799730955),
Offset(28.506094842599616, 39.7706892848568),
Offset(28.184603880834484, 39.85902334983163),
Offset(27.983162915863293, 39.910812186550736),
Offset(27.88729477117482, 39.934505659479896),
Offset(27.875, 39.9375),
],
),
_PathCubicTo(
<Offset>[
Offset(23.053573608398, 22.0),
Offset(23.08047385734708, 21.98749047512847),
Offset(23.180373348852466, 21.944778584324922),
Offset(23.40661342559216, 21.868424224186878),
Offset(23.887450549269467, 21.78913430240099),
Offset(24.73897009797396, 21.594550707437882),
Offset(26.147243640934914, 19.66812772356668),
Offset(29.778886301505835, 22.224378746759765),
Offset(34.14156697248063, 28.39008982711494),
Offset(34.5024758406226, 32.767408236462494),
Offset(33.614825198838254, 35.532060302324105),
Offset(32.46293854802427, 37.30393615291841),
Offset(31.348618416003937, 38.417033232041305),
Offset(30.377478822625626, 39.07663953791927),
Offset(29.58198521780315, 39.42274204797017),
Offset(28.96501300026066, 39.6322799730955),
Offset(28.506094842599616, 39.7706892848568),
Offset(28.184603880834484, 39.85902334983163),
Offset(27.983162915863293, 39.910812186550736),
Offset(27.88729477117482, 39.934505659479896),
Offset(27.875, 39.9375),
],
<Offset>[
Offset(23.053573608398, 26.0),
Offset(23.026843499970756, 25.98713093206553),
Offset(22.930471553825818, 25.93696458861411),
Offset(22.727975001333434, 25.810435118276295),
Offset(22.35865229164589, 25.48545353746269),
Offset(21.484852675448437, 23.920646105398983),
Offset(22.070212775572372, 19.602789326384535),
Offset(24.25581739693188, 19.275065010286717),
Offset(25.471296020158917, 19.70514960582061),
Offset(26.22827021130133, 20.147495919393876),
Offset(26.733592485966874, 20.544229197031424),
Offset(27.081522869281894, 20.885303225908167),
Offset(27.327534182039592, 21.170532082708068),
Offset(27.505108572109584, 21.404060918464253),
Offset(27.63502336031513, 21.591218114904695),
Offset(27.72782810454829, 21.737496381673637),
Offset(27.7923498205881, 21.847395103999485),
Offset(27.83532084300952, 21.924924331216626),
Offset(27.861326008837327, 21.973725967822613),
Offset(27.873455828782106, 21.997010997914884),
Offset(27.875, 22.0),
],
<Offset>[
Offset(23.053573608398, 26.0),
Offset(23.026843499970756, 25.98713093206553),
Offset(22.930471553825818, 25.93696458861411),
Offset(22.727975001333434, 25.810435118276295),
Offset(22.35865229164589, 25.48545353746269),
Offset(21.484852675448437, 23.920646105398983),
Offset(22.070212775572372, 19.602789326384535),
Offset(24.25581739693188, 19.275065010286717),
Offset(25.471296020158917, 19.70514960582061),
Offset(26.22827021130133, 20.147495919393876),
Offset(26.733592485966874, 20.544229197031424),
Offset(27.081522869281894, 20.885303225908167),
Offset(27.327534182039592, 21.170532082708068),
Offset(27.505108572109584, 21.404060918464253),
Offset(27.63502336031513, 21.591218114904695),
Offset(27.72782810454829, 21.737496381673637),
Offset(27.7923498205881, 21.847395103999485),
Offset(27.83532084300952, 21.924924331216626),
Offset(27.861326008837327, 21.973725967822613),
Offset(27.873455828782106, 21.997010997914884),
Offset(27.875, 22.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(6.0, 36.0),
Offset(5.840726871654255, 35.757584762617704),
Offset(5.285457595618709, 34.85199993524763),
Offset(4.227525983784449, 32.77342417727839),
Offset(3.5264717596110557, 28.827211071001663),
Offset(6.517886449942477, 24.591045888519158),
Offset(7.520599639567256, 20.429019310226224),
Offset(9.337441251165988, 14.915299719515282),
Offset(11.67955424234765, 11.532962037598704),
Offset(14.02683296676815, 9.419579743902961),
Offset(16.229456854531474, 8.105002459199046),
Offset(18.082743777434697, 7.3261172370029986),
Offset(19.565347960385694, 6.872065247520328),
Offset(20.738317895220952, 6.610528546128252),
Offset(21.653024624707548, 6.463637943249828),
Offset(22.351393858266118, 6.3842574556990765),
Offset(22.866855439990758, 6.343605379246371),
Offset(23.22597898795316, 6.324220552672472),
Offset(23.450183580341104, 6.315826581309215),
Offset(23.556666562733803, 6.312836771798083),
Offset(23.5703125, 6.312499999999998),
],
),
_PathCubicTo(
<Offset>[
Offset(6.0, 36.0),
Offset(5.840726871654255, 35.757584762617704),
Offset(5.285457595618709, 34.85199993524763),
Offset(4.227525983784449, 32.77342417727839),
Offset(3.5264717596110557, 28.827211071001663),
Offset(6.517886449942477, 24.591045888519158),
Offset(7.520599639567256, 20.429019310226224),
Offset(9.337441251165988, 14.915299719515282),
Offset(11.67955424234765, 11.532962037598704),
Offset(14.02683296676815, 9.419579743902961),
Offset(16.229456854531474, 8.105002459199046),
Offset(18.082743777434697, 7.3261172370029986),
Offset(19.565347960385694, 6.872065247520328),
Offset(20.738317895220952, 6.610528546128252),
Offset(21.653024624707548, 6.463637943249828),
Offset(22.351393858266118, 6.3842574556990765),
Offset(22.866855439990758, 6.343605379246371),
Offset(23.22597898795316, 6.324220552672472),
Offset(23.450183580341104, 6.315826581309215),
Offset(23.556666562733803, 6.312836771798083),
Offset(23.5703125, 6.312499999999998),
],
<Offset>[
Offset(42.0, 36.0),
Offset(41.837490984087786, 36.240257979004646),
Offset(41.215131634221386, 37.10111609048749),
Offset(39.70046993008684, 38.880282689423),
Offset(35.11680046930425, 41.89297634122701),
Offset(17.977223307522138, 40.62221458070813),
Offset(7.4051530249760695, 27.632737664041155),
Offset(7.974125419949719, 17.46832999953845),
Offset(11.043336185217218, 12.16810549276672),
Offset(13.987438256258187, 9.445408761353912),
Offset(16.335956080085097, 8.056106394810097),
Offset(18.194102300352007, 7.289618065369594),
Offset(19.679474513989774, 6.845456228021216),
Offset(20.85398754040343, 6.5917284573090615),
Offset(21.76951977235388, 6.450918244703521),
Offset(22.468302287652584, 6.376174801763673),
Offset(22.98395013193887, 6.338942410896992),
Offset(23.343144268998117, 6.321938651292953),
Offset(23.56736837706624, 6.315030608484569),
Offset(23.673854027857267, 6.312746360589072),
Offset(23.6875, 6.312499999999998),
],
<Offset>[
Offset(42.0, 36.0),
Offset(41.837490984087786, 36.240257979004646),
Offset(41.215131634221386, 37.10111609048749),
Offset(39.70046993008684, 38.880282689423),
Offset(35.11680046930425, 41.89297634122701),
Offset(17.977223307522138, 40.62221458070813),
Offset(7.4051530249760695, 27.632737664041155),
Offset(7.974125419949719, 17.46832999953845),
Offset(11.043336185217218, 12.16810549276672),
Offset(13.987438256258187, 9.445408761353912),
Offset(16.335956080085097, 8.056106394810097),
Offset(18.194102300352007, 7.289618065369594),
Offset(19.679474513989774, 6.845456228021216),
Offset(20.85398754040343, 6.5917284573090615),
Offset(21.76951977235388, 6.450918244703521),
Offset(22.468302287652584, 6.376174801763673),
Offset(22.98395013193887, 6.338942410896992),
Offset(23.343144268998117, 6.321938651292953),
Offset(23.56736837706624, 6.315030608484569),
Offset(23.673854027857267, 6.312746360589072),
Offset(23.6875, 6.312499999999998),
],
),
_PathCubicTo(
<Offset>[
Offset(42.0, 36.0),
Offset(41.837490984087786, 36.240257979004646),
Offset(41.215131634221386, 37.10111609048749),
Offset(39.70046993008684, 38.880282689423),
Offset(35.11680046930425, 41.89297634122701),
Offset(17.977223307522138, 40.62221458070813),
Offset(7.4051530249760695, 27.632737664041155),
Offset(7.974125419949719, 17.46832999953845),
Offset(11.043336185217218, 12.16810549276672),
Offset(13.987438256258187, 9.445408761353912),
Offset(16.335956080085097, 8.056106394810097),
Offset(18.194102300352007, 7.289618065369594),
Offset(19.679474513989774, 6.845456228021216),
Offset(20.85398754040343, 6.5917284573090615),
Offset(21.76951977235388, 6.450918244703521),
Offset(22.468302287652584, 6.376174801763673),
Offset(22.98395013193887, 6.338942410896992),
Offset(23.343144268998117, 6.321938651292953),
Offset(23.56736837706624, 6.315030608484569),
Offset(23.673854027857267, 6.312746360589072),
Offset(23.6875, 6.312499999999998),
],
<Offset>[
Offset(42.0, 32.0),
Offset(41.891121341464114, 32.24061752206759),
Offset(41.46503342924804, 33.1089300861983),
Offset(40.382213841518244, 34.93682280811562),
Offset(37.807067599374584, 37.94317621909476),
Offset(31.28569346733829, 41.88836406262549),
Offset(21.918156356601166, 43.36435943014172),
Offset(14.025584375723557, 40.89778062244908),
Offset(9.769920092960579, 37.63050924159487),
Offset(7.367850012815694, 34.638113152492416),
Offset(5.973096817006795, 32.07021795746492),
Offset(5.173978263055725, 29.973153422615376),
Offset(4.723297068059789, 28.301904267150505),
Offset(4.475728989802221, 26.983370203369095),
Offset(4.346332932330473, 25.957300958770094),
Offset(4.284100454437475, 25.175143122894923),
Offset(4.258180500986249, 24.598514092031586),
Offset(4.250093592349071, 24.197111996156252),
Offset(4.24918203540361, 23.946652278620284),
Offset(4.2498612199243055, 23.82773735822788),
Offset(4.25, 23.8125),
],
<Offset>[
Offset(42.0, 32.0),
Offset(41.891121341464114, 32.24061752206759),
Offset(41.46503342924804, 33.1089300861983),
Offset(40.382213841518244, 34.93682280811562),
Offset(37.807067599374584, 37.94317621909476),
Offset(31.28569346733829, 41.88836406262549),
Offset(21.918156356601166, 43.36435943014172),
Offset(14.025584375723557, 40.89778062244908),
Offset(9.769920092960579, 37.63050924159487),
Offset(7.367850012815694, 34.638113152492416),
Offset(5.973096817006795, 32.07021795746492),
Offset(5.173978263055725, 29.973153422615376),
Offset(4.723297068059789, 28.301904267150505),
Offset(4.475728989802221, 26.983370203369095),
Offset(4.346332932330473, 25.957300958770094),
Offset(4.284100454437475, 25.175143122894923),
Offset(4.258180500986249, 24.598514092031586),
Offset(4.250093592349071, 24.197111996156252),
Offset(4.24918203540361, 23.946652278620284),
Offset(4.2498612199243055, 23.82773735822788),
Offset(4.25, 23.8125),
],
),
_PathCubicTo(
<Offset>[
Offset(42.0, 32.0),
Offset(41.891121341464114, 32.24061752206759),
Offset(41.46503342924804, 33.1089300861983),
Offset(40.382213841518244, 34.93682280811562),
Offset(37.807067599374584, 37.94317621909476),
Offset(31.28569346733829, 41.88836406262549),
Offset(21.918156356601166, 43.36435943014172),
Offset(14.025584375723557, 40.89778062244908),
Offset(9.769920092960579, 37.63050924159487),
Offset(7.367850012815694, 34.638113152492416),
Offset(5.973096817006795, 32.07021795746492),
Offset(5.173978263055725, 29.973153422615376),
Offset(4.723297068059789, 28.301904267150505),
Offset(4.475728989802221, 26.983370203369095),
Offset(4.346332932330473, 25.957300958770094),
Offset(4.284100454437475, 25.175143122894923),
Offset(4.258180500986249, 24.598514092031586),
Offset(4.250093592349071, 24.197111996156252),
Offset(4.24918203540361, 23.946652278620284),
Offset(4.2498612199243055, 23.82773735822788),
Offset(4.25, 23.8125),
],
<Offset>[
Offset(6.0, 32.0),
Offset(5.894357229030582, 31.757944305680645),
Offset(5.535359390645361, 30.859813930958445),
Offset(4.903580651262228, 28.82898486195736),
Offset(4.366121086699318, 24.111995114141347),
Offset(9.36700394742377, 11.224965859696677),
Offset(22.54292545773696, 4.379581429626963),
Offset(32.60235573940598, 6.109759600029818),
Offset(37.826493474762316, 9.62132472038408),
Offset(40.59568298818934, 12.852389468570193),
Offset(42.097634124796315, 15.484672916733718),
Offset(42.946789236607636, 17.592634404564635),
Offset(43.43502405056509, 19.276124853051655),
Offset(43.71087263569899, 20.606380075899363),
Offset(43.86148701396686, 21.64277921186285),
Offset(43.93943970232704, 22.43350690800619),
Offset(43.97670000978504, 23.016835227922453),
Offset(43.992556922799054, 23.423091048223576),
Offset(43.99826508457116, 23.676658296500023),
Offset(43.99984938980357, 23.797069876131136),
Offset(44.0, 23.812499999999996),
],
<Offset>[
Offset(6.0, 32.0),
Offset(5.894357229030582, 31.757944305680645),
Offset(5.535359390645361, 30.859813930958445),
Offset(4.903580651262228, 28.82898486195736),
Offset(4.366121086699318, 24.111995114141347),
Offset(9.36700394742377, 11.224965859696677),
Offset(22.54292545773696, 4.379581429626963),
Offset(32.60235573940598, 6.109759600029818),
Offset(37.826493474762316, 9.62132472038408),
Offset(40.59568298818934, 12.852389468570193),
Offset(42.097634124796315, 15.484672916733718),
Offset(42.946789236607636, 17.592634404564635),
Offset(43.43502405056509, 19.276124853051655),
Offset(43.71087263569899, 20.606380075899363),
Offset(43.86148701396686, 21.64277921186285),
Offset(43.93943970232704, 22.43350690800619),
Offset(43.97670000978504, 23.016835227922453),
Offset(43.992556922799054, 23.423091048223576),
Offset(43.99826508457116, 23.676658296500023),
Offset(43.99984938980357, 23.797069876131136),
Offset(44.0, 23.812499999999996),
],
),
_PathCubicTo(
<Offset>[
Offset(6.0, 32.0),
Offset(5.894357229030582, 31.757944305680645),
Offset(5.535359390645361, 30.859813930958445),
Offset(4.903580651262228, 28.82898486195736),
Offset(4.366121086699318, 24.111995114141347),
Offset(9.36700394742377, 11.224965859696677),
Offset(22.54292545773696, 4.379581429626963),
Offset(32.60235573940598, 6.109759600029818),
Offset(37.826493474762316, 9.62132472038408),
Offset(40.59568298818934, 12.852389468570193),
Offset(42.097634124796315, 15.484672916733718),
Offset(42.946789236607636, 17.592634404564635),
Offset(43.43502405056509, 19.276124853051655),
Offset(43.71087263569899, 20.606380075899363),
Offset(43.86148701396686, 21.64277921186285),
Offset(43.93943970232704, 22.43350690800619),
Offset(43.97670000978504, 23.016835227922453),
Offset(43.992556922799054, 23.423091048223576),
Offset(43.99826508457116, 23.676658296500023),
Offset(43.99984938980357, 23.797069876131136),
Offset(44.0, 23.812499999999996),
],
<Offset>[
Offset(6.0, 36.0),
Offset(5.840726871654255, 35.757584762617704),
Offset(5.285457595618709, 34.85199993524763),
Offset(4.227525983824194, 32.773424177285236),
Offset(3.526471759568551, 28.827211070984085),
Offset(6.517886449901766, 24.591045888462205),
Offset(7.520599639566615, 20.429019310266217),
Offset(9.337441251161277, 14.915299719524107),
Offset(11.679554242336327, 11.53296203761001),
Offset(14.02683296675945, 9.419579743908663),
Offset(16.229456854531474, 8.105002459199046),
Offset(18.082743777434697, 7.3261172370029986),
Offset(19.565347960385694, 6.872065247520328),
Offset(20.738317895220952, 6.610528546128252),
Offset(21.653024624707548, 6.463637943249828),
Offset(22.351393858266118, 6.3842574556990765),
Offset(22.866855439990758, 6.343605379246371),
Offset(23.22597898795316, 6.324220552672472),
Offset(23.450183580341104, 6.315826581309215),
Offset(23.556666562733803, 6.312836771798083),
Offset(23.5703125, 6.312499999999998),
],
<Offset>[
Offset(6.0, 36.0),
Offset(5.840726871654255, 35.757584762617704),
Offset(5.285457595618709, 34.85199993524763),
Offset(4.227525983824194, 32.773424177285236),
Offset(3.526471759568551, 28.827211070984085),
Offset(6.517886449901766, 24.591045888462205),
Offset(7.520599639566615, 20.429019310266217),
Offset(9.337441251161277, 14.915299719524107),
Offset(11.679554242336327, 11.53296203761001),
Offset(14.02683296675945, 9.419579743908663),
Offset(16.229456854531474, 8.105002459199046),
Offset(18.082743777434697, 7.3261172370029986),
Offset(19.565347960385694, 6.872065247520328),
Offset(20.738317895220952, 6.610528546128252),
Offset(21.653024624707548, 6.463637943249828),
Offset(22.351393858266118, 6.3842574556990765),
Offset(22.866855439990758, 6.343605379246371),
Offset(23.22597898795316, 6.324220552672472),
Offset(23.450183580341104, 6.315826581309215),
Offset(23.556666562733803, 6.312836771798083),
Offset(23.5703125, 6.312499999999998),
],
),
_PathClose(
),
],
),
],
);
| flutter/packages/flutter/lib/src/material/animated_icons/data/menu_home.g.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/animated_icons/data/menu_home.g.dart",
"repo_id": "flutter",
"token_count": 48697
} | 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 'dart:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'theme.dart';
/// Defines default property values for descendant [BottomAppBar] widgets.
///
/// Descendant widgets obtain the current [BottomAppBarTheme] object using
/// `BottomAppBarTheme.of(context)`. Instances of [BottomAppBarTheme] can be
/// customized with [BottomAppBarTheme.copyWith].
///
/// Typically a [BottomAppBarTheme] is specified as part of the overall [Theme]
/// with [ThemeData.bottomAppBarTheme].
///
/// All [BottomAppBarTheme] properties are `null` by default. When null, the
/// [BottomAppBar] constructor provides defaults.
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
@immutable
class BottomAppBarTheme with Diagnosticable {
/// Creates a theme that can be used for [ThemeData.bottomAppBarTheme].
const BottomAppBarTheme({
this.color,
this.elevation,
this.shape,
this.height,
this.surfaceTintColor,
this.shadowColor,
this.padding,
});
/// Overrides the default value for [BottomAppBar.color].
final Color? color;
/// Overrides the default value for [BottomAppBar.elevation].
final double? elevation;
/// Overrides the default value for [BottomAppBar.shape].
final NotchedShape? shape;
/// Overrides the default value for [BottomAppBar.height].
final double? height;
/// Overrides the default value for [BottomAppBar.surfaceTintColor].
///
/// If null, [BottomAppBar] will not display an overlay color.
///
/// See [Material.surfaceTintColor] for more details.
final Color? surfaceTintColor;
/// Overrides the default value for [BottomAppBar.shadowColor].
final Color? shadowColor;
/// Overrides the default value for [BottomAppBar.padding].
final EdgeInsetsGeometry? padding;
/// Creates a copy of this object but with the given fields replaced with the
/// new values.
BottomAppBarTheme copyWith({
Color? color,
double? elevation,
NotchedShape? shape,
double? height,
Color? surfaceTintColor,
Color? shadowColor,
EdgeInsetsGeometry? padding,
}) {
return BottomAppBarTheme(
color: color ?? this.color,
elevation: elevation ?? this.elevation,
shape: shape ?? this.shape,
height: height ?? this.height,
surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor,
shadowColor: shadowColor ?? this.shadowColor,
padding: padding ?? this.padding,
);
}
/// The [ThemeData.bottomAppBarTheme] property of the ambient [Theme].
static BottomAppBarTheme of(BuildContext context) {
return Theme.of(context).bottomAppBarTheme;
}
/// Linearly interpolate between two BAB themes.
///
/// {@macro dart.ui.shadow.lerp}
static BottomAppBarTheme lerp(BottomAppBarTheme? a, BottomAppBarTheme? b, double t) {
if (identical(a, b) && a != null) {
return a;
}
return BottomAppBarTheme(
color: Color.lerp(a?.color, b?.color, t),
elevation: lerpDouble(a?.elevation, b?.elevation, t),
shape: t < 0.5 ? a?.shape : b?.shape,
height: lerpDouble(a?.height, b?.height, t),
surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t),
shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t),
padding: EdgeInsetsGeometry.lerp(a?.padding, b?.padding, t),
);
}
@override
int get hashCode => Object.hash(
color,
elevation,
shape,
height,
surfaceTintColor,
shadowColor,
padding,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is BottomAppBarTheme
&& other.color == color
&& other.elevation == elevation
&& other.shape == shape
&& other.height == height
&& other.surfaceTintColor == surfaceTintColor
&& other.shadowColor == shadowColor
&& other.padding == padding;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(ColorProperty('color', color, defaultValue: null));
properties.add(DiagnosticsProperty<double>('elevation', elevation, defaultValue: null));
properties.add(DiagnosticsProperty<NotchedShape>('shape', shape, defaultValue: null));
properties.add(DiagnosticsProperty<double>('height', height, defaultValue: null));
properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null));
properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
}
}
| flutter/packages/flutter/lib/src/material/bottom_app_bar_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/bottom_app_bar_theme.dart",
"repo_id": "flutter",
"token_count": 1667
} | 629 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'material_state.dart';
import 'theme.dart';
import 'theme_data.dart';
// Examples can assume:
// late BuildContext context;
/// Defines default property values for descendant [Checkbox] widgets.
///
/// Descendant widgets obtain the current [CheckboxThemeData] object using
/// `CheckboxTheme.of(context)`. Instances of [CheckboxThemeData] can be
/// customized with [CheckboxThemeData.copyWith].
///
/// Typically a [CheckboxThemeData] is specified as part of the overall [Theme]
/// with [ThemeData.checkboxTheme].
///
/// All [CheckboxThemeData] properties are `null` by default. When null, the
/// [Checkbox] will use the values from [ThemeData] if they exist, otherwise it
/// will provide its own defaults based on the overall [Theme]'s colorScheme.
/// See the individual [Checkbox] properties for details.
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
@immutable
class CheckboxThemeData with Diagnosticable {
/// Creates a theme that can be used for [ThemeData.checkboxTheme].
const CheckboxThemeData({
this.mouseCursor,
this.fillColor,
this.checkColor,
this.overlayColor,
this.splashRadius,
this.materialTapTargetSize,
this.visualDensity,
this.shape,
this.side,
});
/// {@macro flutter.material.checkbox.mouseCursor}
///
/// If specified, overrides the default value of [Checkbox.mouseCursor].
final MaterialStateProperty<MouseCursor?>? mouseCursor;
/// {@macro flutter.material.checkbox.fillColor}
///
/// If specified, overrides the default value of [Checkbox.fillColor].
final MaterialStateProperty<Color?>? fillColor;
/// {@macro flutter.material.checkbox.checkColor}
///
/// Resolves in the following states:
/// * [MaterialState.selected].
/// * [MaterialState.hovered].
/// * [MaterialState.focused].
/// * [MaterialState.disabled].
///
/// If specified, overrides the default value of [Checkbox.checkColor].
final MaterialStateProperty<Color?>? checkColor;
/// {@macro flutter.material.checkbox.overlayColor}
///
/// If specified, overrides the default value of [Checkbox.overlayColor].
final MaterialStateProperty<Color?>? overlayColor;
/// {@macro flutter.material.checkbox.splashRadius}
///
/// If specified, overrides the default value of [Checkbox.splashRadius].
final double? splashRadius;
/// {@macro flutter.material.checkbox.materialTapTargetSize}
///
/// If specified, overrides the default value of
/// [Checkbox.materialTapTargetSize].
final MaterialTapTargetSize? materialTapTargetSize;
/// {@macro flutter.material.checkbox.visualDensity}
///
/// If specified, overrides the default value of [Checkbox.visualDensity].
final VisualDensity? visualDensity;
/// {@macro flutter.material.checkbox.shape}
///
/// If specified, overrides the default value of [Checkbox.shape].
final OutlinedBorder? shape;
/// {@macro flutter.material.checkbox.side}
///
/// If specified, overrides the default value of [Checkbox.side].
final BorderSide? side;
/// Creates a copy of this object but with the given fields replaced with the
/// new values.
CheckboxThemeData copyWith({
MaterialStateProperty<MouseCursor?>? mouseCursor,
MaterialStateProperty<Color?>? fillColor,
MaterialStateProperty<Color?>? checkColor,
MaterialStateProperty<Color?>? overlayColor,
double? splashRadius,
MaterialTapTargetSize? materialTapTargetSize,
VisualDensity? visualDensity,
OutlinedBorder? shape,
BorderSide? side,
}) {
return CheckboxThemeData(
mouseCursor: mouseCursor ?? this.mouseCursor,
fillColor: fillColor ?? this.fillColor,
checkColor: checkColor ?? this.checkColor,
overlayColor: overlayColor ?? this.overlayColor,
splashRadius: splashRadius ?? this.splashRadius,
materialTapTargetSize: materialTapTargetSize ?? this.materialTapTargetSize,
visualDensity: visualDensity ?? this.visualDensity,
shape: shape ?? this.shape,
side: side ?? this.side,
);
}
/// Linearly interpolate between two [CheckboxThemeData]s.
///
/// {@macro dart.ui.shadow.lerp}
static CheckboxThemeData lerp(CheckboxThemeData? a, CheckboxThemeData? b, double t) {
if (identical(a, b) && a != null) {
return a;
}
return CheckboxThemeData(
mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor,
fillColor: MaterialStateProperty.lerp<Color?>(a?.fillColor, b?.fillColor, t, Color.lerp),
checkColor: MaterialStateProperty.lerp<Color?>(a?.checkColor, b?.checkColor, t, Color.lerp),
overlayColor: MaterialStateProperty.lerp<Color?>(a?.overlayColor, b?.overlayColor, t, Color.lerp),
splashRadius: lerpDouble(a?.splashRadius, b?.splashRadius, t),
materialTapTargetSize: t < 0.5 ? a?.materialTapTargetSize : b?.materialTapTargetSize,
visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity,
shape: ShapeBorder.lerp(a?.shape, b?.shape, t) as OutlinedBorder?,
side: _lerpSides(a?.side, b?.side, t),
);
}
@override
int get hashCode => Object.hash(
mouseCursor,
fillColor,
checkColor,
overlayColor,
splashRadius,
materialTapTargetSize,
visualDensity,
shape,
side,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is CheckboxThemeData
&& other.mouseCursor == mouseCursor
&& other.fillColor == fillColor
&& other.checkColor == checkColor
&& other.overlayColor == overlayColor
&& other.splashRadius == splashRadius
&& other.materialTapTargetSize == materialTapTargetSize
&& other.visualDensity == visualDensity
&& other.shape == shape
&& other.side == side;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<MaterialStateProperty<MouseCursor?>>('mouseCursor', mouseCursor, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('fillColor', fillColor, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('checkColor', checkColor, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('overlayColor', overlayColor, defaultValue: null));
properties.add(DoubleProperty('splashRadius', splashRadius, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialTapTargetSize>('materialTapTargetSize', materialTapTargetSize, defaultValue: null));
properties.add(DiagnosticsProperty<VisualDensity>('visualDensity', visualDensity, defaultValue: null));
properties.add(DiagnosticsProperty<OutlinedBorder>('shape', shape, defaultValue: null));
properties.add(DiagnosticsProperty<BorderSide>('side', side, defaultValue: null));
}
// Special case because BorderSide.lerp() doesn't support null arguments
static BorderSide? _lerpSides(BorderSide? a, BorderSide? b, double t) {
if (a == null || b == null) {
return null;
}
if (identical(a, b)) {
return a;
}
return BorderSide.lerp(a, b, t);
}
}
/// Applies a checkbox theme to descendant [Checkbox] widgets.
///
/// Descendant widgets obtain the current theme's [CheckboxTheme] object using
/// [CheckboxTheme.of]. When a widget uses [CheckboxTheme.of], it is
/// automatically rebuilt if the theme later changes.
///
/// A checkbox theme can be specified as part of the overall Material theme
/// using [ThemeData.checkboxTheme].
///
/// See also:
///
/// * [CheckboxThemeData], which describes the actual configuration of a
/// checkbox theme.
class CheckboxTheme extends InheritedWidget {
/// Constructs a checkbox theme that configures all descendant [Checkbox]
/// widgets.
const CheckboxTheme({
super.key,
required this.data,
required super.child,
});
/// The properties used for all descendant [Checkbox] widgets.
final CheckboxThemeData data;
/// Returns the configuration [data] from the closest [CheckboxTheme]
/// ancestor. If there is no ancestor, it returns [ThemeData.checkboxTheme].
///
/// Typical usage is as follows:
///
/// ```dart
/// CheckboxThemeData theme = CheckboxTheme.of(context);
/// ```
static CheckboxThemeData of(BuildContext context) {
final CheckboxTheme? checkboxTheme = context.dependOnInheritedWidgetOfExactType<CheckboxTheme>();
return checkboxTheme?.data ?? Theme.of(context).checkboxTheme;
}
@override
bool updateShouldNotify(CheckboxTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/checkbox_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/checkbox_theme.dart",
"repo_id": "flutter",
"token_count": 2924
} | 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 'package:flutter/foundation.dart' show ValueListenable, clampDouble;
import 'package:flutter/widgets.dart';
import 'debug.dart';
import 'desktop_text_selection_toolbar.dart';
import 'desktop_text_selection_toolbar_button.dart';
import 'material_localizations.dart';
/// Desktop Material styled text selection handle controls.
///
/// Specifically does not manage the toolbar, which is left to
/// [EditableText.contextMenuBuilder].
class _DesktopTextSelectionHandleControls extends DesktopTextSelectionControls with TextSelectionHandleControls {
}
/// Desktop Material styled text selection controls.
///
/// The [desktopTextSelectionControls] global variable has a
/// suitable instance of this class.
class DesktopTextSelectionControls extends TextSelectionControls {
/// Desktop has no text selection handles.
@override
Size getHandleSize(double textLineHeight) {
return Size.zero;
}
/// Builder for the Material-style desktop copy/paste text selection toolbar.
@Deprecated(
'Use `contextMenuBuilder` instead. '
'This feature was deprecated after v3.3.0-0.5.pre.',
)
@override
Widget buildToolbar(
BuildContext context,
Rect globalEditableRegion,
double textLineHeight,
Offset selectionMidpoint,
List<TextSelectionPoint> endpoints,
TextSelectionDelegate delegate,
ValueListenable<ClipboardStatus>? clipboardStatus,
Offset? lastSecondaryTapDownPosition,
) {
return _DesktopTextSelectionControlsToolbar(
clipboardStatus: clipboardStatus,
endpoints: endpoints,
globalEditableRegion: globalEditableRegion,
handleCut: canCut(delegate) ? () => handleCut(delegate) : null,
handleCopy: canCopy(delegate) ? () => handleCopy(delegate) : null,
handlePaste: canPaste(delegate) ? () => handlePaste(delegate) : null,
handleSelectAll: canSelectAll(delegate) ? () => handleSelectAll(delegate) : null,
selectionMidpoint: selectionMidpoint,
lastSecondaryTapDownPosition: lastSecondaryTapDownPosition,
textLineHeight: textLineHeight,
);
}
/// Builds the text selection handles, but desktop has none.
@override
Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) {
return const SizedBox.shrink();
}
/// Gets the position for the text selection handles, but desktop has none.
@override
Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) {
return Offset.zero;
}
@Deprecated(
'Use `contextMenuBuilder` instead. '
'This feature was deprecated after v3.3.0-0.5.pre.',
)
@override
bool canSelectAll(TextSelectionDelegate delegate) {
// Allow SelectAll when selection is not collapsed, unless everything has
// already been selected. Same behavior as Android.
final TextEditingValue value = delegate.textEditingValue;
return delegate.selectAllEnabled &&
value.text.isNotEmpty &&
!(value.selection.start == 0 && value.selection.end == value.text.length);
}
@Deprecated(
'Use `contextMenuBuilder` instead. '
'This feature was deprecated after v3.3.0-0.5.pre.',
)
@override
void handleSelectAll(TextSelectionDelegate delegate) {
super.handleSelectAll(delegate);
delegate.hideToolbar();
}
}
// TODO(justinmc): Deprecate this after TextSelectionControls.buildToolbar is
// deleted, when users should migrate back to desktopTextSelectionControls.
// See https://github.com/flutter/flutter/pull/124262
/// Desktop text selection handle controls that loosely follow Material design
/// conventions.
final TextSelectionControls desktopTextSelectionHandleControls =
_DesktopTextSelectionHandleControls();
/// Desktop text selection controls that loosely follow Material design
/// conventions.
final TextSelectionControls desktopTextSelectionControls =
DesktopTextSelectionControls();
// Generates the child that's passed into DesktopTextSelectionToolbar.
class _DesktopTextSelectionControlsToolbar extends StatefulWidget {
const _DesktopTextSelectionControlsToolbar({
required this.clipboardStatus,
required this.endpoints,
required this.globalEditableRegion,
required this.handleCopy,
required this.handleCut,
required this.handlePaste,
required this.handleSelectAll,
required this.selectionMidpoint,
required this.textLineHeight,
required this.lastSecondaryTapDownPosition,
});
final ValueListenable<ClipboardStatus>? clipboardStatus;
final List<TextSelectionPoint> endpoints;
final Rect globalEditableRegion;
final VoidCallback? handleCopy;
final VoidCallback? handleCut;
final VoidCallback? handlePaste;
final VoidCallback? handleSelectAll;
final Offset? lastSecondaryTapDownPosition;
final Offset selectionMidpoint;
final double textLineHeight;
@override
_DesktopTextSelectionControlsToolbarState createState() => _DesktopTextSelectionControlsToolbarState();
}
class _DesktopTextSelectionControlsToolbarState extends State<_DesktopTextSelectionControlsToolbar> {
void _onChangedClipboardStatus() {
setState(() {
// Inform the widget that the value of clipboardStatus has changed.
});
}
@override
void initState() {
super.initState();
widget.clipboardStatus?.addListener(_onChangedClipboardStatus);
}
@override
void didUpdateWidget(_DesktopTextSelectionControlsToolbar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.clipboardStatus != widget.clipboardStatus) {
oldWidget.clipboardStatus?.removeListener(_onChangedClipboardStatus);
widget.clipboardStatus?.addListener(_onChangedClipboardStatus);
}
}
@override
void dispose() {
widget.clipboardStatus?.removeListener(_onChangedClipboardStatus);
super.dispose();
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
assert(debugCheckHasMediaQuery(context));
// Don't render the menu until the state of the clipboard is known.
if (widget.handlePaste != null && widget.clipboardStatus?.value == ClipboardStatus.unknown) {
return const SizedBox.shrink();
}
final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context);
final Offset midpointAnchor = Offset(
clampDouble(widget.selectionMidpoint.dx - widget.globalEditableRegion.left,
mediaQueryPadding.left,
MediaQuery.sizeOf(context).width - mediaQueryPadding.right,
),
widget.selectionMidpoint.dy - widget.globalEditableRegion.top,
);
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final List<Widget> items = <Widget>[];
void addToolbarButton(
String text,
VoidCallback onPressed,
) {
items.add(DesktopTextSelectionToolbarButton.text(
context: context,
onPressed: onPressed,
text: text,
));
}
if (widget.handleCut != null) {
addToolbarButton(localizations.cutButtonLabel, widget.handleCut!);
}
if (widget.handleCopy != null) {
addToolbarButton(localizations.copyButtonLabel, widget.handleCopy!);
}
if (widget.handlePaste != null
&& widget.clipboardStatus?.value == ClipboardStatus.pasteable) {
addToolbarButton(localizations.pasteButtonLabel, widget.handlePaste!);
}
if (widget.handleSelectAll != null) {
addToolbarButton(localizations.selectAllButtonLabel, widget.handleSelectAll!);
}
// If there is no option available, build an empty widget.
if (items.isEmpty) {
return const SizedBox.shrink();
}
return DesktopTextSelectionToolbar(
anchor: widget.lastSecondaryTapDownPosition ?? midpointAnchor,
children: items,
);
}
}
| flutter/packages/flutter/lib/src/material/desktop_text_selection.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/desktop_text_selection.dart",
"repo_id": "flutter",
"token_count": 2508
} | 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 'dart:math' as math;
import 'package:flutter/widgets.dart';
import 'colors.dart';
import 'debug.dart';
import 'icon_button.dart';
import 'icons.dart';
import 'material_localizations.dart';
import 'theme.dart';
/// A widget representing a rotating expand/collapse button. The icon rotates
/// 180 degrees when pressed, then reverts the animation on a second press.
/// The underlying icon is [Icons.expand_more].
///
/// The expand icon does not include a semantic label for accessibility. In
/// order to be accessible it should be combined with a label using
/// [MergeSemantics]. This is done automatically by the [ExpansionPanel] widget.
///
/// See [IconButton] for a more general implementation of a pressable button
/// with an icon.
///
/// See also:
///
/// * https://material.io/design/iconography/system-icons.html
class ExpandIcon extends StatefulWidget {
/// Creates an [ExpandIcon] with the given padding, and a callback that is
/// triggered when the icon is pressed.
const ExpandIcon({
super.key,
this.isExpanded = false,
this.size = 24.0,
required this.onPressed,
this.padding = const EdgeInsets.all(8.0),
this.color,
this.disabledColor,
this.expandedColor,
});
/// Whether the icon is in an expanded state.
///
/// Rebuilding the widget with a different [isExpanded] value will trigger
/// the animation, but will not trigger the [onPressed] callback.
final bool isExpanded;
/// The size of the icon.
///
/// Defaults to 24.
final double size;
/// The callback triggered when the icon is pressed and the state changes
/// between expanded and collapsed. The value passed to the current state.
///
/// If this is set to null, the button will be disabled.
final ValueChanged<bool>? onPressed;
/// The padding around the icon. The entire padded icon will react to input
/// gestures.
///
/// Defaults to a padding of 8 on all sides.
final EdgeInsetsGeometry padding;
/// {@template flutter.material.ExpandIcon.color}
/// The color of the icon.
///
/// Defaults to [Colors.black54] when the theme's
/// [ThemeData.brightness] is [Brightness.light] and to
/// [Colors.white60] when it is [Brightness.dark]. This adheres to the
/// Material Design specifications for [icons](https://material.io/design/iconography/system-icons.html#color)
/// and for [dark theme](https://material.io/design/color/dark-theme.html#ui-application)
/// {@endtemplate}
final Color? color;
/// The color of the icon when it is disabled,
/// i.e. if [onPressed] is null.
///
/// Defaults to [Colors.black38] when the theme's
/// [ThemeData.brightness] is [Brightness.light] and to
/// [Colors.white38] when it is [Brightness.dark]. This adheres to the
/// Material Design specifications for [icons](https://material.io/design/iconography/system-icons.html#color)
/// and for [dark theme](https://material.io/design/color/dark-theme.html#ui-application)
final Color? disabledColor;
/// The color of the icon when the icon is expanded.
///
/// Defaults to [Colors.black54] when the theme's
/// [ThemeData.brightness] is [Brightness.light] and to
/// [Colors.white] when it is [Brightness.dark]. This adheres to the
/// Material Design specifications for [icons](https://material.io/design/iconography/system-icons.html#color)
/// and for [dark theme](https://material.io/design/color/dark-theme.html#ui-application)
final Color? expandedColor;
@override
State<ExpandIcon> createState() => _ExpandIconState();
}
class _ExpandIconState extends State<ExpandIcon> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _iconTurns;
static final Animatable<double> _iconTurnTween = Tween<double>(begin: 0.0, end: 0.5)
.chain(CurveTween(curve: Curves.fastOutSlowIn));
@override
void initState() {
super.initState();
_controller = AnimationController(duration: kThemeAnimationDuration, vsync: this);
_iconTurns = _controller.drive(_iconTurnTween);
// If the widget is initially expanded, rotate the icon without animating it.
if (widget.isExpanded) {
_controller.value = math.pi;
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
void didUpdateWidget(ExpandIcon oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.isExpanded != oldWidget.isExpanded) {
if (widget.isExpanded) {
_controller.forward();
} else {
_controller.reverse();
}
}
}
void _handlePressed() {
widget.onPressed?.call(widget.isExpanded);
}
/// Default icon colors and opacities for when [Theme.brightness] is set to
/// [Brightness.light] are based on the
/// [Material Design system icon specifications](https://material.io/design/iconography/system-icons.html#color).
/// Icon colors and opacities for [Brightness.dark] are based on the
/// [Material Design dark theme specifications](https://material.io/design/color/dark-theme.html#ui-application)
Color get _iconColor {
if (widget.isExpanded && widget.expandedColor != null) {
return widget.expandedColor!;
}
if (widget.color != null) {
return widget.color!;
}
return switch (Theme.of(context).brightness) {
Brightness.light => Colors.black54,
Brightness.dark => Colors.white60,
};
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context));
assert(debugCheckHasMaterialLocalizations(context));
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final String onTapHint = widget.isExpanded ? localizations.expandedIconTapHint : localizations.collapsedIconTapHint;
return Semantics(
onTapHint: widget.onPressed == null ? null : onTapHint,
child: IconButton(
padding: widget.padding,
iconSize: widget.size,
color: _iconColor,
disabledColor: widget.disabledColor,
onPressed: widget.onPressed == null ? null : _handlePressed,
icon: RotationTransition(
turns: _iconTurns,
child: const Icon(Icons.expand_more),
),
),
);
}
}
| flutter/packages/flutter/lib/src/material/expand_icon.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/expand_icon.dart",
"repo_id": "flutter",
"token_count": 2060
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// A [ButtonStyle] that overrides the default appearance of
/// [IconButton]s when it's used with the [IconButton], the [IconButtonTheme] or the
/// overall [Theme]'s [ThemeData.iconButtonTheme].
///
/// The [IconButton] will be affected by [IconButtonTheme] and [IconButtonThemeData]
/// only if [ThemeData.useMaterial3] is set to true; otherwise, [IconTheme] will be used.
///
/// The [style]'s properties override [IconButton]'s default style. Only
/// the style's non-null property values or resolved non-null
/// [MaterialStateProperty] values are used.
///
/// See also:
///
/// * [IconButtonTheme], the theme which is configured with this class.
/// * [IconButton.styleFrom], which converts simple values into a
/// [ButtonStyle] that's consistent with [IconButton]'s defaults.
/// * [MaterialStateProperty.resolve], "resolve" a material state property
/// to a simple value based on a set of [MaterialState]s.
/// * [ThemeData.iconButtonTheme], which can be used to override the default
/// [ButtonStyle] for [IconButton]s below the overall [Theme].
@immutable
class IconButtonThemeData with Diagnosticable {
/// Creates a [IconButtonThemeData].
///
/// The [style] may be null.
const IconButtonThemeData({ this.style });
/// Overrides for [IconButton]'s default style if [ThemeData.useMaterial3]
/// is set to true.
///
/// Non-null properties or non-null resolved [MaterialStateProperty]
/// values override the default [ButtonStyle] in [IconButton].
///
/// If [style] is null, then this theme doesn't override anything.
final ButtonStyle? style;
/// Linearly interpolate between two icon button themes.
static IconButtonThemeData? lerp(IconButtonThemeData? a, IconButtonThemeData? b, double t) {
if (identical(a, b)) {
return a;
}
return IconButtonThemeData(
style: ButtonStyle.lerp(a?.style, b?.style, t),
);
}
@override
int get hashCode => style.hashCode;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is IconButtonThemeData && other.style == style;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ButtonStyle>('style', style, defaultValue: null));
}
}
/// Overrides the default [ButtonStyle] of its [IconButton] descendants.
///
/// See also:
///
/// * [IconButtonThemeData], which is used to configure this theme.
/// * [IconButton.styleFrom], which converts simple values into a
/// [ButtonStyle] that's consistent with [IconButton]'s defaults.
/// * [ThemeData.iconButtonTheme], which can be used to override the default
/// [ButtonStyle] for [IconButton]s below the overall [Theme].
class IconButtonTheme extends InheritedTheme {
/// Create a [IconButtonTheme].
const IconButtonTheme({
super.key,
required this.data,
required super.child,
});
/// The configuration of this theme.
final IconButtonThemeData data;
/// The closest instance of this class that encloses the given context.
///
/// If there is no enclosing [IconButtonTheme] widget, then
/// [ThemeData.iconButtonTheme] is used.
///
/// Typical usage is as follows:
///
/// ```dart
/// IconButtonThemeData theme = IconButtonTheme.of(context);
/// ```
static IconButtonThemeData of(BuildContext context) {
final IconButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType<IconButtonTheme>();
return buttonTheme?.data ?? Theme.of(context).iconButtonTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return IconButtonTheme(data: data, child: child);
}
@override
bool updateShouldNotify(IconButtonTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/icon_button_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/icon_button_theme.dart",
"repo_id": "flutter",
"token_count": 1270
} | 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:ui';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'button.dart';
import 'button_theme.dart';
import 'constants.dart';
import 'ink_well.dart';
import 'material.dart';
import 'theme.dart';
import 'theme_data.dart';
/// A utility class for building Material buttons that depend on the
/// ambient [ButtonTheme] and [Theme].
///
/// This class is planned to be deprecated in a future release.
/// Please use one or more of these buttons and associated themes instead:
///
/// * [TextButton], [TextButtonTheme], [TextButtonThemeData],
/// * [ElevatedButton], [ElevatedButtonTheme], [ElevatedButtonThemeData],
/// * [OutlinedButton], [OutlinedButtonTheme], [OutlinedButtonThemeData]
///
/// The button's size will expand to fit the child widget, if necessary.
///
/// MaterialButtons whose [onPressed] and [onLongPress] callbacks are null will be disabled. To have
/// an enabled button, make sure to pass a non-null value for [onPressed] or [onLongPress].
///
/// To create a button directly, without inheriting theme defaults, use
/// [RawMaterialButton].
///
/// If you want an ink-splash effect for taps, but don't want to use a button,
/// consider using [InkWell] directly.
///
/// See also:
///
/// * [IconButton], to create buttons that contain icons rather than text.
class MaterialButton extends StatelessWidget {
/// Creates a Material Design button.
///
/// To create a custom Material button consider using [TextButton],
/// [ElevatedButton], or [OutlinedButton].
///
/// The [elevation], [hoverElevation], [focusElevation], [highlightElevation],
/// and [disabledElevation] arguments must be non-negative, if specified.
const MaterialButton({
super.key,
required this.onPressed,
this.onLongPress,
this.onHighlightChanged,
this.mouseCursor,
this.textTheme,
this.textColor,
this.disabledTextColor,
this.color,
this.disabledColor,
this.focusColor,
this.hoverColor,
this.highlightColor,
this.splashColor,
this.colorBrightness,
this.elevation,
this.focusElevation,
this.hoverElevation,
this.highlightElevation,
this.disabledElevation,
this.padding,
this.visualDensity,
this.shape,
this.clipBehavior = Clip.none,
this.focusNode,
this.autofocus = false,
this.materialTapTargetSize,
this.animationDuration,
this.minWidth,
this.height,
this.enableFeedback = true,
this.child,
}) : assert(elevation == null || elevation >= 0.0),
assert(focusElevation == null || focusElevation >= 0.0),
assert(hoverElevation == null || hoverElevation >= 0.0),
assert(highlightElevation == null || highlightElevation >= 0.0),
assert(disabledElevation == null || disabledElevation >= 0.0);
/// The callback that is called when the button is tapped or otherwise activated.
///
/// If this callback and [onLongPress] are null, then the button will be disabled.
///
/// See also:
///
/// * [enabled], which is true if the button is enabled.
final VoidCallback? onPressed;
/// The callback that is called when the button is long-pressed.
///
/// If this callback and [onPressed] are null, then the button will be disabled.
///
/// See also:
///
/// * [enabled], which is true if the button is enabled.
final VoidCallback? onLongPress;
/// Called by the underlying [InkWell] widget's [InkWell.onHighlightChanged]
/// callback.
///
/// If [onPressed] changes from null to non-null while a gesture is ongoing,
/// this can fire during the build phase (in which case calling
/// [State.setState] is not allowed).
final ValueChanged<bool>? onHighlightChanged;
/// {@macro flutter.material.RawMaterialButton.mouseCursor}
///
/// If this property is null, [MaterialStateMouseCursor.clickable] will be used.
final MouseCursor? mouseCursor;
/// Defines the button's base colors, and the defaults for the button's minimum
/// size, internal padding, and shape.
///
/// Defaults to `ButtonTheme.of(context).textTheme`.
final ButtonTextTheme? textTheme;
/// The color to use for this button's text.
///
/// The button's [Material.textStyle] will be the current theme's button text
/// style, [TextTheme.labelLarge] of [ThemeData.textTheme], configured with this
/// color.
///
/// The default text color depends on the button theme's text theme,
/// [ButtonThemeData.textTheme].
///
/// If [textColor] is a [MaterialStateProperty<Color>], [disabledTextColor]
/// will be ignored.
///
/// See also:
///
/// * [disabledTextColor], the text color to use when the button has been
/// disabled.
final Color? textColor;
/// The color to use for this button's text when the button is disabled.
///
/// The button's [Material.textStyle] will be the current theme's button text
/// style, [TextTheme.labelLarge] of [ThemeData.textTheme], configured with this
/// color.
///
/// The default value is the theme's disabled color,
/// [ThemeData.disabledColor].
///
/// If [textColor] is a [MaterialStateProperty<Color>], [disabledTextColor]
/// will be ignored.
///
/// See also:
///
/// * [textColor] - The color to use for this button's text when the button is [enabled].
final Color? disabledTextColor;
/// The button's fill color, displayed by its [Material], while it
/// is in its default (unpressed, [enabled]) state.
///
/// See also:
///
/// * [disabledColor] - the fill color of the button when the button is disabled.
final Color? color;
/// The fill color of the button when the button is disabled.
///
/// The default value of this color is the theme's disabled color,
/// [ThemeData.disabledColor].
///
/// See also:
///
/// * [color] - the fill color of the button when the button is [enabled].
final Color? disabledColor;
/// The splash color of the button's [InkWell].
///
/// The ink splash indicates that the button has been touched. It
/// appears on top of the button's child and spreads in an expanding
/// circle beginning where the touch occurred.
///
/// The default splash color is the current theme's splash color,
/// [ThemeData.splashColor].
///
/// The appearance of the splash can be configured with the theme's splash
/// factory, [ThemeData.splashFactory].
final Color? splashColor;
/// The fill color of the button's [Material] when it has the input focus.
///
/// The button changed focus color when the button has the input focus. It
/// appears behind the button's child.
final Color? focusColor;
/// The fill color of the button's [Material] when a pointer is hovering over
/// it.
///
/// The button changes fill color when a pointer is hovering over the button.
/// It appears behind the button's child.
final Color? hoverColor;
/// The highlight color of the button's [InkWell].
///
/// The highlight indicates that the button is actively being pressed. It
/// appears on top of the button's child and quickly spreads to fill
/// the button, and then fades out.
///
/// If [textTheme] is [ButtonTextTheme.primary], the default highlight color is
/// transparent (in other words the highlight doesn't appear). Otherwise it's
/// the current theme's highlight color, [ThemeData.highlightColor].
final Color? highlightColor;
/// The z-coordinate at which to place this button relative to its parent.
///
/// This controls the size of the shadow below the raised button.
///
/// Defaults to 2, the appropriate elevation for raised buttons. The value
/// is always non-negative.
///
/// See also:
///
/// * [TextButton], a button with no elevation or fill color.
/// * [focusElevation], the elevation when the button is focused.
/// * [hoverElevation], the elevation when a pointer is hovering over the
/// button.
/// * [disabledElevation], the elevation when the button is disabled.
/// * [highlightElevation], the elevation when the button is pressed.
final double? elevation;
/// The elevation for the button's [Material] when the button
/// is [enabled] and a pointer is hovering over it.
///
/// Defaults to 4.0. The value is always non-negative.
///
/// See also:
///
/// * [elevation], the default elevation.
/// * [focusElevation], the elevation when the button is focused.
/// * [disabledElevation], the elevation when the button is disabled.
/// * [highlightElevation], the elevation when the button is pressed.
final double? hoverElevation;
/// The elevation for the button's [Material] when the button
/// is [enabled] and has the input focus.
///
/// Defaults to 4.0. The value is always non-negative.
///
/// See also:
///
/// * [elevation], the default elevation.
/// * [hoverElevation], the elevation when a pointer is hovering over the
/// button.
/// * [disabledElevation], the elevation when the button is disabled.
/// * [highlightElevation], the elevation when the button is pressed.
final double? focusElevation;
/// The elevation for the button's [Material] relative to its parent when the
/// button is [enabled] and pressed.
///
/// This controls the size of the shadow below the button. When a tap
/// down gesture occurs within the button, its [InkWell] displays a
/// [highlightColor] "highlight".
///
/// Defaults to 8.0. The value is always non-negative.
///
/// See also:
///
/// * [elevation], the default elevation.
/// * [focusElevation], the elevation when the button is focused.
/// * [hoverElevation], the elevation when a pointer is hovering over the
/// button.
/// * [disabledElevation], the elevation when the button is disabled.
final double? highlightElevation;
/// The elevation for the button's [Material] relative to its parent when the
/// button is not [enabled].
///
/// Defaults to 0.0. The value is always non-negative.
///
/// See also:
///
/// * [elevation], the default elevation.
/// * [highlightElevation], the elevation when the button is pressed.
final double? disabledElevation;
/// The theme brightness to use for this button.
///
/// Defaults to the theme's brightness in [ThemeData.brightness]. Setting
/// this value determines the button text's colors based on
/// [ButtonThemeData.getTextColor].
///
/// See also:
///
/// * [ButtonTextTheme], uses [Brightness] to determine text color.
final Brightness? colorBrightness;
/// The button's label.
///
/// Often a [Text] widget in all caps.
final Widget? child;
/// Whether the button is enabled or disabled.
///
/// Buttons are disabled by default. To enable a button, set its [onPressed]
/// or [onLongPress] properties to a non-null value.
bool get enabled => onPressed != null || onLongPress != null;
/// The internal padding for the button's [child].
///
/// Defaults to the value from the current [ButtonTheme],
/// [ButtonThemeData.padding].
final EdgeInsetsGeometry? padding;
/// Defines how compact the button'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;
/// The shape of the button's [Material].
///
/// The button's highlight and splash are clipped to this shape. If the
/// button has an elevation, then its drop shadow is defined by this
/// shape as well.
///
/// Defaults to the value from the current [ButtonTheme],
/// [ButtonThemeData.shape].
final ShapeBorder? shape;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// {@macro flutter.widgets.Focus.autofocus}
final bool autofocus;
/// Defines the duration of animated changes for [shape] and [elevation].
///
/// The default value is [kThemeChangeDuration].
final Duration? animationDuration;
/// Configures the minimum size of the tap target.
///
/// Defaults to [ThemeData.materialTapTargetSize].
///
/// See also:
///
/// * [MaterialTapTargetSize], for a description of how this affects tap targets.
final MaterialTapTargetSize? materialTapTargetSize;
/// The smallest horizontal extent that the button will occupy.
///
/// Defaults to the value from the current [ButtonTheme].
final double? minWidth;
/// The vertical extent of the button.
///
/// Defaults to the value from the current [ButtonTheme].
final double? height;
/// 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.
///
/// See also:
///
/// * [Feedback] for providing platform-specific feedback to certain actions.
final bool enableFeedback;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final ButtonThemeData buttonTheme = ButtonTheme.of(context);
return RawMaterialButton(
onPressed: onPressed,
onLongPress: onLongPress,
enableFeedback: enableFeedback,
onHighlightChanged: onHighlightChanged,
mouseCursor: mouseCursor,
fillColor: buttonTheme.getFillColor(this),
textStyle: theme.textTheme.labelLarge!.copyWith(color: buttonTheme.getTextColor(this)),
focusColor: focusColor ?? buttonTheme.getFocusColor(this),
hoverColor: hoverColor ?? buttonTheme.getHoverColor(this),
highlightColor: highlightColor ?? theme.highlightColor,
splashColor: splashColor ?? theme.splashColor,
elevation: buttonTheme.getElevation(this),
focusElevation: buttonTheme.getFocusElevation(this),
hoverElevation: buttonTheme.getHoverElevation(this),
highlightElevation: buttonTheme.getHighlightElevation(this),
padding: buttonTheme.getPadding(this),
visualDensity: visualDensity ?? theme.visualDensity,
constraints: buttonTheme.getConstraints(this).copyWith(
minWidth: minWidth,
minHeight: height,
),
shape: buttonTheme.getShape(this),
clipBehavior: clipBehavior,
focusNode: focusNode,
autofocus: autofocus,
animationDuration: buttonTheme.getAnimationDuration(this),
materialTapTargetSize: materialTapTargetSize ?? theme.materialTapTargetSize,
disabledElevation: disabledElevation ?? 0.0,
child: child,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('enabled', value: enabled, ifFalse: 'disabled'));
properties.add(DiagnosticsProperty<ButtonTextTheme>('textTheme', textTheme, defaultValue: null));
properties.add(ColorProperty('textColor', textColor, defaultValue: null));
properties.add(ColorProperty('disabledTextColor', disabledTextColor, defaultValue: null));
properties.add(ColorProperty('color', color, defaultValue: null));
properties.add(ColorProperty('disabledColor', disabledColor, defaultValue: null));
properties.add(ColorProperty('focusColor', focusColor, defaultValue: null));
properties.add(ColorProperty('hoverColor', hoverColor, defaultValue: null));
properties.add(ColorProperty('highlightColor', highlightColor, defaultValue: null));
properties.add(ColorProperty('splashColor', splashColor, defaultValue: null));
properties.add(DiagnosticsProperty<Brightness>('colorBrightness', colorBrightness, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
properties.add(DiagnosticsProperty<VisualDensity>('visualDensity', visualDensity, defaultValue: null));
properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null));
properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialTapTargetSize>('materialTapTargetSize', materialTapTargetSize, defaultValue: null));
}
}
| flutter/packages/flutter/lib/src/material/material_button.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/material_button.dart",
"repo_id": "flutter",
"token_count": 4860
} | 634 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'navigation_rail.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// Defines default property values for descendant [NavigationRail]
/// widgets.
///
/// Descendant widgets obtain the current [NavigationRailThemeData] object
/// using `NavigationRailTheme.of(context)`. Instances of
/// [NavigationRailThemeData] can be customized with
/// [NavigationRailThemeData.copyWith].
///
/// Typically a [NavigationRailThemeData] is specified as part of the
/// overall [Theme] with [ThemeData.navigationRailTheme].
///
/// All [NavigationRailThemeData] properties are `null` by default.
/// When null, the [NavigationRail] will use the values from [ThemeData]
/// if they exist, otherwise it will provide its own defaults based on the
/// overall [Theme]'s textTheme and colorScheme. See the individual
/// [NavigationRail] properties for details.
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
@immutable
class NavigationRailThemeData with Diagnosticable {
/// Creates a theme that can be used for [ThemeData.navigationRailTheme].
const NavigationRailThemeData({
this.backgroundColor,
this.elevation,
this.unselectedLabelTextStyle,
this.selectedLabelTextStyle,
this.unselectedIconTheme,
this.selectedIconTheme,
this.groupAlignment,
this.labelType,
this.useIndicator,
this.indicatorColor,
this.indicatorShape,
this.minWidth,
this.minExtendedWidth,
});
/// Color to be used for the [NavigationRail]'s background.
final Color? backgroundColor;
/// The z-coordinate to be used for the [NavigationRail]'s elevation.
final double? elevation;
/// The style to merge with the default text style for
/// [NavigationRailDestination] labels, when the destination is not selected.
final TextStyle? unselectedLabelTextStyle;
/// The style to merge with the default text style for
/// [NavigationRailDestination] labels, when the destination is selected.
final TextStyle? selectedLabelTextStyle;
/// The theme to merge with the default icon theme for
/// [NavigationRailDestination] icons, when the destination is not selected.
final IconThemeData? unselectedIconTheme;
/// The theme to merge with the default icon theme for
/// [NavigationRailDestination] icons, when the destination is selected.
final IconThemeData? selectedIconTheme;
/// The alignment for the [NavigationRailDestination]s as they are positioned
/// within the [NavigationRail].
final double? groupAlignment;
/// The type that defines the layout and behavior of the labels in the
/// [NavigationRail].
final NavigationRailLabelType? labelType;
/// Whether or not the selected [NavigationRailDestination] should include a
/// [NavigationIndicator].
final bool? useIndicator;
/// Overrides the default value of [NavigationRail]'s selection indicator color,
/// when [useIndicator] is true.
final Color? indicatorColor;
/// Overrides the default shape of the [NavigationRail]'s selection indicator.
final ShapeBorder? indicatorShape;
/// Overrides the default value of [NavigationRail]'s minimum width when it
/// is not extended.
final double? minWidth;
/// Overrides the default value of [NavigationRail]'s minimum width when it
/// is extended.
final double? minExtendedWidth;
/// Creates a copy of this object with the given fields replaced with the
/// new values.
NavigationRailThemeData copyWith({
Color? backgroundColor,
double? elevation,
TextStyle? unselectedLabelTextStyle,
TextStyle? selectedLabelTextStyle,
IconThemeData? unselectedIconTheme,
IconThemeData? selectedIconTheme,
double? groupAlignment,
NavigationRailLabelType? labelType,
bool? useIndicator,
Color? indicatorColor,
ShapeBorder? indicatorShape,
double? minWidth,
double? minExtendedWidth,
}) {
return NavigationRailThemeData(
backgroundColor: backgroundColor ?? this.backgroundColor,
elevation: elevation ?? this.elevation,
unselectedLabelTextStyle: unselectedLabelTextStyle ?? this.unselectedLabelTextStyle,
selectedLabelTextStyle: selectedLabelTextStyle ?? this.selectedLabelTextStyle,
unselectedIconTheme: unselectedIconTheme ?? this.unselectedIconTheme,
selectedIconTheme: selectedIconTheme ?? this.selectedIconTheme,
groupAlignment: groupAlignment ?? this.groupAlignment,
labelType: labelType ?? this.labelType,
useIndicator: useIndicator ?? this.useIndicator,
indicatorColor: indicatorColor ?? this.indicatorColor,
indicatorShape: indicatorShape ?? this.indicatorShape,
minWidth: minWidth ?? this.minWidth,
minExtendedWidth: minExtendedWidth ?? this.minExtendedWidth,
);
}
/// Linearly interpolate between two navigation rail themes.
///
/// If both arguments are null then null is returned.
///
/// {@macro dart.ui.shadow.lerp}
static NavigationRailThemeData? lerp(NavigationRailThemeData? a, NavigationRailThemeData? b, double t) {
if (identical(a, b)) {
return a;
}
return NavigationRailThemeData(
backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t),
elevation: lerpDouble(a?.elevation, b?.elevation, t),
unselectedLabelTextStyle: TextStyle.lerp(a?.unselectedLabelTextStyle, b?.unselectedLabelTextStyle, t),
selectedLabelTextStyle: TextStyle.lerp(a?.selectedLabelTextStyle, b?.selectedLabelTextStyle, t),
unselectedIconTheme: a?.unselectedIconTheme == null && b?.unselectedIconTheme == null
? null : IconThemeData.lerp(a?.unselectedIconTheme, b?.unselectedIconTheme, t),
selectedIconTheme: a?.selectedIconTheme == null && b?.selectedIconTheme == null
? null : IconThemeData.lerp(a?.selectedIconTheme, b?.selectedIconTheme, t),
groupAlignment: lerpDouble(a?.groupAlignment, b?.groupAlignment, t),
labelType: t < 0.5 ? a?.labelType : b?.labelType,
useIndicator: t < 0.5 ? a?.useIndicator : b?.useIndicator,
indicatorColor: Color.lerp(a?.indicatorColor, b?.indicatorColor, t),
indicatorShape: ShapeBorder.lerp(a?.indicatorShape, b?.indicatorShape, t),
minWidth: lerpDouble(a?.minWidth, b?.minWidth, t),
minExtendedWidth: lerpDouble(a?.minExtendedWidth, b?.minExtendedWidth, t),
);
}
@override
int get hashCode => Object.hash(
backgroundColor,
elevation,
unselectedLabelTextStyle,
selectedLabelTextStyle,
unselectedIconTheme,
selectedIconTheme,
groupAlignment,
labelType,
useIndicator,
indicatorColor,
indicatorShape,
minWidth,
minExtendedWidth,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is NavigationRailThemeData
&& other.backgroundColor == backgroundColor
&& other.elevation == elevation
&& other.unselectedLabelTextStyle == unselectedLabelTextStyle
&& other.selectedLabelTextStyle == selectedLabelTextStyle
&& other.unselectedIconTheme == unselectedIconTheme
&& other.selectedIconTheme == selectedIconTheme
&& other.groupAlignment == groupAlignment
&& other.labelType == labelType
&& other.useIndicator == useIndicator
&& other.indicatorColor == indicatorColor
&& other.indicatorShape == indicatorShape
&& other.minWidth == minWidth
&& other.minExtendedWidth == minExtendedWidth;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
const NavigationRailThemeData defaultData = NavigationRailThemeData();
properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: defaultData.backgroundColor));
properties.add(DoubleProperty('elevation', elevation, defaultValue: defaultData.elevation));
properties.add(DiagnosticsProperty<TextStyle>('unselectedLabelTextStyle', unselectedLabelTextStyle, defaultValue: defaultData.unselectedLabelTextStyle));
properties.add(DiagnosticsProperty<TextStyle>('selectedLabelTextStyle', selectedLabelTextStyle, defaultValue: defaultData.selectedLabelTextStyle));
properties.add(DiagnosticsProperty<IconThemeData>('unselectedIconTheme', unselectedIconTheme, defaultValue: defaultData.unselectedIconTheme));
properties.add(DiagnosticsProperty<IconThemeData>('selectedIconTheme', selectedIconTheme, defaultValue: defaultData.selectedIconTheme));
properties.add(DoubleProperty('groupAlignment', groupAlignment, defaultValue: defaultData.groupAlignment));
properties.add(DiagnosticsProperty<NavigationRailLabelType>('labelType', labelType, defaultValue: defaultData.labelType));
properties.add(DiagnosticsProperty<bool>('useIndicator', useIndicator, defaultValue: defaultData.useIndicator));
properties.add(ColorProperty('indicatorColor', indicatorColor, defaultValue: defaultData.indicatorColor));
properties.add(DiagnosticsProperty<ShapeBorder>('indicatorShape', indicatorShape, defaultValue: null));
properties.add(DoubleProperty('minWidth', minWidth, defaultValue: defaultData.minWidth));
properties.add(DoubleProperty('minExtendedWidth', minExtendedWidth, defaultValue: defaultData.minExtendedWidth));
}
}
/// An inherited widget that defines visual properties for [NavigationRail]s and
/// [NavigationRailDestination]s in this widget's subtree.
///
/// Values specified here are used for [NavigationRail] properties that are not
/// given an explicit non-null value.
class NavigationRailTheme extends InheritedTheme {
/// Creates a navigation rail theme that controls the
/// [NavigationRailThemeData] properties for a [NavigationRail].
const NavigationRailTheme({
super.key,
required this.data,
required super.child,
});
/// Specifies the background color, elevation, label text style, icon theme,
/// group alignment, and label type and border values for descendant
/// [NavigationRail] widgets.
final NavigationRailThemeData data;
/// The closest instance of this class that encloses the given context.
///
/// If there is no enclosing [NavigationRailTheme] widget, then
/// [ThemeData.navigationRailTheme] is used.
///
/// Typical usage is as follows:
///
/// ```dart
/// NavigationRailThemeData theme = NavigationRailTheme.of(context);
/// ```
static NavigationRailThemeData of(BuildContext context) {
final NavigationRailTheme? navigationRailTheme = context.dependOnInheritedWidgetOfExactType<NavigationRailTheme>();
return navigationRailTheme?.data ?? Theme.of(context).navigationRailTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return NavigationRailTheme(data: data, child: child);
}
@override
bool updateShouldNotify(NavigationRailTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/navigation_rail_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/navigation_rail_theme.dart",
"repo_id": "flutter",
"token_count": 3407
} | 635 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' show lerpDouble;
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'debug.dart';
import 'icons.dart';
import 'material.dart';
import 'theme.dart';
/// A list whose items the user can interactively reorder by dragging.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=3fB1mxOsqJE}
///
/// This sample shows by dragging the user can reorder the items of the list.
/// The [onReorder] parameter is required and will be called when a child
/// widget is dragged to a new position.
///
/// {@tool dartpad}
///
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.0.dart **
/// {@end-tool}
///
/// By default, on [TargetPlatformVariant.desktop] platforms each item will
/// have a drag handle added on top of it that will allow the user to grab it
/// to move the item. On [TargetPlatformVariant.mobile], no drag handle will be
/// added, but when the user long presses anywhere on the item it will start
/// moving the item. Displaying drag handles can be controlled with
/// [ReorderableListView.buildDefaultDragHandles].
///
/// All list items must have a key.
///
/// This example demonstrates using the [ReorderableListView.proxyDecorator] callback
/// to customize the appearance of a list item while it's being dragged.
///
/// {@tool dartpad}
/// While a drag is underway, the widget returned by the [ReorderableListView.proxyDecorator]
/// callback serves as a "proxy" (a substitute) for the item in the list. The proxy is
/// created with the original list item as its child. The [ReorderableListView.proxyDecorator]
/// callback in this example is similar to the default one except that it changes the
/// proxy item's background color.
///
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.1.dart **
/// {@end-tool}
///
/// This example demonstrates using the [ReorderableListView.proxyDecorator] callback to
/// customize the appearance of a [Card] while it's being dragged.
///
/// {@tool dartpad}
/// The default [proxyDecorator] wraps the dragged item in a [Material] widget and animates
/// its elevation. This example demonstrates how to use the [ReorderableListView.proxyDecorator]
/// callback to update the dragged card elevation without inserted a new [Material] widget.
///
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.2.dart **
/// {@end-tool}
class ReorderableListView extends StatefulWidget {
/// Creates a reorderable list from a pre-built list of widgets.
///
/// This constructor is appropriate for lists with a small number of
/// children because constructing the [List] requires doing work for every
/// child that could possibly be displayed in the list view instead of just
/// those children that are actually visible.
///
/// See also:
///
/// * [ReorderableListView.builder], which allows you to build a reorderable
/// list where the items are built as needed when scrolling the list.
ReorderableListView({
super.key,
required List<Widget> children,
required this.onReorder,
this.onReorderStart,
this.onReorderEnd,
this.itemExtent,
this.itemExtentBuilder,
this.prototypeItem,
this.proxyDecorator,
this.buildDefaultDragHandles = true,
this.padding,
this.header,
this.footer,
this.scrollDirection = Axis.vertical,
this.reverse = false,
this.scrollController,
this.primary,
this.physics,
this.shrinkWrap = false,
this.anchor = 0.0,
this.cacheExtent,
this.dragStartBehavior = DragStartBehavior.start,
this.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
this.restorationId,
this.clipBehavior = Clip.hardEdge,
this.autoScrollerVelocityScalar,
}) : assert(
(itemExtent == null && prototypeItem == null) ||
(itemExtent == null && itemExtentBuilder == null) ||
(prototypeItem == null && itemExtentBuilder == null),
'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.',
),
assert(
children.every((Widget w) => w.key != null),
'All children of this widget must have a key.',
),
itemBuilder = ((BuildContext context, int index) => children[index]),
itemCount = children.length;
/// Creates a reorderable list from widget items that are created on demand.
///
/// This constructor is appropriate for list views with a large number of
/// children because the builder is called only for those children
/// that are actually visible.
///
/// The `itemBuilder` callback will be called only with indices greater than
/// or equal to zero and less than `itemCount`.
///
/// The `itemBuilder` should always return a non-null widget, and actually
/// create the widget instances when called. Avoid using a builder that
/// returns a previously-constructed widget; if the list view's children are
/// created in advance, or all at once when the [ReorderableListView] itself
/// is created, it is more efficient to use the [ReorderableListView]
/// constructor. Even more efficient, however, is to create the instances
/// on demand using this constructor's `itemBuilder` callback.
///
/// This example creates a list using the
/// [ReorderableListView.builder] constructor. Using the [IndexedWidgetBuilder], The
/// list items are built lazily on demand.
/// {@tool dartpad}
///
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.reorderable_list_view_builder.0.dart **
/// {@end-tool}
/// See also:
///
/// * [ReorderableListView], which allows you to build a reorderable
/// list with all the items passed into the constructor.
const ReorderableListView.builder({
super.key,
required this.itemBuilder,
required this.itemCount,
required this.onReorder,
this.onReorderStart,
this.onReorderEnd,
this.itemExtent,
this.itemExtentBuilder,
this.prototypeItem,
this.proxyDecorator,
this.buildDefaultDragHandles = true,
this.padding,
this.header,
this.footer,
this.scrollDirection = Axis.vertical,
this.reverse = false,
this.scrollController,
this.primary,
this.physics,
this.shrinkWrap = false,
this.anchor = 0.0,
this.cacheExtent,
this.dragStartBehavior = DragStartBehavior.start,
this.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
this.restorationId,
this.clipBehavior = Clip.hardEdge,
this.autoScrollerVelocityScalar,
}) : assert(itemCount >= 0),
assert(
(itemExtent == null && prototypeItem == null) ||
(itemExtent == null && itemExtentBuilder == null) ||
(prototypeItem == null && itemExtentBuilder == null),
'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.',
);
/// {@macro flutter.widgets.reorderable_list.itemBuilder}
final IndexedWidgetBuilder itemBuilder;
/// {@macro flutter.widgets.reorderable_list.itemCount}
final int itemCount;
/// {@macro flutter.widgets.reorderable_list.onReorder}
final ReorderCallback onReorder;
/// {@macro flutter.widgets.reorderable_list.onReorderStart}
final void Function(int index)? onReorderStart;
/// {@macro flutter.widgets.reorderable_list.onReorderEnd}
final void Function(int index)? onReorderEnd;
/// {@macro flutter.widgets.reorderable_list.proxyDecorator}
final ReorderItemProxyDecorator? proxyDecorator;
/// If true: on desktop platforms, a drag handle is stacked over the
/// center of each item's trailing edge; on mobile platforms, a long
/// press anywhere on the item starts a drag.
///
/// The default desktop drag handle is just an [Icons.drag_handle]
/// wrapped by a [ReorderableDragStartListener]. On mobile
/// platforms, the entire item is wrapped with a
/// [ReorderableDelayedDragStartListener].
///
/// To change the appearance or the layout of the drag handles, make
/// this parameter false and wrap each list item, or a widget within
/// each list item, with [ReorderableDragStartListener] or
/// [ReorderableDelayedDragStartListener], or a custom subclass
/// of [ReorderableDragStartListener].
///
/// The following sample specifies `buildDefaultDragHandles: false`, and
/// uses a [Card] at the leading edge of each item for the item's drag handle.
///
/// {@tool dartpad}
///
///
/// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0.dart **
///{@end-tool}
final bool buildDefaultDragHandles;
/// {@macro flutter.widgets.reorderable_list.padding}
final EdgeInsets? padding;
/// A non-reorderable header item to show before the items of the list.
///
/// If null, no header will appear before the list.
final Widget? header;
/// A non-reorderable footer item to show after the items of the list.
///
/// If null, no footer will appear after the list.
final Widget? footer;
/// {@macro flutter.widgets.scroll_view.scrollDirection}
final Axis scrollDirection;
/// {@macro flutter.widgets.scroll_view.reverse}
final bool reverse;
/// {@macro flutter.widgets.scroll_view.controller}
final ScrollController? scrollController;
/// {@macro flutter.widgets.scroll_view.primary}
/// Defaults to true when [scrollDirection] is [Axis.vertical] and
/// [scrollController] is null.
final bool? primary;
/// {@macro flutter.widgets.scroll_view.physics}
final ScrollPhysics? physics;
/// {@macro flutter.widgets.scroll_view.shrinkWrap}
final bool shrinkWrap;
/// {@macro flutter.widgets.scroll_view.anchor}
final double anchor;
/// {@macro flutter.rendering.RenderViewportBase.cacheExtent}
final double? cacheExtent;
/// {@macro flutter.widgets.scrollable.dragStartBehavior}
final DragStartBehavior dragStartBehavior;
/// {@macro flutter.widgets.scroll_view.keyboardDismissBehavior}
///
/// The default is [ScrollViewKeyboardDismissBehavior.manual]
final ScrollViewKeyboardDismissBehavior keyboardDismissBehavior;
/// {@macro flutter.widgets.scrollable.restorationId}
final String? restorationId;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// {@macro flutter.widgets.list_view.itemExtent}
final double? itemExtent;
/// {@macro flutter.widgets.list_view.itemExtentBuilder}
final ItemExtentBuilder? itemExtentBuilder;
/// {@macro flutter.widgets.list_view.prototypeItem}
final Widget? prototypeItem;
/// {@macro flutter.widgets.EdgeDraggingAutoScroller.velocityScalar}
///
/// {@macro flutter.widgets.SliverReorderableList.autoScrollerVelocityScalar.default}
final double? autoScrollerVelocityScalar;
@override
State<ReorderableListView> createState() => _ReorderableListViewState();
}
class _ReorderableListViewState extends State<ReorderableListView> {
Widget _itemBuilder(BuildContext context, int index) {
final Widget item = widget.itemBuilder(context, index);
assert(() {
if (item.key == null) {
throw FlutterError(
'Every item of ReorderableListView must have a key.',
);
}
return true;
}());
final Key itemGlobalKey = _ReorderableListViewChildGlobalKey(item.key!, this);
if (widget.buildDefaultDragHandles) {
switch (Theme.of(context).platform) {
case TargetPlatform.linux:
case TargetPlatform.windows:
case TargetPlatform.macOS:
switch (widget.scrollDirection) {
case Axis.horizontal:
return Stack(
key: itemGlobalKey,
children: <Widget>[
item,
Positioned.directional(
textDirection: Directionality.of(context),
start: 0,
end: 0,
bottom: 8,
child: Align(
alignment: AlignmentDirectional.bottomCenter,
child: ReorderableDragStartListener(
index: index,
child: const Icon(Icons.drag_handle),
),
),
),
],
);
case Axis.vertical:
return Stack(
key: itemGlobalKey,
children: <Widget>[
item,
Positioned.directional(
textDirection: Directionality.of(context),
top: 0,
bottom: 0,
end: 8,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: ReorderableDragStartListener(
index: index,
child: const Icon(Icons.drag_handle),
),
),
),
],
);
}
case TargetPlatform.iOS:
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return ReorderableDelayedDragStartListener(
key: itemGlobalKey,
index: index,
child: item,
);
}
}
return KeyedSubtree(
key: itemGlobalKey,
child: item,
);
}
Widget _proxyDecorator(Widget child, int index, Animation<double> animation) {
return AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget? child) {
final double animValue = Curves.easeInOut.transform(animation.value);
final double elevation = lerpDouble(0, 6, animValue)!;
return Material(
elevation: elevation,
child: child,
);
},
child: child,
);
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
assert(debugCheckHasOverlay(context));
// If there is a header or footer we can't just apply the padding to the list,
// so we break it up into padding for the header, footer and padding for the list.
final EdgeInsets padding = widget.padding ?? EdgeInsets.zero;
late final EdgeInsets headerPadding;
late final EdgeInsets footerPadding;
late final EdgeInsets listPadding;
if (widget.header == null && widget.footer == null) {
headerPadding = EdgeInsets.zero;
footerPadding = EdgeInsets.zero;
listPadding = padding;
} else if (widget.header != null || widget.footer != null) {
switch (widget.scrollDirection) {
case Axis.horizontal:
if (widget.reverse) {
headerPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom);
listPadding = EdgeInsets.fromLTRB(widget.footer != null ? 0 : padding.left, padding.top, widget.header != null ? 0 : padding.right, padding.bottom);
footerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom);
} else {
headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom);
listPadding = EdgeInsets.fromLTRB(widget.header != null ? 0 : padding.left, padding.top, widget.footer != null ? 0 : padding.right, padding.bottom);
footerPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom);
}
case Axis.vertical:
if (widget.reverse) {
headerPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom);
listPadding = EdgeInsets.fromLTRB(padding.left, widget.footer != null ? 0 : padding.top, padding.right, widget.header != null ? 0 : padding.bottom);
footerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0);
} else {
headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0);
listPadding = EdgeInsets.fromLTRB(padding.left, widget.header != null ? 0 : padding.top, padding.right, widget.footer != null ? 0 : padding.bottom);
footerPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom);
}
}
}
return CustomScrollView(
scrollDirection: widget.scrollDirection,
reverse: widget.reverse,
controller: widget.scrollController,
primary: widget.primary,
physics: widget.physics,
shrinkWrap: widget.shrinkWrap,
anchor: widget.anchor,
cacheExtent: widget.cacheExtent,
dragStartBehavior: widget.dragStartBehavior,
keyboardDismissBehavior: widget.keyboardDismissBehavior,
restorationId: widget.restorationId,
clipBehavior: widget.clipBehavior,
slivers: <Widget>[
if (widget.header != null)
SliverPadding(
padding: headerPadding,
sliver: SliverToBoxAdapter(child: widget.header),
),
SliverPadding(
padding: listPadding,
sliver: SliverReorderableList(
itemBuilder: _itemBuilder,
itemExtent: widget.itemExtent,
itemExtentBuilder: widget.itemExtentBuilder,
prototypeItem: widget.prototypeItem,
itemCount: widget.itemCount,
onReorder: widget.onReorder,
onReorderStart: widget.onReorderStart,
onReorderEnd: widget.onReorderEnd,
proxyDecorator: widget.proxyDecorator ?? _proxyDecorator,
autoScrollerVelocityScalar: widget.autoScrollerVelocityScalar,
),
),
if (widget.footer != null)
SliverPadding(
padding: footerPadding,
sliver: SliverToBoxAdapter(child: widget.footer),
),
],
);
}
}
// A global key that takes its identity from the object and uses a value of a
// particular type to identify itself.
//
// The difference with GlobalObjectKey is that it uses [==] instead of [identical]
// of the objects used to generate widgets.
@optionalTypeArgs
class _ReorderableListViewChildGlobalKey extends GlobalObjectKey {
const _ReorderableListViewChildGlobalKey(this.subKey, this.state) : super(subKey);
final Key subKey;
final State state;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is _ReorderableListViewChildGlobalKey
&& other.subKey == subKey
&& other.state == state;
}
@override
int get hashCode => Object.hash(subKey, state);
}
| flutter/packages/flutter/lib/src/material/reorderable_list.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/reorderable_list.dart",
"repo_id": "flutter",
"token_count": 6967
} | 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/rendering.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'icon_button.dart';
import 'icons.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'material_state.dart';
import 'scaffold.dart';
import 'snack_bar_theme.dart';
import 'text_button.dart';
import 'text_button_theme.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
const double _singleLineVerticalPadding = 14.0;
const Duration _snackBarTransitionDuration = Duration(milliseconds: 250);
const Duration _snackBarDisplayDuration = Duration(milliseconds: 4000);
const Curve _snackBarHeightCurve = Curves.fastOutSlowIn;
const Curve _snackBarM3HeightCurve = Curves.easeInOutQuart;
const Curve _snackBarFadeInCurve = Interval(0.4, 1.0);
const Curve _snackBarM3FadeInCurve = Interval(0.4, 0.6, curve: Curves.easeInCirc);
const Curve _snackBarFadeOutCurve = Interval(0.72, 1.0, curve: Curves.fastOutSlowIn);
/// Specify how a [SnackBar] was closed.
///
/// The [ScaffoldMessengerState.showSnackBar] function returns a
/// [ScaffoldFeatureController]. The value of the controller's closed property
/// is a Future that resolves to a SnackBarClosedReason. Applications that need
/// to know how a snackbar was closed can use this value.
///
/// Example:
///
/// ```dart
/// ScaffoldMessenger.of(context).showSnackBar(
/// const SnackBar(
/// content: Text('He likes me. I think he likes me.'),
/// )
/// ).closed.then((SnackBarClosedReason reason) {
/// // ...
/// });
/// ```
enum SnackBarClosedReason {
/// The snack bar was closed after the user tapped a [SnackBarAction].
action,
/// The snack bar was closed through a [SemanticsAction.dismiss].
dismiss,
/// The snack bar was closed by a user's swipe.
swipe,
/// The snack bar was closed by the [ScaffoldFeatureController] close callback
/// or by calling [ScaffoldMessengerState.hideCurrentSnackBar] directly.
hide,
/// The snack bar was closed by an call to [ScaffoldMessengerState.removeCurrentSnackBar].
remove,
/// The snack bar was closed because its timer expired.
timeout,
}
/// A button for a [SnackBar], known as an "action".
///
/// Snack bar actions are always enabled. Instead of disabling a snack bar
/// action, avoid including it in the snack bar in the first place.
///
/// Snack bar actions can only be pressed once. Subsequent presses are ignored.
///
/// See also:
///
/// * [SnackBar]
/// * <https://material.io/design/components/snackbars.html>
class SnackBarAction extends StatefulWidget {
/// Creates an action for a [SnackBar].
const SnackBarAction({
super.key,
this.textColor,
this.disabledTextColor,
this.backgroundColor,
this.disabledBackgroundColor,
required this.label,
required this.onPressed,
}) : assert(backgroundColor is! MaterialStateColor || disabledBackgroundColor == null,
'disabledBackgroundColor must not be provided when background color is '
'a MaterialStateColor');
/// The button label color. If not provided, defaults to
/// [SnackBarThemeData.actionTextColor].
///
/// If [textColor] is a [MaterialStateColor], then the text color will be
/// resolved against the set of [MaterialState]s that the action text
/// is in, thus allowing for different colors for states such as pressed,
/// hovered and others.
final Color? textColor;
/// The button background fill color. If not provided, defaults to
/// [SnackBarThemeData.actionBackgroundColor].
///
/// If [backgroundColor] is a [MaterialStateColor], then the text color will
/// be resolved against the set of [MaterialState]s that the action text is
/// in, thus allowing for different colors for the states.
final Color? backgroundColor;
/// The button disabled label color. This color is shown after the
/// [SnackBarAction] is dismissed.
final Color? disabledTextColor;
/// The button disabled background color. This color is shown after the
/// [SnackBarAction] is dismissed.
///
/// If not provided, defaults to [SnackBarThemeData.disabledActionBackgroundColor].
final Color? disabledBackgroundColor;
/// The button label.
final String label;
/// The callback to be called when the button is pressed.
///
/// This callback will be called at most once each time this action is
/// displayed in a [SnackBar].
final VoidCallback onPressed;
@override
State<SnackBarAction> createState() => _SnackBarActionState();
}
class _SnackBarActionState extends State<SnackBarAction> {
bool _haveTriggeredAction = false;
void _handlePressed() {
if (_haveTriggeredAction) {
return;
}
setState(() {
_haveTriggeredAction = true;
});
widget.onPressed();
ScaffoldMessenger.of(context).hideCurrentSnackBar(reason: SnackBarClosedReason.action);
}
@override
Widget build(BuildContext context) {
final SnackBarThemeData defaults = Theme.of(context).useMaterial3
? _SnackbarDefaultsM3(context)
: _SnackbarDefaultsM2(context);
final SnackBarThemeData snackBarTheme = Theme.of(context).snackBarTheme;
MaterialStateColor resolveForegroundColor() {
if (widget.textColor != null) {
if (widget.textColor is MaterialStateColor) {
return widget.textColor! as MaterialStateColor;
}
} else if (snackBarTheme.actionTextColor != null) {
if (snackBarTheme.actionTextColor is MaterialStateColor) {
return snackBarTheme.actionTextColor! as MaterialStateColor;
}
} else if (defaults.actionTextColor != null) {
if (defaults.actionTextColor is MaterialStateColor) {
return defaults.actionTextColor! as MaterialStateColor;
}
}
return MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return widget.disabledTextColor ??
snackBarTheme.disabledActionTextColor ??
defaults.disabledActionTextColor!;
}
return widget.textColor ??
snackBarTheme.actionTextColor ??
defaults.actionTextColor!;
});
}
MaterialStateColor? resolveBackgroundColor() {
if (widget.backgroundColor is MaterialStateColor) {
return widget.backgroundColor! as MaterialStateColor;
}
if (snackBarTheme.actionBackgroundColor is MaterialStateColor) {
return snackBarTheme.actionBackgroundColor! as MaterialStateColor;
}
return MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return widget.disabledBackgroundColor ??
snackBarTheme.disabledActionBackgroundColor ??
Colors.transparent;
}
return widget.backgroundColor ??
snackBarTheme.actionBackgroundColor ??
Colors.transparent;
});
}
return TextButton(
style: ButtonStyle(
foregroundColor: resolveForegroundColor(),
backgroundColor: resolveBackgroundColor(),
),
onPressed: _haveTriggeredAction ? null : _handlePressed,
child: Text(widget.label),
);
}
}
/// A lightweight message with an optional action which briefly displays at the
/// bottom of the screen.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=zpO6n_oZWw0}
///
/// To display a snack bar, call `ScaffoldMessenger.of(context).showSnackBar()`,
/// passing an instance of [SnackBar] that describes the message.
///
/// To control how long the [SnackBar] remains visible, specify a [duration].
///
/// A SnackBar with an action will not time out when TalkBack or VoiceOver are
/// enabled. This is controlled by [AccessibilityFeatures.accessibleNavigation].
///
/// During page transitions, the [SnackBar] will smoothly animate to its
/// location on the other page. For example if the [SnackBar.behavior] is set to
/// [SnackBarBehavior.floating] and the next page has a floating action button,
/// while the current one does not, the [SnackBar] will smoothly animate above
/// the floating action button. It also works in the case of a back gesture
/// transition.
///
/// {@tool dartpad}
/// Here is an example of a [SnackBar] with an [action] button implemented using
/// [SnackBarAction].
///
/// ** See code in examples/api/lib/material/snack_bar/snack_bar.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// Here is an example of a customized [SnackBar]. It utilizes
/// [behavior], [shape], [padding], [width], and [duration] to customize the
/// location, appearance, and the duration for which the [SnackBar] is visible.
///
/// ** See code in examples/api/lib/material/snack_bar/snack_bar.1.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example demonstrates the various [SnackBar] widget components,
/// including an optional icon, in either floating or fixed format.
///
/// ** See code in examples/api/lib/material/snack_bar/snack_bar.2.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ScaffoldMessenger.of], to obtain the current [ScaffoldMessengerState],
/// which manages the display and animation of snack bars.
/// * [ScaffoldMessengerState.showSnackBar], which displays a [SnackBar].
/// * [ScaffoldMessengerState.removeCurrentSnackBar], which abruptly hides the
/// currently displayed snack bar, if any, and allows the next to be displayed.
/// * [SnackBarAction], which is used to specify an [action] button to show
/// on the snack bar.
/// * [SnackBarThemeData], to configure the default property values for
/// [SnackBar] widgets.
/// * <https://material.io/design/components/snackbars.html>
class SnackBar extends StatefulWidget {
/// Creates a snack bar.
///
/// The [elevation] must be null or non-negative.
const SnackBar({
super.key,
required this.content,
this.backgroundColor,
this.elevation,
this.margin,
this.padding,
this.width,
this.shape,
this.hitTestBehavior,
this.behavior,
this.action,
this.actionOverflowThreshold,
this.showCloseIcon,
this.closeIconColor,
this.duration = _snackBarDisplayDuration,
this.animation,
this.onVisible,
this.dismissDirection,
this.clipBehavior = Clip.hardEdge,
}) : assert(elevation == null || elevation >= 0.0),
assert(width == null || margin == null,
'Width and margin can not be used together',
),
assert(actionOverflowThreshold == null || (actionOverflowThreshold >= 0 && actionOverflowThreshold <= 1),
'Action overflow threshold must be between 0 and 1 inclusive');
/// The primary content of the snack bar.
///
/// Typically a [Text] widget.
final Widget content;
/// The snack bar's background color.
///
/// If not specified, it will use [SnackBarThemeData.backgroundColor] of
/// [ThemeData.snackBarTheme]. If that is not specified it will default to a
/// dark variation of [ColorScheme.surface] for light themes, or
/// [ColorScheme.onSurface] for dark themes.
final Color? backgroundColor;
/// The z-coordinate at which to place the snack bar. This controls the size
/// of the shadow below the snack bar.
///
/// Defines the card's [Material.elevation].
///
/// If this property is null, then [SnackBarThemeData.elevation] of
/// [ThemeData.snackBarTheme] is used, if that is also null, the default value
/// is 6.0.
final double? elevation;
/// Empty space to surround the snack bar.
///
/// This property is only used when [behavior] is [SnackBarBehavior.floating].
/// It can not be used if [width] is specified.
///
/// If this property is null, then [SnackBarThemeData.insetPadding] of
/// [ThemeData.snackBarTheme] is used. If that is also null, then the default is
/// `EdgeInsets.fromLTRB(15.0, 5.0, 15.0, 10.0)`.
///
/// If this property is not null and [hitTestBehavior] is null, then [hitTestBehavior] default is [HitTestBehavior.deferToChild].
final EdgeInsetsGeometry? margin;
/// The amount of padding to apply to the snack bar's content and optional
/// action.
///
/// If this property is null, the default padding values are as follows:
///
/// * [content]
/// * Top and bottom paddings are 14.
/// * Left padding is 24 if [behavior] is [SnackBarBehavior.fixed],
/// 16 if [behavior] is [SnackBarBehavior.floating].
/// * Right padding is same as start padding if there is no [action],
/// otherwise 0.
/// * [action]
/// * Top and bottom paddings are 14.
/// * Left and right paddings are half of [content]'s left padding.
///
/// If this property is not null, the padding is as follows:
///
/// * [content]
/// * Left, top and bottom paddings are assigned normally.
/// * Right padding is assigned normally if there is no [action],
/// otherwise 0.
/// * [action]
/// * Left padding is replaced with half the right padding.
/// * Top and bottom paddings are assigned normally.
/// * Right padding is replaced with one and a half times the
/// right padding.
final EdgeInsetsGeometry? padding;
/// The width of the snack bar.
///
/// If width is specified, the snack bar will be centered horizontally in the
/// available space. This property is only used when [behavior] is
/// [SnackBarBehavior.floating]. It can not be used if [margin] is specified.
///
/// If this property is null, then [SnackBarThemeData.width] of
/// [ThemeData.snackBarTheme] is used. If that is null, the snack bar will
/// take up the full device width less the margin.
final double? width;
/// The shape of the snack bar's [Material].
///
/// Defines the snack bar's [Material.shape].
///
/// If this property is null then [SnackBarThemeData.shape] of
/// [ThemeData.snackBarTheme] is used. If that's null then the shape will
/// depend on the [SnackBarBehavior]. For [SnackBarBehavior.fixed], no
/// overriding shape is specified, so the [SnackBar] is rectangular. For
/// [SnackBarBehavior.floating], it uses a [RoundedRectangleBorder] with a
/// circular corner radius of 4.0.
final ShapeBorder? shape;
/// Defines how the snack bar area, including margin, will behave during hit testing.
///
/// If this property is null and [margin] is not null, then [HitTestBehavior.deferToChild] is used by default.
///
/// Please refer to [HitTestBehavior] for a detailed explanation of every behavior.
final HitTestBehavior? hitTestBehavior;
/// This defines the behavior and location of the snack bar.
///
/// Defines where a [SnackBar] should appear within a [Scaffold] and how its
/// location should be adjusted when the scaffold also includes a
/// [FloatingActionButton] or a [BottomNavigationBar]
///
/// If this property is null, then [SnackBarThemeData.behavior] of
/// [ThemeData.snackBarTheme] is used. If that is null, then the default is
/// [SnackBarBehavior.fixed].
///
/// If this value is [SnackBarBehavior.floating], the length of the bar
/// is defined by either [width] or [margin].
final SnackBarBehavior? behavior;
/// (optional) An action that the user can take based on the snack bar.
///
/// For example, the snack bar might let the user undo the operation that
/// prompted the snackbar. Snack bars can have at most one action.
///
/// The action should not be "dismiss" or "cancel".
final SnackBarAction? action;
/// (optional) The percentage threshold for action widget's width before it overflows
/// to a new line.
///
/// Must be between 0 and 1. If the width of the snackbar's [content] is greater
/// than this percentage of the width of the snackbar less the width of its [action],
/// then the [action] will appear below the [content].
///
/// At a value of 0, the action will not overflow to a new line.
///
/// Defaults to 0.25.
final double? actionOverflowThreshold;
/// (optional) Whether to include a "close" icon widget.
///
/// Tapping the icon will close the snack bar.
final bool? showCloseIcon;
/// (optional) An optional color for the close icon, if [showCloseIcon] is
/// true.
///
/// If this property is null, then [SnackBarThemeData.closeIconColor] of
/// [ThemeData.snackBarTheme] is used. If that is null, then the default is
/// inverse surface.
///
/// If [closeIconColor] is a [MaterialStateColor], then the icon color will be
/// resolved against the set of [MaterialState]s that the action text
/// is in, thus allowing for different colors for states such as pressed,
/// hovered and others.
final Color? closeIconColor;
/// The amount of time the snack bar should be displayed.
///
/// Defaults to 4.0s.
///
/// See also:
///
/// * [ScaffoldMessengerState.removeCurrentSnackBar], which abruptly hides the
/// currently displayed snack bar, if any, and allows the next to be
/// displayed.
/// * <https://material.io/design/components/snackbars.html>
final Duration duration;
/// The animation driving the entrance and exit of the snack bar.
final Animation<double>? animation;
/// Called the first time that the snackbar is visible within a [Scaffold].
final VoidCallback? onVisible;
/// The direction in which the SnackBar can be dismissed.
///
/// If this property is null, then [SnackBarThemeData.dismissDirection] of
/// [ThemeData.snackBarTheme] is used. If that is null, then the default is
/// [DismissDirection.down].
final DismissDirection? dismissDirection;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
// API for ScaffoldMessengerState.showSnackBar():
/// Creates an animation controller useful for driving a snack bar's entrance and exit animation.
static AnimationController createAnimationController({
required TickerProvider vsync,
Duration? duration,
Duration? reverseDuration,
}) {
return AnimationController(
duration: duration ?? _snackBarTransitionDuration,
reverseDuration: reverseDuration,
debugLabel: 'SnackBar',
vsync: vsync,
);
}
/// Creates a copy of this snack bar but with the animation replaced with the given animation.
///
/// If the original snack bar lacks a key, the newly created snack bar will
/// use the given fallback key.
SnackBar withAnimation(Animation<double> newAnimation, { Key? fallbackKey }) {
return SnackBar(
key: key ?? fallbackKey,
content: content,
backgroundColor: backgroundColor,
elevation: elevation,
margin: margin,
padding: padding,
width: width,
shape: shape,
hitTestBehavior: hitTestBehavior,
behavior: behavior,
action: action,
actionOverflowThreshold: actionOverflowThreshold,
showCloseIcon: showCloseIcon,
closeIconColor: closeIconColor,
duration: duration,
animation: newAnimation,
onVisible: onVisible,
dismissDirection: dismissDirection,
clipBehavior: clipBehavior,
);
}
@override
State<SnackBar> createState() => _SnackBarState();
}
class _SnackBarState extends State<SnackBar> {
bool _wasVisible = false;
@override
void initState() {
super.initState();
widget.animation!.addStatusListener(_onAnimationStatusChanged);
}
@override
void didUpdateWidget(SnackBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.animation != oldWidget.animation) {
oldWidget.animation!.removeStatusListener(_onAnimationStatusChanged);
widget.animation!.addStatusListener(_onAnimationStatusChanged);
}
}
@override
void dispose() {
widget.animation!.removeStatusListener(_onAnimationStatusChanged);
super.dispose();
}
void _onAnimationStatusChanged(AnimationStatus animationStatus) {
switch (animationStatus) {
case AnimationStatus.dismissed:
case AnimationStatus.forward:
case AnimationStatus.reverse:
break;
case AnimationStatus.completed:
if (widget.onVisible != null && !_wasVisible) {
widget.onVisible!();
}
_wasVisible = true;
}
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context));
final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context);
assert(widget.animation != null);
final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme;
final SnackBarThemeData snackBarTheme = theme.snackBarTheme;
final bool isThemeDark = theme.brightness == Brightness.dark;
final Color buttonColor = isThemeDark ? colorScheme.primary : colorScheme.secondary;
final SnackBarThemeData defaults = theme.useMaterial3
? _SnackbarDefaultsM3(context)
: _SnackbarDefaultsM2(context);
// SnackBar uses a theme that is the opposite brightness from
// the surrounding theme.
final Brightness brightness = isThemeDark ? Brightness.light : Brightness.dark;
// Invert the theme values for Material 2. Material 3 values are tokenized to pre-inverted values.
final ThemeData effectiveTheme = theme.useMaterial3
? theme
: theme.copyWith(
colorScheme: ColorScheme(
primary: colorScheme.onPrimary,
secondary: buttonColor,
surface: colorScheme.onSurface,
background: defaults.backgroundColor,
error: colorScheme.onError,
onPrimary: colorScheme.primary,
onSecondary: colorScheme.secondary,
onSurface: colorScheme.surface,
onBackground: colorScheme.background,
onError: colorScheme.error,
brightness: brightness,
),
);
final TextStyle? contentTextStyle = snackBarTheme.contentTextStyle ?? defaults.contentTextStyle;
final SnackBarBehavior snackBarBehavior = widget.behavior ?? snackBarTheme.behavior ?? defaults.behavior!;
final double? width = widget.width ?? snackBarTheme.width;
assert((){
// Whether the behavior is set through the constructor or the theme,
// assert that our other properties are configured properly.
if (snackBarBehavior != SnackBarBehavior.floating) {
String message(String parameter) {
final String prefix = '$parameter can only be used with floating behavior.';
if (widget.behavior != null) {
return '$prefix SnackBarBehavior.fixed was set in the SnackBar constructor.';
} else if (snackBarTheme.behavior != null) {
return '$prefix SnackBarBehavior.fixed was set by the inherited SnackBarThemeData.';
} else {
return '$prefix SnackBarBehavior.fixed was set by default.';
}
}
assert(widget.margin == null, message('Margin'));
assert(width == null, message('Width'));
}
return true;
}());
final bool showCloseIcon = widget.showCloseIcon ?? snackBarTheme.showCloseIcon ?? defaults.showCloseIcon!;
final bool isFloatingSnackBar = snackBarBehavior == SnackBarBehavior.floating;
final double horizontalPadding = isFloatingSnackBar ? 16.0 : 24.0;
final EdgeInsetsGeometry padding = widget.padding ??
EdgeInsetsDirectional.only(
start: horizontalPadding,
end: widget.action != null || showCloseIcon
? 0
: horizontalPadding);
final double actionHorizontalMargin = (widget.padding?.resolve(TextDirection.ltr).right ?? horizontalPadding) / 2;
final double iconHorizontalMargin = (widget.padding?.resolve(TextDirection.ltr).right ?? horizontalPadding) / 12.0;
final CurvedAnimation heightAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarHeightCurve);
final CurvedAnimation fadeInAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarFadeInCurve);
final CurvedAnimation fadeInM3Animation = CurvedAnimation(parent: widget.animation!, curve: _snackBarM3FadeInCurve);
final CurvedAnimation fadeOutAnimation = CurvedAnimation(
parent: widget.animation!,
curve: _snackBarFadeOutCurve,
reverseCurve: const Threshold(0.0),
);
// Material 3 Animation has a height animation on entry, but a direct fade out on exit.
final CurvedAnimation heightM3Animation = CurvedAnimation(
parent: widget.animation!,
curve: _snackBarM3HeightCurve,
reverseCurve: const Threshold(0.0),
);
final IconButton? iconButton = showCloseIcon
? IconButton(
icon: const Icon(Icons.close),
iconSize: 24.0,
color: widget.closeIconColor ?? snackBarTheme.closeIconColor ?? defaults.closeIconColor,
onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(reason: SnackBarClosedReason.dismiss),
tooltip: MaterialLocalizations.of(context).closeButtonTooltip,
)
: null;
// Calculate combined width of Action, Icon, and their padding, if they are present.
final TextPainter actionTextPainter = TextPainter(
text: TextSpan(
text: widget.action?.label ?? '',
style: Theme.of(context).textTheme.labelLarge,
),
maxLines: 1,
textDirection: TextDirection.ltr)
..layout();
final double actionAndIconWidth = actionTextPainter.size.width +
(widget.action != null ? actionHorizontalMargin : 0) +
(showCloseIcon ? (iconButton?.iconSize ?? 0 + iconHorizontalMargin) : 0);
actionTextPainter.dispose();
final EdgeInsets margin = widget.margin?.resolve(TextDirection.ltr) ?? snackBarTheme.insetPadding ?? defaults.insetPadding!;
final double snackBarWidth = widget.width ?? MediaQuery.sizeOf(context).width - (margin.left + margin.right);
final double actionOverflowThreshold = widget.actionOverflowThreshold
?? snackBarTheme.actionOverflowThreshold
?? defaults.actionOverflowThreshold!;
final bool willOverflowAction = actionAndIconWidth / snackBarWidth > actionOverflowThreshold;
final List<Widget> maybeActionAndIcon = <Widget>[
if (widget.action != null)
Padding(
padding: EdgeInsets.symmetric(horizontal: actionHorizontalMargin),
child: TextButtonTheme(
data: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: buttonColor,
padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
),
),
child: widget.action!,
),
),
if (showCloseIcon)
Padding(
padding: EdgeInsets.symmetric(horizontal: iconHorizontalMargin),
child: iconButton,
),
];
Widget snackBar = Padding(
padding: padding,
child: Wrap(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Container(
padding: widget.padding == null
? const EdgeInsets.symmetric(
vertical: _singleLineVerticalPadding)
: null,
child: DefaultTextStyle(
style: contentTextStyle!,
child: widget.content,
),
),
),
if (!willOverflowAction) ...maybeActionAndIcon,
if (willOverflowAction) SizedBox(width: snackBarWidth * 0.4),
],
),
if (willOverflowAction)
Padding(
padding: const EdgeInsets.only(bottom: _singleLineVerticalPadding),
child: Row(mainAxisAlignment: MainAxisAlignment.end, children: maybeActionAndIcon),
),
],
),
);
if (!isFloatingSnackBar) {
snackBar = SafeArea(
top: false,
child: snackBar,
);
}
final double elevation = widget.elevation ?? snackBarTheme.elevation ?? defaults.elevation!;
final Color backgroundColor = widget.backgroundColor ?? snackBarTheme.backgroundColor ?? defaults.backgroundColor!;
final ShapeBorder? shape = widget.shape ?? snackBarTheme.shape ?? (isFloatingSnackBar ? defaults.shape : null);
final DismissDirection dismissDirection = widget.dismissDirection ?? snackBarTheme.dismissDirection ?? DismissDirection.down;
snackBar = Material(
shape: shape,
elevation: elevation,
color: backgroundColor,
clipBehavior: widget.clipBehavior,
child: Theme(
data: effectiveTheme,
child: accessibleNavigation || theme.useMaterial3
? snackBar
: FadeTransition(
opacity: fadeOutAnimation,
child: snackBar,
),
),
);
if (isFloatingSnackBar) {
// If width is provided, do not include horizontal margins.
if (width != null) {
snackBar = Container(
margin: EdgeInsets.only(top: margin.top, bottom: margin.bottom),
width: width,
child: snackBar,
);
} else {
snackBar = Padding(
padding: margin,
child: snackBar,
);
}
snackBar = SafeArea(
top: false,
bottom: false,
child: snackBar,
);
}
snackBar = Semantics(
container: true,
liveRegion: true,
onDismiss: () {
ScaffoldMessenger.of(context).removeCurrentSnackBar(reason: SnackBarClosedReason.dismiss);
},
child: Dismissible(
key: const Key('dismissible'),
direction: dismissDirection,
resizeDuration: null,
behavior: widget.hitTestBehavior ?? (widget.margin != null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque),
onDismissed: (DismissDirection direction) {
ScaffoldMessenger.of(context).removeCurrentSnackBar(reason: SnackBarClosedReason.swipe);
},
child: snackBar,
),
);
final Widget snackBarTransition;
if (accessibleNavigation) {
snackBarTransition = snackBar;
} else if (isFloatingSnackBar && !theme.useMaterial3) {
snackBarTransition = FadeTransition(
opacity: fadeInAnimation,
child: snackBar,
);
// Is Material 3 Floating Snack Bar.
} else if (isFloatingSnackBar && theme.useMaterial3) {
snackBarTransition = FadeTransition(
opacity: fadeInM3Animation,
child: AnimatedBuilder(
animation: heightM3Animation,
builder: (BuildContext context, Widget? child) {
return Align(
alignment: AlignmentDirectional.bottomStart,
heightFactor: heightM3Animation.value,
child: child,
);
},
child: snackBar,
),
);
} else {
snackBarTransition = AnimatedBuilder(
animation: heightAnimation,
builder: (BuildContext context, Widget? child) {
return Align(
alignment: AlignmentDirectional.topStart,
heightFactor: heightAnimation.value,
child: child,
);
},
child: snackBar,
);
}
return Hero(
tag: '<SnackBar Hero tag - ${widget.content}>',
transitionOnUserGestures: true,
child: ClipRect(
clipBehavior: widget.clipBehavior,
child: snackBarTransition,
),
);
}
}
// Hand coded defaults based on Material Design 2.
class _SnackbarDefaultsM2 extends SnackBarThemeData {
_SnackbarDefaultsM2(BuildContext context)
: _theme = Theme.of(context),
_colors = Theme.of(context).colorScheme,
super(elevation: 6.0);
late final ThemeData _theme;
late final ColorScheme _colors;
@override
Color get backgroundColor => _theme.brightness == Brightness.light
? Color.alphaBlend(_colors.onSurface.withOpacity(0.80), _colors.surface)
: _colors.onSurface;
@override
TextStyle? get contentTextStyle => ThemeData(
useMaterial3: _theme.useMaterial3,
brightness: _theme.brightness == Brightness.light
? Brightness.dark
: Brightness.light)
.textTheme
.titleMedium;
@override
SnackBarBehavior get behavior => SnackBarBehavior.fixed;
@override
Color get actionTextColor => _colors.secondary;
@override
Color get disabledActionTextColor => _colors.onSurface
.withOpacity(_theme.brightness == Brightness.light ? 0.38 : 0.3);
@override
ShapeBorder get shape => const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(4.0),
),
);
@override
EdgeInsets get insetPadding => const EdgeInsets.fromLTRB(15.0, 5.0, 15.0, 10.0);
@override
bool get showCloseIcon => false;
@override
Color get closeIconColor => _colors.onSurface;
@override
double get actionOverflowThreshold => 0.25;
}
// BEGIN GENERATED TOKEN PROPERTIES - Snackbar
// 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 _SnackbarDefaultsM3 extends SnackBarThemeData {
_SnackbarDefaultsM3(this.context);
final BuildContext context;
late final ThemeData _theme = Theme.of(context);
late final ColorScheme _colors = _theme.colorScheme;
@override
Color get backgroundColor => _colors.inverseSurface;
@override
Color get actionTextColor => MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return _colors.inversePrimary;
}
if (states.contains(MaterialState.pressed)) {
return _colors.inversePrimary;
}
if (states.contains(MaterialState.hovered)) {
return _colors.inversePrimary;
}
if (states.contains(MaterialState.focused)) {
return _colors.inversePrimary;
}
return _colors.inversePrimary;
});
@override
Color get disabledActionTextColor =>
_colors.inversePrimary;
@override
TextStyle get contentTextStyle =>
Theme.of(context).textTheme.bodyMedium!.copyWith
(color: _colors.onInverseSurface,
);
@override
double get elevation => 6.0;
@override
ShapeBorder get shape => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)));
@override
SnackBarBehavior get behavior => SnackBarBehavior.fixed;
@override
EdgeInsets get insetPadding => const EdgeInsets.fromLTRB(15.0, 5.0, 15.0, 10.0);
@override
bool get showCloseIcon => false;
@override
Color? get closeIconColor => _colors.onInverseSurface;
@override
double get actionOverflowThreshold => 0.25;
}
// END GENERATED TOKEN PROPERTIES - Snackbar
| flutter/packages/flutter/lib/src/material/snack_bar.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/snack_bar.dart",
"repo_id": "flutter",
"token_count": 12386
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'debug.dart';
import 'material_localizations.dart';
import 'text_selection_theme.dart';
import 'text_selection_toolbar.dart';
import 'text_selection_toolbar_text_button.dart';
import 'theme.dart';
const double _kHandleSize = 22.0;
// Padding between the toolbar and the anchor.
const double _kToolbarContentDistanceBelow = _kHandleSize - 2.0;
const double _kToolbarContentDistance = 8.0;
/// Android Material styled text selection handle controls.
///
/// Specifically does not manage the toolbar, which is left to
/// [EditableText.contextMenuBuilder].
@Deprecated(
'Use `MaterialTextSelectionControls`. '
'This feature was deprecated after v3.3.0-0.5.pre.',
)
class MaterialTextSelectionHandleControls extends MaterialTextSelectionControls with TextSelectionHandleControls {
}
/// Android Material styled text selection controls.
///
/// The [materialTextSelectionControls] global variable has a
/// suitable instance of this class.
class MaterialTextSelectionControls extends TextSelectionControls {
/// Returns the size of the Material handle.
@override
Size getHandleSize(double textLineHeight) => const Size(_kHandleSize, _kHandleSize);
/// Builder for material-style copy/paste text selection toolbar.
@Deprecated(
'Use `contextMenuBuilder` instead. '
'This feature was deprecated after v3.3.0-0.5.pre.',
)
@override
Widget buildToolbar(
BuildContext context,
Rect globalEditableRegion,
double textLineHeight,
Offset selectionMidpoint,
List<TextSelectionPoint> endpoints,
TextSelectionDelegate delegate,
ValueListenable<ClipboardStatus>? clipboardStatus,
Offset? lastSecondaryTapDownPosition,
) {
return _TextSelectionControlsToolbar(
globalEditableRegion: globalEditableRegion,
textLineHeight: textLineHeight,
selectionMidpoint: selectionMidpoint,
endpoints: endpoints,
delegate: delegate,
clipboardStatus: clipboardStatus,
handleCut: canCut(delegate) ? () => handleCut(delegate) : null,
handleCopy: canCopy(delegate) ? () => handleCopy(delegate) : null,
handlePaste: canPaste(delegate) ? () => handlePaste(delegate) : null,
handleSelectAll: canSelectAll(delegate) ? () => handleSelectAll(delegate) : null,
);
}
/// Builder for material-style text selection handles.
@override
Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textHeight, [VoidCallback? onTap]) {
final ThemeData theme = Theme.of(context);
final Color handleColor = TextSelectionTheme.of(context).selectionHandleColor ?? theme.colorScheme.primary;
final Widget handle = SizedBox(
width: _kHandleSize,
height: _kHandleSize,
child: CustomPaint(
painter: _TextSelectionHandlePainter(
color: handleColor,
),
child: GestureDetector(
onTap: onTap,
behavior: HitTestBehavior.translucent,
),
),
);
// [handle] is a circle, with a rectangle in the top left quadrant of that
// circle (an onion pointing to 10:30). We rotate [handle] to point
// straight up or up-right depending on the handle type.
return switch (type) {
TextSelectionHandleType.left => Transform.rotate(angle: math.pi / 2.0, child: handle), // points up-right
TextSelectionHandleType.right => handle, // points up-left
TextSelectionHandleType.collapsed => Transform.rotate(angle: math.pi / 4.0, child: handle), // points up
};
}
/// Gets anchor for material-style text selection handles.
///
/// See [TextSelectionControls.getHandleAnchor].
@override
Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) {
return switch (type) {
TextSelectionHandleType.collapsed => const Offset(_kHandleSize / 2, -4),
TextSelectionHandleType.left => const Offset(_kHandleSize, 0),
TextSelectionHandleType.right => Offset.zero,
};
}
@Deprecated(
'Use `contextMenuBuilder` instead. '
'This feature was deprecated after v3.3.0-0.5.pre.',
)
@override
bool canSelectAll(TextSelectionDelegate delegate) {
// Android allows SelectAll when selection is not collapsed, unless
// everything has already been selected.
final TextEditingValue value = delegate.textEditingValue;
return delegate.selectAllEnabled &&
value.text.isNotEmpty &&
!(value.selection.start == 0 && value.selection.end == value.text.length);
}
}
// The label and callback for the available default text selection menu buttons.
class _TextSelectionToolbarItemData {
const _TextSelectionToolbarItemData({
required this.label,
required this.onPressed,
});
final String label;
final VoidCallback onPressed;
}
// The highest level toolbar widget, built directly by buildToolbar.
class _TextSelectionControlsToolbar extends StatefulWidget {
const _TextSelectionControlsToolbar({
required this.clipboardStatus,
required this.delegate,
required this.endpoints,
required this.globalEditableRegion,
required this.handleCut,
required this.handleCopy,
required this.handlePaste,
required this.handleSelectAll,
required this.selectionMidpoint,
required this.textLineHeight,
});
final ValueListenable<ClipboardStatus>? clipboardStatus;
final TextSelectionDelegate delegate;
final List<TextSelectionPoint> endpoints;
final Rect globalEditableRegion;
final VoidCallback? handleCut;
final VoidCallback? handleCopy;
final VoidCallback? handlePaste;
final VoidCallback? handleSelectAll;
final Offset selectionMidpoint;
final double textLineHeight;
@override
_TextSelectionControlsToolbarState createState() => _TextSelectionControlsToolbarState();
}
class _TextSelectionControlsToolbarState extends State<_TextSelectionControlsToolbar> with TickerProviderStateMixin {
void _onChangedClipboardStatus() {
setState(() {
// Inform the widget that the value of clipboardStatus has changed.
});
}
@override
void initState() {
super.initState();
widget.clipboardStatus?.addListener(_onChangedClipboardStatus);
}
@override
void didUpdateWidget(_TextSelectionControlsToolbar oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.clipboardStatus != oldWidget.clipboardStatus) {
widget.clipboardStatus?.addListener(_onChangedClipboardStatus);
oldWidget.clipboardStatus?.removeListener(_onChangedClipboardStatus);
}
}
@override
void dispose() {
widget.clipboardStatus?.removeListener(_onChangedClipboardStatus);
super.dispose();
}
@override
Widget build(BuildContext context) {
// If there are no buttons to be shown, don't render anything.
if (widget.handleCut == null && widget.handleCopy == null
&& widget.handlePaste == null && widget.handleSelectAll == null) {
return const SizedBox.shrink();
}
// If the paste button is desired, don't render anything until the state of
// the clipboard is known, since it's used to determine if paste is shown.
if (widget.handlePaste != null
&& widget.clipboardStatus?.value == ClipboardStatus.unknown) {
return const SizedBox.shrink();
}
// Calculate the positioning of the menu. It is placed above the selection
// if there is enough room, or otherwise below.
final TextSelectionPoint startTextSelectionPoint = widget.endpoints[0];
final TextSelectionPoint endTextSelectionPoint = widget.endpoints.length > 1
? widget.endpoints[1]
: widget.endpoints[0];
final double topAmountInEditableRegion = startTextSelectionPoint.point.dy - widget.textLineHeight;
final double anchorTop = math.max(topAmountInEditableRegion, 0) + widget.globalEditableRegion.top - _kToolbarContentDistance;
final Offset anchorAbove = Offset(
widget.globalEditableRegion.left + widget.selectionMidpoint.dx,
anchorTop,
);
final Offset anchorBelow = Offset(
widget.globalEditableRegion.left + widget.selectionMidpoint.dx,
widget.globalEditableRegion.top + endTextSelectionPoint.point.dy + _kToolbarContentDistanceBelow,
);
// Determine which buttons will appear so that the order and total number is
// known. A button's position in the menu can slightly affect its
// appearance.
assert(debugCheckHasMaterialLocalizations(context));
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final List<_TextSelectionToolbarItemData> itemDatas = <_TextSelectionToolbarItemData>[
if (widget.handleCut != null)
_TextSelectionToolbarItemData(
label: localizations.cutButtonLabel,
onPressed: widget.handleCut!,
),
if (widget.handleCopy != null)
_TextSelectionToolbarItemData(
label: localizations.copyButtonLabel,
onPressed: widget.handleCopy!,
),
if (widget.handlePaste != null
&& widget.clipboardStatus?.value == ClipboardStatus.pasteable)
_TextSelectionToolbarItemData(
label: localizations.pasteButtonLabel,
onPressed: widget.handlePaste!,
),
if (widget.handleSelectAll != null)
_TextSelectionToolbarItemData(
label: localizations.selectAllButtonLabel,
onPressed: widget.handleSelectAll!,
),
];
// If there is no option available, build an empty widget.
if (itemDatas.isEmpty) {
return const SizedBox.shrink();
}
return TextSelectionToolbar(
anchorAbove: anchorAbove,
anchorBelow: anchorBelow,
children: itemDatas.asMap().entries.map((MapEntry<int, _TextSelectionToolbarItemData> entry) {
return TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(entry.key, itemDatas.length),
alignment: AlignmentDirectional.centerStart,
onPressed: entry.value.onPressed,
child: Text(entry.value.label),
);
}).toList(),
);
}
}
/// Draws a single text selection handle which points up and to the left.
class _TextSelectionHandlePainter extends CustomPainter {
_TextSelectionHandlePainter({ required this.color });
final Color color;
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()..color = color;
final double radius = size.width/2.0;
final Rect circle = Rect.fromCircle(center: Offset(radius, radius), radius: radius);
final Rect point = Rect.fromLTWH(0.0, 0.0, radius, radius);
final Path path = Path()..addOval(circle)..addRect(point);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(_TextSelectionHandlePainter oldPainter) {
return color != oldPainter.color;
}
}
// TODO(justinmc): Deprecate this after TextSelectionControls.buildToolbar is
// deleted, when users should migrate back to materialTextSelectionControls.
// See https://github.com/flutter/flutter/pull/124262
/// Text selection handle controls that follow the Material Design specification.
final TextSelectionControls materialTextSelectionHandleControls = MaterialTextSelectionHandleControls();
/// Text selection controls that follow the Material Design specification.
final TextSelectionControls materialTextSelectionControls = MaterialTextSelectionControls();
| flutter/packages/flutter/lib/src/material/text_selection.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/text_selection.dart",
"repo_id": "flutter",
"token_count": 3803
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'text_theme.dart';
// Examples can assume:
// late TargetPlatform platform;
/// A characterization of the of a [TextTheme]'s glyphs that is used to define
/// its localized [TextStyle] geometry for [ThemeData.textTheme].
///
/// The script category defines the overall geometry of a [TextTheme] for
/// the [Typography.geometryThemeFor] method in terms of the
/// three language categories defined in <https://material.io/go/design-typography>.
///
/// Generally speaking, font sizes for [ScriptCategory.tall] and
/// [ScriptCategory.dense] scripts - for text styles that are smaller than the
/// title style - are one unit larger than they are for
/// [ScriptCategory.englishLike] scripts.
enum ScriptCategory {
/// The languages of Western, Central, and Eastern Europe and much of
/// Africa are typically written in the Latin alphabet. Vietnamese is a
/// notable exception in that, while it uses a localized form of the Latin
/// writing system, its accented glyphs can be much taller than those
/// found in Western European languages. The Greek and Cyrillic writing
/// systems are very similar to Latin.
englishLike,
/// Language scripts that require extra line height to accommodate larger
/// glyphs, including Chinese, Japanese, and Korean.
dense,
/// Language scripts that require extra line height to accommodate
/// larger glyphs, including South and Southeast Asian and
/// Middle-Eastern languages, like Arabic, Hindi, Telugu, Thai, and
/// Vietnamese.
tall,
}
/// The color and geometry [TextTheme]s for Material apps.
///
/// The text theme provided by the overall [Theme],
/// [ThemeData.textTheme], is based on the current locale's
/// [MaterialLocalizations.scriptCategory] and is created
/// by merging a color text theme - [black] for
/// [Brightness.light] themes and [white] for [Brightness.dark]
/// themes - and a geometry text theme, one of [englishLike], [dense],
/// or [tall], depending on the locale.
///
/// To lookup the localized text theme use
/// `Theme.of(context).textTheme`.
///
/// The color text themes are [blackMountainView], [whiteMountainView],
/// [blackCupertino], and [whiteCupertino]. The Mountain View theme [TextStyle]s
/// are based on the Roboto fonts as used on Android. The Cupertino themes are
/// based on the [San Francisco
/// font](https://developer.apple.com/design/human-interface-guidelines/typography/)
/// fonts as used by Apple on iOS.
///
/// Two sets of geometry themes are provided: 2014 and 2018. The 2014 themes
/// correspond to the original version of the Material Design spec and are
/// the defaults. The 2018 themes correspond the second iteration of the
/// specification and feature different font sizes, font weights, and
/// letter spacing values.
///
/// By default, [ThemeData.typography] is `Typography.material2014(platform:
/// platform)` which uses [englishLike2014], [dense2014] and [tall2014]. To use
/// the 2018 text theme geometries, specify a value using the [material2018]
/// constructor:
///
/// ```dart
/// typography: Typography.material2018(platform: platform)
/// ```
///
/// See also:
///
/// * <https://material.io/design/typography/>
/// * <https://m3.material.io/styles/typography>
@immutable
class Typography with Diagnosticable {
/// Creates a typography instance.
///
/// This constructor is identical to [Typography.material2018].
factory Typography({
TargetPlatform? platform,
TextTheme? black,
TextTheme? white,
TextTheme? englishLike,
TextTheme? dense,
TextTheme? tall,
}) = Typography.material2018;
/// Creates a typography instance using Material Design's 2014 defaults.
///
/// If [platform] is [TargetPlatform.iOS] or [TargetPlatform.macOS], the
/// default values for [black] and [white] are [blackCupertino] and
/// [whiteCupertino] respectively. Otherwise they are [blackMountainView] and
/// [whiteMountainView]. If [platform] is null then both [black] and [white]
/// must be specified.
///
/// The default values for [englishLike], [dense], and [tall] are
/// [englishLike2014], [dense2014], and [tall2014].
factory Typography.material2014({
TargetPlatform? platform = TargetPlatform.android,
TextTheme? black,
TextTheme? white,
TextTheme? englishLike,
TextTheme? dense,
TextTheme? tall,
}) {
assert(platform != null || (black != null && white != null));
return Typography._withPlatform(
platform,
black, white,
englishLike ?? englishLike2014,
dense ?? dense2014,
tall ?? tall2014,
);
}
/// Creates a typography instance using Material Design's 2018 defaults.
///
/// If [platform] is [TargetPlatform.iOS] or [TargetPlatform.macOS], the
/// default values for [black] and [white] are [blackCupertino] and
/// [whiteCupertino] respectively. Otherwise they are [blackMountainView] and
/// [whiteMountainView]. If [platform] is null then both [black] and [white]
/// must be specified.
///
/// The default values for [englishLike], [dense], and [tall] are
/// [englishLike2018], [dense2018], and [tall2018].
factory Typography.material2018({
TargetPlatform? platform = TargetPlatform.android,
TextTheme? black,
TextTheme? white,
TextTheme? englishLike,
TextTheme? dense,
TextTheme? tall,
}) {
assert(platform != null || (black != null && white != null));
return Typography._withPlatform(
platform,
black, white,
englishLike ?? englishLike2018,
dense ?? dense2018,
tall ?? tall2018,
);
}
/// Creates a typography instance using Material Design 3 2021 defaults.
///
/// If [platform] is [TargetPlatform.iOS] or [TargetPlatform.macOS], the
/// default values for [black] and [white] are [blackCupertino] and
/// [whiteCupertino] respectively. Otherwise they are [blackMountainView] and
/// [whiteMountainView]. If [platform] is null then both [black] and [white]
/// must be specified.
///
/// The default values for [englishLike], [dense], and [tall] are
/// [englishLike2021], [dense2021], and [tall2021].
///
/// See also:
/// * <https://m3.material.io/styles/typography>
factory Typography.material2021({
TargetPlatform? platform = TargetPlatform.android,
ColorScheme colorScheme = const ColorScheme.light(),
TextTheme? black,
TextTheme? white,
TextTheme? englishLike,
TextTheme? dense,
TextTheme? tall,
}) {
assert(platform != null || (black != null && white != null));
final Typography base = Typography._withPlatform(
platform,
black, white,
englishLike ?? englishLike2021,
dense ?? dense2021,
tall ?? tall2021,
);
// Ensure they are all uniformly dark or light, with
// no color variation based on style as it was in previous
// versions of Material Design.
final Color dark = colorScheme.brightness == Brightness.light ? colorScheme.onSurface : colorScheme.surface;
final Color light = colorScheme.brightness == Brightness.light ? colorScheme.surface : colorScheme.onSurface;
return base.copyWith(
black: base.black.apply(
displayColor: dark,
bodyColor: dark,
decorationColor: dark
),
white: base.white.apply(
displayColor: light,
bodyColor: light,
decorationColor: light
),
);
}
factory Typography._withPlatform(
TargetPlatform? platform,
TextTheme? black,
TextTheme? white,
TextTheme englishLike,
TextTheme dense,
TextTheme tall,
) {
assert(platform != null || (black != null && white != null));
switch (platform) {
case TargetPlatform.iOS:
black ??= blackCupertino;
white ??= whiteCupertino;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
black ??= blackMountainView;
white ??= whiteMountainView;
case TargetPlatform.windows:
black ??= blackRedmond;
white ??= whiteRedmond;
case TargetPlatform.macOS:
black ??= blackRedwoodCity;
white ??= whiteRedwoodCity;
case TargetPlatform.linux:
black ??= blackHelsinki;
white ??= whiteHelsinki;
case null:
break;
}
return Typography._(black!, white!, englishLike, dense, tall);
}
const Typography._(this.black, this.white, this.englishLike, this.dense, this.tall);
/// A Material Design text theme with dark glyphs.
///
/// This [TextTheme] should provide color but not geometry (font size,
/// weight, etc). A text theme's geometry depends on the locale. To look
/// up a localized [TextTheme], use the overall [Theme], for example:
/// `Theme.of(context).textTheme`.
///
/// The [englishLike], [dense], and [tall] text theme's provide locale-specific
/// geometry.
final TextTheme black;
/// A Material Design text theme with light glyphs.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
/// A text theme's geometry depends on the locale. To look up a localized
/// [TextTheme], use the overall [Theme], for example:
/// `Theme.of(context).textTheme`.
///
/// The [englishLike], [dense], and [tall] text theme's provide locale-specific
/// geometry.
final TextTheme white;
/// Defines text geometry for [ScriptCategory.englishLike] scripts, such as
/// English, French, Russian, etc.
///
/// This text theme is merged with either [black] or [white], depending
/// on the overall [ThemeData.brightness], when the current locale's
/// [MaterialLocalizations.scriptCategory] is [ScriptCategory.englishLike].
///
/// To look up a localized [TextTheme], use the overall [Theme], for
/// example: `Theme.of(context).textTheme`.
final TextTheme englishLike;
/// Defines text geometry for dense scripts, such as Chinese, Japanese
/// and Korean.
///
/// This text theme is merged with either [black] or [white], depending
/// on the overall [ThemeData.brightness], when the current locale's
/// [MaterialLocalizations.scriptCategory] is [ScriptCategory.dense].
///
/// To look up a localized [TextTheme], use the overall [Theme], for
/// example: `Theme.of(context).textTheme`.
final TextTheme dense;
/// Defines text geometry for tall scripts, such as Farsi, Hindi, and Thai.
///
/// This text theme is merged with either [black] or [white], depending
/// on the overall [ThemeData.brightness], when the current locale's
/// [MaterialLocalizations.scriptCategory] is [ScriptCategory.tall].
///
/// To look up a localized [TextTheme], use the overall [Theme], for
/// example: `Theme.of(context).textTheme`.
final TextTheme tall;
/// Returns one of [englishLike], [dense], or [tall].
TextTheme geometryThemeFor(ScriptCategory category) {
return switch (category) {
ScriptCategory.englishLike => englishLike,
ScriptCategory.dense => dense,
ScriptCategory.tall => tall,
};
}
/// Creates a copy of this [Typography] with the given fields
/// replaced by the non-null parameter values.
Typography copyWith({
TextTheme? black,
TextTheme? white,
TextTheme? englishLike,
TextTheme? dense,
TextTheme? tall,
}) {
return Typography._(
black ?? this.black,
white ?? this.white,
englishLike ?? this.englishLike,
dense ?? this.dense,
tall ?? this.tall,
);
}
/// Linearly interpolate between two [Typography] objects.
///
/// {@macro dart.ui.shadow.lerp}
static Typography lerp(Typography a, Typography b, double t) {
if (identical(a, b)) {
return a;
}
return Typography._(
TextTheme.lerp(a.black, b.black, t),
TextTheme.lerp(a.white, b.white, t),
TextTheme.lerp(a.englishLike, b.englishLike, t),
TextTheme.lerp(a.dense, b.dense, t),
TextTheme.lerp(a.tall, b.tall, t),
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is Typography
&& other.black == black
&& other.white == white
&& other.englishLike == englishLike
&& other.dense == dense
&& other.tall == tall;
}
@override
int get hashCode => Object.hash(
black,
white,
englishLike,
dense,
tall,
);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
final Typography defaultTypography = Typography.material2014();
properties.add(DiagnosticsProperty<TextTheme>('black', black, defaultValue: defaultTypography.black));
properties.add(DiagnosticsProperty<TextTheme>('white', white, defaultValue: defaultTypography.white));
properties.add(DiagnosticsProperty<TextTheme>('englishLike', englishLike, defaultValue: defaultTypography.englishLike));
properties.add(DiagnosticsProperty<TextTheme>('dense', dense, defaultValue: defaultTypography.dense));
properties.add(DiagnosticsProperty<TextTheme>('tall', tall, defaultValue: defaultTypography.tall));
}
/// A Material Design text theme with dark glyphs based on Roboto.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
static const TextTheme blackMountainView = TextTheme(
displayLarge: TextStyle(debugLabel: 'blackMountainView displayLarge', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'blackMountainView displayMedium', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'blackMountainView displaySmall', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'blackMountainView headlineLarge', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'blackMountainView headlineMedium', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'blackMountainView headlineSmall', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'blackMountainView titleLarge', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'blackMountainView titleMedium', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'blackMountainView titleSmall', fontFamily: 'Roboto', color: Colors.black, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'blackMountainView bodyLarge', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'blackMountainView bodyMedium', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'blackMountainView bodySmall', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'blackMountainView labelLarge', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'blackMountainView labelMedium', fontFamily: 'Roboto', color: Colors.black, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'blackMountainView labelSmall', fontFamily: 'Roboto', color: Colors.black, decoration: TextDecoration.none),
);
/// A Material Design text theme with light glyphs based on Roboto.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
static const TextTheme whiteMountainView = TextTheme(
displayLarge: TextStyle(debugLabel: 'whiteMountainView displayLarge', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'whiteMountainView displayMedium', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'whiteMountainView displaySmall', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'whiteMountainView headlineLarge', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'whiteMountainView headlineMedium', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'whiteMountainView headlineSmall', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'whiteMountainView titleLarge', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'whiteMountainView titleMedium', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'whiteMountainView titleSmall', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'whiteMountainView bodyLarge', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'whiteMountainView bodyMedium', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'whiteMountainView bodySmall', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'whiteMountainView labelLarge', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'whiteMountainView labelMedium', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'whiteMountainView labelSmall', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none),
);
/// A Material Design text theme with dark glyphs based on Segoe UI.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
static const TextTheme blackRedmond = TextTheme(
displayLarge: TextStyle(debugLabel: 'blackRedmond displayLarge', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'blackRedmond displayMedium', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'blackRedmond displaySmall', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'blackRedmond headlineLarge', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'blackRedmond headlineMedium', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'blackRedmond headlineSmall', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'blackRedmond titleLarge', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'blackRedmond titleMedium', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'blackRedmond titleSmall', fontFamily: 'Segoe UI', color: Colors.black, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'blackRedmond bodyLarge', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'blackRedmond bodyMedium', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'blackRedmond bodySmall', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'blackRedmond labelLarge', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'blackRedmond labelMedium', fontFamily: 'Segoe UI', color: Colors.black, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'blackRedmond labelSmall', fontFamily: 'Segoe UI', color: Colors.black, decoration: TextDecoration.none),
);
/// A Material Design text theme with light glyphs based on Segoe UI.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
static const TextTheme whiteRedmond = TextTheme(
displayLarge: TextStyle(debugLabel: 'whiteRedmond displayLarge', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'whiteRedmond displayMedium', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'whiteRedmond displaySmall', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'whiteRedmond headlineLarge', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'whiteRedmond headlineMedium', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'whiteRedmond headlineSmall', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'whiteRedmond titleLarge', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'whiteRedmond titleMedium', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'whiteRedmond titleSmall', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'whiteRedmond bodyLarge', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'whiteRedmond bodyMedium', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'whiteRedmond bodySmall', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'whiteRedmond labelLarge', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'whiteRedmond labelMedium', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'whiteRedmond labelSmall', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none),
);
static const List<String> _helsinkiFontFallbacks = <String>['Ubuntu', 'Cantarell', 'DejaVu Sans', 'Liberation Sans', 'Arial'];
/// A Material Design text theme with dark glyphs based on Roboto, with
/// fallback fonts that are likely (but not guaranteed) to be installed on
/// Linux.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
static const TextTheme blackHelsinki = TextTheme(
displayLarge: TextStyle(debugLabel: 'blackHelsinki displayLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'blackHelsinki displayMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'blackHelsinki displaySmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'blackHelsinki headlineLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'blackHelsinki headlineMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'blackHelsinki headlineSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'blackHelsinki titleLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'blackHelsinki titleMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'blackHelsinki titleSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'blackHelsinki bodyLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'blackHelsinki bodyMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'blackHelsinki bodySmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'blackHelsinki labelLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'blackHelsinki labelMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'blackHelsinki labelSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black, decoration: TextDecoration.none),
);
/// A Material Design text theme with light glyphs based on Roboto, with fallbacks of DejaVu Sans, Liberation Sans and Arial.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
static const TextTheme whiteHelsinki = TextTheme(
displayLarge: TextStyle(debugLabel: 'whiteHelsinki displayLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'whiteHelsinki displayMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'whiteHelsinki displaySmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'whiteHelsinki headlineLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'whiteHelsinki headlineMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'whiteHelsinki headlineSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'whiteHelsinki titleLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'whiteHelsinki titleMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'whiteHelsinki titleSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'whiteHelsinki bodyLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'whiteHelsinki bodyMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'whiteHelsinki bodySmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'whiteHelsinki labelLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'whiteHelsinki labelMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'whiteHelsinki labelSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none),
);
/// A Material Design text theme with dark glyphs based on San Francisco.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
///
/// This theme uses the iOS version of the font names.
static const TextTheme blackCupertino = TextTheme(
displayLarge: TextStyle(debugLabel: 'blackCupertino displayLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'blackCupertino displayMedium', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'blackCupertino displaySmall', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'blackCupertino headlineLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'blackCupertino headlineMedium', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'blackCupertino headlineSmall', fontFamily: 'CupertinoSystemDisplay', color: Colors.black87, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'blackCupertino titleLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.black87, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'blackCupertino titleMedium', fontFamily: 'CupertinoSystemText', color: Colors.black87, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'blackCupertino titleSmall', fontFamily: 'CupertinoSystemText', color: Colors.black, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'blackCupertino bodyLarge', fontFamily: 'CupertinoSystemText', color: Colors.black87, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'blackCupertino bodyMedium', fontFamily: 'CupertinoSystemText', color: Colors.black87, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'blackCupertino bodySmall', fontFamily: 'CupertinoSystemText', color: Colors.black54, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'blackCupertino labelLarge', fontFamily: 'CupertinoSystemText', color: Colors.black87, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'blackCupertino labelMedium', fontFamily: 'CupertinoSystemText', color: Colors.black, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'blackCupertino labelSmall', fontFamily: 'CupertinoSystemText', color: Colors.black, decoration: TextDecoration.none),
);
/// A Material Design text theme with light glyphs based on San Francisco.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
///
/// This theme uses the iOS version of the font names.
static const TextTheme whiteCupertino = TextTheme(
displayLarge: TextStyle(debugLabel: 'whiteCupertino displayLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'whiteCupertino displayMedium', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'whiteCupertino displaySmall', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'whiteCupertino headlineLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'whiteCupertino headlineMedium', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'whiteCupertino headlineSmall', fontFamily: 'CupertinoSystemDisplay', color: Colors.white, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'whiteCupertino titleLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.white, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'whiteCupertino titleMedium', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'whiteCupertino titleSmall', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'whiteCupertino bodyLarge', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'whiteCupertino bodyMedium', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'whiteCupertino bodySmall', fontFamily: 'CupertinoSystemText', color: Colors.white70, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'whiteCupertino labelLarge', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'whiteCupertino labelMedium', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'whiteCupertino labelSmall', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none),
);
/// A Material Design text theme with dark glyphs based on San Francisco.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
///
/// This theme uses the macOS version of the font names.
static const TextTheme blackRedwoodCity = TextTheme(
displayLarge: TextStyle(debugLabel: 'blackRedwoodCity displayLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'blackRedwoodCity displayMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'blackRedwoodCity displaySmall', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'blackRedwoodCity headlineLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'blackRedwoodCity headlineMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'blackRedwoodCity headlineSmall', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'blackRedwoodCity titleLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'blackRedwoodCity titleMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'blackRedwoodCity titleSmall', fontFamily: '.AppleSystemUIFont', color: Colors.black, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'blackRedwoodCity bodyLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'blackRedwoodCity bodyMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'blackRedwoodCity bodySmall', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'blackRedwoodCity labelLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'blackRedwoodCity labelMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'blackRedwoodCity labelSmall', fontFamily: '.AppleSystemUIFont', color: Colors.black, decoration: TextDecoration.none),
);
/// A Material Design text theme with light glyphs based on San Francisco.
///
/// This [TextTheme] provides color but not geometry (font size, weight, etc).
///
/// This theme uses the macOS version of the font names.
static const TextTheme whiteRedwoodCity = TextTheme(
displayLarge: TextStyle(debugLabel: 'whiteRedwoodCity displayLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none),
displayMedium: TextStyle(debugLabel: 'whiteRedwoodCity displayMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none),
displaySmall: TextStyle(debugLabel: 'whiteRedwoodCity displaySmall', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none),
headlineLarge: TextStyle(debugLabel: 'whiteRedwoodCity headlineLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none),
headlineMedium: TextStyle(debugLabel: 'whiteRedwoodCity headlineMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none),
headlineSmall: TextStyle(debugLabel: 'whiteRedwoodCity headlineSmall', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none),
titleLarge: TextStyle(debugLabel: 'whiteRedwoodCity titleLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none),
titleMedium: TextStyle(debugLabel: 'whiteRedwoodCity titleMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none),
titleSmall: TextStyle(debugLabel: 'whiteRedwoodCity titleSmall', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none),
bodyLarge: TextStyle(debugLabel: 'whiteRedwoodCity bodyLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none),
bodyMedium: TextStyle(debugLabel: 'whiteRedwoodCity bodyMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none),
bodySmall: TextStyle(debugLabel: 'whiteRedwoodCity bodySmall', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none),
labelLarge: TextStyle(debugLabel: 'whiteRedwoodCity labelLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none),
labelMedium: TextStyle(debugLabel: 'whiteRedwoodCity labelMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none),
labelSmall: TextStyle(debugLabel: 'whiteRedwoodCity labelSmall', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none),
);
/// Defines text geometry for [ScriptCategory.englishLike] scripts, such as
/// English, French, Russian, etc.
static const TextTheme englishLike2014 = TextTheme(
displayLarge: TextStyle(debugLabel: 'englishLike displayLarge 2014', inherit: false, fontSize: 112.0, fontWeight: FontWeight.w100, textBaseline: TextBaseline.alphabetic),
displayMedium: TextStyle(debugLabel: 'englishLike displayMedium 2014', inherit: false, fontSize: 56.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
displaySmall: TextStyle(debugLabel: 'englishLike displaySmall 2014', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
headlineLarge: TextStyle(debugLabel: 'englishLike headlineLarge 2014', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
headlineMedium: TextStyle(debugLabel: 'englishLike headlineMedium 2014', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
headlineSmall: TextStyle(debugLabel: 'englishLike headlineSmall 2014', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
titleLarge: TextStyle(debugLabel: 'englishLike titleLarge 2014', inherit: false, fontSize: 20.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic),
titleMedium: TextStyle(debugLabel: 'englishLike titleMedium 2014', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
titleSmall: TextStyle(debugLabel: 'englishLike titleSmall 2014', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.1),
bodyLarge: TextStyle(debugLabel: 'englishLike bodyLarge 2014', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic),
bodyMedium: TextStyle(debugLabel: 'englishLike bodyMedium 2014', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
bodySmall: TextStyle(debugLabel: 'englishLike bodySmall 2014', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
labelLarge: TextStyle(debugLabel: 'englishLike labelLarge 2014', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic),
labelMedium: TextStyle(debugLabel: 'englishLike labelMedium 2014', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
labelSmall: TextStyle(debugLabel: 'englishLike labelSmall 2014', inherit: false, fontSize: 10.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 1.5),
);
/// Defines text geometry for [ScriptCategory.englishLike] scripts, such as
/// English, French, Russian, etc.
///
/// The font sizes, weights, and letter spacings in this version match the
/// [2018 Material Design specification](https://material.io/go/design-typography#typography-styles).
static const TextTheme englishLike2018 = TextTheme(
displayLarge: TextStyle(debugLabel: 'englishLike displayLarge 2018', inherit: false, fontSize: 96.0, fontWeight: FontWeight.w300, textBaseline: TextBaseline.alphabetic, letterSpacing: -1.5),
displayMedium: TextStyle(debugLabel: 'englishLike displayMedium 2018', inherit: false, fontSize: 60.0, fontWeight: FontWeight.w300, textBaseline: TextBaseline.alphabetic, letterSpacing: -0.5),
displaySmall: TextStyle(debugLabel: 'englishLike displaySmall 2018', inherit: false, fontSize: 48.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.0),
headlineLarge: TextStyle(debugLabel: 'englishLike headlineLarge 2018', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.25),
headlineMedium: TextStyle(debugLabel: 'englishLike headlineMedium 2018', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.25),
headlineSmall: TextStyle(debugLabel: 'englishLike headlineSmall 2018', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.0),
titleLarge: TextStyle(debugLabel: 'englishLike titleLarge 2018', inherit: false, fontSize: 20.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.15),
titleMedium: TextStyle(debugLabel: 'englishLike titleMedium 2018', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.15),
titleSmall: TextStyle(debugLabel: 'englishLike titleSmall 2018', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.1),
bodyLarge: TextStyle(debugLabel: 'englishLike bodyLarge 2018', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.5),
bodyMedium: TextStyle(debugLabel: 'englishLike bodyMedium 2018', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.25),
bodySmall: TextStyle(debugLabel: 'englishLike bodySmall 2018', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.4),
labelLarge: TextStyle(debugLabel: 'englishLike labelLarge 2018', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic, letterSpacing: 1.25),
labelMedium: TextStyle(debugLabel: 'englishLike labelMedium 2018', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 1.5),
labelSmall: TextStyle(debugLabel: 'englishLike labelSmall 2018', inherit: false, fontSize: 10.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 1.5),
);
/// Defines text geometry for dense scripts, such as Chinese, Japanese
/// and Korean.
static const TextTheme dense2014 = TextTheme(
displayLarge: TextStyle(debugLabel: 'dense displayLarge 2014', inherit: false, fontSize: 112.0, fontWeight: FontWeight.w100, textBaseline: TextBaseline.ideographic),
displayMedium: TextStyle(debugLabel: 'dense displayMedium 2014', inherit: false, fontSize: 56.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
displaySmall: TextStyle(debugLabel: 'dense displaySmall 2014', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
headlineLarge: TextStyle(debugLabel: 'dense headlineLarge 2014', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
headlineMedium: TextStyle(debugLabel: 'dense headlineMedium 2014', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
headlineSmall: TextStyle(debugLabel: 'dense headlineSmall 2014', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
titleLarge: TextStyle(debugLabel: 'dense titleLarge 2014', inherit: false, fontSize: 21.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic),
titleMedium: TextStyle(debugLabel: 'dense titleMedium 2014', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
titleSmall: TextStyle(debugLabel: 'dense titleSmall 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic),
bodyLarge: TextStyle(debugLabel: 'dense bodyLarge 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic),
bodyMedium: TextStyle(debugLabel: 'dense bodyMedium 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
bodySmall: TextStyle(debugLabel: 'dense bodySmall 2014', inherit: false, fontSize: 13.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
labelLarge: TextStyle(debugLabel: 'dense labelLarge 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic),
labelMedium: TextStyle(debugLabel: 'dense labelMedium 2014', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
labelSmall: TextStyle(debugLabel: 'dense labelSmall 2014', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
);
/// Defines text geometry for dense scripts, such as Chinese, Japanese
/// and Korean.
///
/// The font sizes, weights, and letter spacings in this version match the
/// 2018 [Material Design specification](https://material.io/go/design-typography#typography-styles).
static const TextTheme dense2018 = TextTheme(
displayLarge: TextStyle(debugLabel: 'dense displayLarge 2018', inherit: false, fontSize: 96.0, fontWeight: FontWeight.w100, textBaseline: TextBaseline.ideographic),
displayMedium: TextStyle(debugLabel: 'dense displayMedium 2018', inherit: false, fontSize: 60.0, fontWeight: FontWeight.w100, textBaseline: TextBaseline.ideographic),
displaySmall: TextStyle(debugLabel: 'dense displaySmall 2018', inherit: false, fontSize: 48.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
headlineLarge: TextStyle(debugLabel: 'dense headlineLarge 2018', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
headlineMedium: TextStyle(debugLabel: 'dense headlineMedium 2018', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
headlineSmall: TextStyle(debugLabel: 'dense headlineSmall 2018', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
titleLarge: TextStyle(debugLabel: 'dense titleLarge 2018', inherit: false, fontSize: 21.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic),
titleMedium: TextStyle(debugLabel: 'dense titleMedium 2018', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
titleSmall: TextStyle(debugLabel: 'dense titleSmall 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic),
bodyLarge: TextStyle(debugLabel: 'dense bodyLarge 2018', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
bodyMedium: TextStyle(debugLabel: 'dense bodyMedium 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
bodySmall: TextStyle(debugLabel: 'dense bodySmall 2018', inherit: false, fontSize: 13.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
labelLarge: TextStyle(debugLabel: 'dense labelLarge 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic),
labelMedium: TextStyle(debugLabel: 'dense labelMedium 2018', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
labelSmall: TextStyle(debugLabel: 'dense labelSmall 2018', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic),
);
/// Defines text geometry for tall scripts, such as Farsi, Hindi, and Thai.
static const TextTheme tall2014 = TextTheme(
displayLarge: TextStyle(debugLabel: 'tall displayLarge 2014', inherit: false, fontSize: 112.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
displayMedium: TextStyle(debugLabel: 'tall displayMedium 2014', inherit: false, fontSize: 56.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
displaySmall: TextStyle(debugLabel: 'tall displaySmall 2014', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
headlineLarge: TextStyle(debugLabel: 'tall headlineLarge 2014', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
headlineMedium: TextStyle(debugLabel: 'tall headlineMedium 2014', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
headlineSmall: TextStyle(debugLabel: 'tall headlineSmall 2014', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
titleLarge: TextStyle(debugLabel: 'tall titleLarge 2014', inherit: false, fontSize: 21.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic),
titleMedium: TextStyle(debugLabel: 'tall titleMedium 2014', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
titleSmall: TextStyle(debugLabel: 'tall titleSmall 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic),
bodyLarge: TextStyle(debugLabel: 'tall bodyLarge 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic),
bodyMedium: TextStyle(debugLabel: 'tall bodyMedium 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
bodySmall: TextStyle(debugLabel: 'tall bodySmall 2014', inherit: false, fontSize: 13.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
labelLarge: TextStyle(debugLabel: 'tall labelLarge 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic),
labelMedium: TextStyle(debugLabel: 'tall labelMedium 2014', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
labelSmall: TextStyle(debugLabel: 'tall labelSmall 2014', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
);
/// Defines text geometry for tall scripts, such as Farsi, Hindi, and Thai.
///
/// The font sizes, weights, and letter spacings in this version match the
/// 2018 [Material Design specification](https://material.io/go/design-typography#typography-styles).
static const TextTheme tall2018 = TextTheme(
displayLarge: TextStyle(debugLabel: 'tall displayLarge 2018', inherit: false, fontSize: 96.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
displayMedium: TextStyle(debugLabel: 'tall displayMedium 2018', inherit: false, fontSize: 60.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
displaySmall: TextStyle(debugLabel: 'tall displaySmall 2018', inherit: false, fontSize: 48.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
headlineLarge: TextStyle(debugLabel: 'tall headlineLarge 2018', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
headlineMedium: TextStyle(debugLabel: 'tall headlineMedium 2018', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
headlineSmall: TextStyle(debugLabel: 'tall headlineSmall 2018', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
titleLarge: TextStyle(debugLabel: 'tall titleLarge 2018', inherit: false, fontSize: 21.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic),
titleMedium : TextStyle(debugLabel: 'tall titleMedium 2018', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
titleSmall: TextStyle(debugLabel: 'tall titleSmall 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic),
bodyLarge: TextStyle(debugLabel: 'tall bodyLarge 2018', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic),
bodyMedium: TextStyle(debugLabel: 'tall bodyMedium 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
bodySmall: TextStyle(debugLabel: 'tall bodySmall 2018', inherit: false, fontSize: 13.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
labelLarge: TextStyle(debugLabel: 'tall labelLarge 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic),
labelMedium: TextStyle(debugLabel: 'tall labelMedium 2018', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
labelSmall: TextStyle(debugLabel: 'tall labelSmall 2018', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic),
);
/// Defines text geometry for [ScriptCategory.englishLike] scripts, such as
/// English, French, Russian, etc.
///
/// The font sizes, weights, and letter spacings in this version match the
/// [2021 Material Design 3 specification](https://m3.material.io/styles/typography/overview).
static const TextTheme englishLike2021 = _M3Typography.englishLike;
/// Defines text geometry for dense scripts, such as Chinese, Japanese
/// and Korean.
///
/// The Material Design 3 specification does not include 'dense' text themes,
/// so this is just here to be consistent with the API.
static const TextTheme dense2021 = _M3Typography.dense;
/// Defines text geometry for tall scripts, such as Farsi, Hindi, and Thai.
///
/// The Material Design 3 specification does not include 'tall' text themes,
/// so this is just here to be consistent with the API.
static const TextTheme tall2021 = _M3Typography.tall;
}
// BEGIN GENERATED TOKEN PROPERTIES - Typography
// 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.
abstract final class _M3Typography {
static const TextTheme englishLike = TextTheme(
displayLarge: TextStyle(debugLabel: 'englishLike displayLarge 2021', inherit: false, fontSize: 57.0, fontWeight: FontWeight.w400, letterSpacing: -0.25, height: 1.12, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
displayMedium: TextStyle(debugLabel: 'englishLike displayMedium 2021', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.16, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
displaySmall: TextStyle(debugLabel: 'englishLike displaySmall 2021', inherit: false, fontSize: 36.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.22, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
headlineLarge: TextStyle(debugLabel: 'englishLike headlineLarge 2021', inherit: false, fontSize: 32.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.25, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
headlineMedium: TextStyle(debugLabel: 'englishLike headlineMedium 2021', inherit: false, fontSize: 28.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.29, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
headlineSmall: TextStyle(debugLabel: 'englishLike headlineSmall 2021', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.33, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
titleLarge: TextStyle(debugLabel: 'englishLike titleLarge 2021', inherit: false, fontSize: 22.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.27, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
titleMedium: TextStyle(debugLabel: 'englishLike titleMedium 2021', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w500, letterSpacing: 0.15, height: 1.50, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
titleSmall: TextStyle(debugLabel: 'englishLike titleSmall 2021', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, letterSpacing: 0.1, height: 1.43, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
labelLarge: TextStyle(debugLabel: 'englishLike labelLarge 2021', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, letterSpacing: 0.1, height: 1.43, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
labelMedium: TextStyle(debugLabel: 'englishLike labelMedium 2021', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w500, letterSpacing: 0.5, height: 1.33, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
labelSmall: TextStyle(debugLabel: 'englishLike labelSmall 2021', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w500, letterSpacing: 0.5, height: 1.45, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
bodyLarge: TextStyle(debugLabel: 'englishLike bodyLarge 2021', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w400, letterSpacing: 0.5, height: 1.50, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
bodyMedium: TextStyle(debugLabel: 'englishLike bodyMedium 2021', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w400, letterSpacing: 0.25, height: 1.43, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
bodySmall: TextStyle(debugLabel: 'englishLike bodySmall 2021', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, letterSpacing: 0.4, height: 1.33, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
);
static const TextTheme dense = TextTheme(
displayLarge: TextStyle(debugLabel: 'dense displayLarge 2021', inherit: false, fontSize: 57.0, fontWeight: FontWeight.w400, letterSpacing: -0.25, height: 1.12, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
displayMedium: TextStyle(debugLabel: 'dense displayMedium 2021', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.16, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
displaySmall: TextStyle(debugLabel: 'dense displaySmall 2021', inherit: false, fontSize: 36.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.22, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
headlineLarge: TextStyle(debugLabel: 'dense headlineLarge 2021', inherit: false, fontSize: 32.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.25, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
headlineMedium: TextStyle(debugLabel: 'dense headlineMedium 2021', inherit: false, fontSize: 28.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.29, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
headlineSmall: TextStyle(debugLabel: 'dense headlineSmall 2021', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.33, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
titleLarge: TextStyle(debugLabel: 'dense titleLarge 2021', inherit: false, fontSize: 22.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.27, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
titleMedium: TextStyle(debugLabel: 'dense titleMedium 2021', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w500, letterSpacing: 0.15, height: 1.50, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
titleSmall: TextStyle(debugLabel: 'dense titleSmall 2021', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, letterSpacing: 0.1, height: 1.43, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
labelLarge: TextStyle(debugLabel: 'dense labelLarge 2021', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, letterSpacing: 0.1, height: 1.43, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
labelMedium: TextStyle(debugLabel: 'dense labelMedium 2021', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w500, letterSpacing: 0.5, height: 1.33, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
labelSmall: TextStyle(debugLabel: 'dense labelSmall 2021', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w500, letterSpacing: 0.5, height: 1.45, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
bodyLarge: TextStyle(debugLabel: 'dense bodyLarge 2021', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w400, letterSpacing: 0.5, height: 1.50, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
bodyMedium: TextStyle(debugLabel: 'dense bodyMedium 2021', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w400, letterSpacing: 0.25, height: 1.43, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
bodySmall: TextStyle(debugLabel: 'dense bodySmall 2021', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, letterSpacing: 0.4, height: 1.33, textBaseline: TextBaseline.ideographic, leadingDistribution: TextLeadingDistribution.even),
);
static const TextTheme tall = TextTheme(
displayLarge: TextStyle(debugLabel: 'tall displayLarge 2021', inherit: false, fontSize: 57.0, fontWeight: FontWeight.w400, letterSpacing: -0.25, height: 1.12, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
displayMedium: TextStyle(debugLabel: 'tall displayMedium 2021', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.16, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
displaySmall: TextStyle(debugLabel: 'tall displaySmall 2021', inherit: false, fontSize: 36.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.22, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
headlineLarge: TextStyle(debugLabel: 'tall headlineLarge 2021', inherit: false, fontSize: 32.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.25, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
headlineMedium: TextStyle(debugLabel: 'tall headlineMedium 2021', inherit: false, fontSize: 28.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.29, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
headlineSmall: TextStyle(debugLabel: 'tall headlineSmall 2021', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.33, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
titleLarge: TextStyle(debugLabel: 'tall titleLarge 2021', inherit: false, fontSize: 22.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.27, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
titleMedium: TextStyle(debugLabel: 'tall titleMedium 2021', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w500, letterSpacing: 0.15, height: 1.50, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
titleSmall: TextStyle(debugLabel: 'tall titleSmall 2021', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, letterSpacing: 0.1, height: 1.43, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
labelLarge: TextStyle(debugLabel: 'tall labelLarge 2021', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, letterSpacing: 0.1, height: 1.43, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
labelMedium: TextStyle(debugLabel: 'tall labelMedium 2021', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w500, letterSpacing: 0.5, height: 1.33, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
labelSmall: TextStyle(debugLabel: 'tall labelSmall 2021', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w500, letterSpacing: 0.5, height: 1.45, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
bodyLarge: TextStyle(debugLabel: 'tall bodyLarge 2021', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w400, letterSpacing: 0.5, height: 1.50, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
bodyMedium: TextStyle(debugLabel: 'tall bodyMedium 2021', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w400, letterSpacing: 0.25, height: 1.43, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
bodySmall: TextStyle(debugLabel: 'tall bodySmall 2021', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, letterSpacing: 0.4, height: 1.33, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even),
);
}
// END GENERATED TOKEN PROPERTIES - Typography
| flutter/packages/flutter/lib/src/material/typography.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/typography.dart",
"repo_id": "flutter",
"token_count": 20861
} | 639 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:ui' show Color, lerpDouble;
import 'package:flutter/foundation.dart';
double _getHue(double red, double green, double blue, double max, double delta) {
late double hue;
if (max == 0.0) {
hue = 0.0;
} else if (max == red) {
hue = 60.0 * (((green - blue) / delta) % 6);
} else if (max == green) {
hue = 60.0 * (((blue - red) / delta) + 2);
} else if (max == blue) {
hue = 60.0 * (((red - green) / delta) + 4);
}
/// Set hue to 0.0 when red == green == blue.
hue = hue.isNaN ? 0.0 : hue;
return hue;
}
Color _colorFromHue(
double alpha,
double hue,
double chroma,
double secondary,
double match,
) {
double red;
double green;
double blue;
if (hue < 60.0) {
red = chroma;
green = secondary;
blue = 0.0;
} else if (hue < 120.0) {
red = secondary;
green = chroma;
blue = 0.0;
} else if (hue < 180.0) {
red = 0.0;
green = chroma;
blue = secondary;
} else if (hue < 240.0) {
red = 0.0;
green = secondary;
blue = chroma;
} else if (hue < 300.0) {
red = secondary;
green = 0.0;
blue = chroma;
} else {
red = chroma;
green = 0.0;
blue = secondary;
}
return Color.fromARGB((alpha * 0xFF).round(), ((red + match) * 0xFF).round(), ((green + match) * 0xFF).round(), ((blue + match) * 0xFF).round());
}
/// A color represented using [alpha], [hue], [saturation], and [value].
///
/// An [HSVColor] is represented in a parameter space that's based on human
/// perception of color in pigments (e.g. paint and printer's ink). The
/// representation is useful for some color computations (e.g. rotating the hue
/// through the colors), because interpolation and picking of
/// colors as red, green, and blue channels doesn't always produce intuitive
/// results.
///
/// The HSV color space models the way that different pigments are perceived
/// when mixed. The hue describes which pigment is used, the saturation
/// describes which shade of the pigment, and the value resembles mixing the
/// pigment with different amounts of black or white pigment.
///
/// See also:
///
/// * [HSLColor], a color that uses a color space based on human perception of
/// colored light.
/// * [HSV and HSL](https://en.wikipedia.org/wiki/HSL_and_HSV) Wikipedia
/// article, which this implementation is based upon.
@immutable
class HSVColor {
/// Creates a color.
///
/// All the arguments must be in their respective ranges. See the fields for
/// each parameter for a description of their ranges.
const HSVColor.fromAHSV(this.alpha, this.hue, this.saturation, this.value)
: assert(alpha >= 0.0),
assert(alpha <= 1.0),
assert(hue >= 0.0),
assert(hue <= 360.0),
assert(saturation >= 0.0),
assert(saturation <= 1.0),
assert(value >= 0.0),
assert(value <= 1.0);
/// Creates an [HSVColor] from an RGB [Color].
///
/// This constructor does not necessarily round-trip with [toColor] because
/// of floating point imprecision.
factory HSVColor.fromColor(Color color) {
final double red = color.red / 0xFF;
final double green = color.green / 0xFF;
final double blue = color.blue / 0xFF;
final double max = math.max(red, math.max(green, blue));
final double min = math.min(red, math.min(green, blue));
final double delta = max - min;
final double alpha = color.alpha / 0xFF;
final double hue = _getHue(red, green, blue, max, delta);
final double saturation = max == 0.0 ? 0.0 : delta / max;
return HSVColor.fromAHSV(alpha, hue, saturation, max);
}
/// Alpha, from 0.0 to 1.0. The describes the transparency of the color.
/// A value of 0.0 is fully transparent, and 1.0 is fully opaque.
final double alpha;
/// Hue, from 0.0 to 360.0. Describes which color of the spectrum is
/// represented. A value of 0.0 represents red, as does 360.0. Values in
/// between go through all the hues representable in RGB. You can think of
/// this as selecting which pigment will be added to a color.
final double hue;
/// Saturation, from 0.0 to 1.0. This describes how colorful the color is.
/// 0.0 implies a shade of grey (i.e. no pigment), and 1.0 implies a color as
/// vibrant as that hue gets. You can think of this as the equivalent of
/// how much of a pigment is added.
final double saturation;
/// Value, from 0.0 to 1.0. The "value" of a color that, in this context,
/// describes how bright a color is. A value of 0.0 indicates black, and 1.0
/// indicates full intensity color. You can think of this as the equivalent of
/// removing black from the color as value increases.
final double value;
/// Returns a copy of this color with the [alpha] parameter replaced with the
/// given value.
HSVColor withAlpha(double alpha) {
return HSVColor.fromAHSV(alpha, hue, saturation, value);
}
/// Returns a copy of this color with the [hue] parameter replaced with the
/// given value.
HSVColor withHue(double hue) {
return HSVColor.fromAHSV(alpha, hue, saturation, value);
}
/// Returns a copy of this color with the [saturation] parameter replaced with
/// the given value.
HSVColor withSaturation(double saturation) {
return HSVColor.fromAHSV(alpha, hue, saturation, value);
}
/// Returns a copy of this color with the [value] parameter replaced with the
/// given value.
HSVColor withValue(double value) {
return HSVColor.fromAHSV(alpha, hue, saturation, value);
}
/// Returns this color in RGB.
Color toColor() {
final double chroma = saturation * value;
final double secondary = chroma * (1.0 - (((hue / 60.0) % 2.0) - 1.0).abs());
final double match = value - chroma;
return _colorFromHue(alpha, hue, chroma, secondary, match);
}
HSVColor _scaleAlpha(double factor) {
return withAlpha(alpha * factor);
}
/// Linearly interpolate between two HSVColors.
///
/// The colors are interpolated by interpolating the [alpha], [hue],
/// [saturation], and [value] channels separately, which usually leads to a
/// more pleasing effect than [Color.lerp] (which interpolates the red, green,
/// and blue channels separately).
///
/// If either color is null, this function linearly interpolates from a
/// transparent instance of the other color. This is usually preferable to
/// interpolating from [Colors.transparent] (`const Color(0x00000000)`) since
/// that will interpolate from a transparent red and cycle through the hues to
/// match the target color, regardless of what that color's hue is.
///
/// {@macro dart.ui.shadow.lerp}
///
/// Values outside of the valid range for each channel will be clamped.
static HSVColor? lerp(HSVColor? a, HSVColor? b, double t) {
if (identical(a, b)) {
return a;
}
if (a == null) {
return b!._scaleAlpha(t);
}
if (b == null) {
return a._scaleAlpha(1.0 - t);
}
return HSVColor.fromAHSV(
clampDouble(lerpDouble(a.alpha, b.alpha, t)!, 0.0, 1.0),
lerpDouble(a.hue, b.hue, t)! % 360.0,
clampDouble(lerpDouble(a.saturation, b.saturation, t)!, 0.0, 1.0),
clampDouble(lerpDouble(a.value, b.value, t)!, 0.0, 1.0),
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is HSVColor
&& other.alpha == alpha
&& other.hue == hue
&& other.saturation == saturation
&& other.value == value;
}
@override
int get hashCode => Object.hash(alpha, hue, saturation, value);
@override
String toString() => '${objectRuntimeType(this, 'HSVColor')}($alpha, $hue, $saturation, $value)';
}
/// A color represented using [alpha], [hue], [saturation], and [lightness].
///
/// An [HSLColor] is represented in a parameter space that's based up human
/// perception of colored light. The representation is useful for some color
/// computations (e.g., combining colors of light), because interpolation and
/// picking of colors as red, green, and blue channels doesn't always produce
/// intuitive results.
///
/// HSL is a perceptual color model, placing fully saturated colors around a
/// circle (conceptually) at a lightness of 0.5, with a lightness of 0.0 being
/// completely black, and a lightness of 1.0 being completely white. As the
/// lightness increases or decreases from 0.5, the apparent saturation decreases
/// proportionally (even though the [saturation] parameter hasn't changed).
///
/// See also:
///
/// * [HSVColor], a color that uses a color space based on human perception of
/// pigments (e.g. paint and printer's ink).
/// * [HSV and HSL](https://en.wikipedia.org/wiki/HSL_and_HSV) Wikipedia
/// article, which this implementation is based upon.
@immutable
class HSLColor {
/// Creates a color.
///
/// All the arguments must be in their respective ranges. See the fields for
/// each parameter for a description of their ranges.
const HSLColor.fromAHSL(this.alpha, this.hue, this.saturation, this.lightness)
: assert(alpha >= 0.0),
assert(alpha <= 1.0),
assert(hue >= 0.0),
assert(hue <= 360.0),
assert(saturation >= 0.0),
assert(saturation <= 1.0),
assert(lightness >= 0.0),
assert(lightness <= 1.0);
/// Creates an [HSLColor] from an RGB [Color].
///
/// This constructor does not necessarily round-trip with [toColor] because
/// of floating point imprecision.
factory HSLColor.fromColor(Color color) {
final double red = color.red / 0xFF;
final double green = color.green / 0xFF;
final double blue = color.blue / 0xFF;
final double max = math.max(red, math.max(green, blue));
final double min = math.min(red, math.min(green, blue));
final double delta = max - min;
final double alpha = color.alpha / 0xFF;
final double hue = _getHue(red, green, blue, max, delta);
final double lightness = (max + min) / 2.0;
// Saturation can exceed 1.0 with rounding errors, so clamp it.
final double saturation = lightness == 1.0
? 0.0
: clampDouble(delta / (1.0 - (2.0 * lightness - 1.0).abs()), 0.0, 1.0);
return HSLColor.fromAHSL(alpha, hue, saturation, lightness);
}
/// Alpha, from 0.0 to 1.0. The describes the transparency of the color.
/// A value of 0.0 is fully transparent, and 1.0 is fully opaque.
final double alpha;
/// Hue, from 0.0 to 360.0. Describes which color of the spectrum is
/// represented. A value of 0.0 represents red, as does 360.0. Values in
/// between go through all the hues representable in RGB. You can think of
/// this as selecting which color filter is placed over a light.
final double hue;
/// Saturation, from 0.0 to 1.0. This describes how colorful the color is.
/// 0.0 implies a shade of grey (i.e. no pigment), and 1.0 implies a color as
/// vibrant as that hue gets. You can think of this as the purity of the
/// color filter over the light.
final double saturation;
/// Lightness, from 0.0 to 1.0. The lightness of a color describes how bright
/// a color is. A value of 0.0 indicates black, and 1.0 indicates white. You
/// can think of this as the intensity of the light behind the filter. As the
/// lightness approaches 0.5, the colors get brighter and appear more
/// saturated, and over 0.5, the colors start to become less saturated and
/// approach white at 1.0.
final double lightness;
/// Returns a copy of this color with the alpha parameter replaced with the
/// given value.
HSLColor withAlpha(double alpha) {
return HSLColor.fromAHSL(alpha, hue, saturation, lightness);
}
/// Returns a copy of this color with the [hue] parameter replaced with the
/// given value.
HSLColor withHue(double hue) {
return HSLColor.fromAHSL(alpha, hue, saturation, lightness);
}
/// Returns a copy of this color with the [saturation] parameter replaced with
/// the given value.
HSLColor withSaturation(double saturation) {
return HSLColor.fromAHSL(alpha, hue, saturation, lightness);
}
/// Returns a copy of this color with the [lightness] parameter replaced with
/// the given value.
HSLColor withLightness(double lightness) {
return HSLColor.fromAHSL(alpha, hue, saturation, lightness);
}
/// Returns this HSL color in RGB.
Color toColor() {
final double chroma = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
final double secondary = chroma * (1.0 - (((hue / 60.0) % 2.0) - 1.0).abs());
final double match = lightness - chroma / 2.0;
return _colorFromHue(alpha, hue, chroma, secondary, match);
}
HSLColor _scaleAlpha(double factor) {
return withAlpha(alpha * factor);
}
/// Linearly interpolate between two HSLColors.
///
/// The colors are interpolated by interpolating the [alpha], [hue],
/// [saturation], and [lightness] channels separately, which usually leads to
/// a more pleasing effect than [Color.lerp] (which interpolates the red,
/// green, and blue channels separately).
///
/// If either color is null, this function linearly interpolates from a
/// transparent instance of the other color. This is usually preferable to
/// interpolating from [Colors.transparent] (`const Color(0x00000000)`) since
/// that will interpolate from a transparent red and cycle through the hues to
/// match the target color, regardless of what that color's hue is.
///
/// The `t` argument represents position on the timeline, with 0.0 meaning
/// that the interpolation has not started, returning `a` (or something
/// equivalent to `a`), 1.0 meaning that the interpolation has finished,
/// returning `b` (or something equivalent to `b`), and values between them
/// meaning that the interpolation is at the relevant point on the timeline
/// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
/// 1.0, so negative values and values greater than 1.0 are valid
/// (and can easily be generated by curves such as [Curves.elasticInOut]).
///
/// Values outside of the valid range for each channel will be clamped.
///
/// Values for `t` are usually obtained from an [Animation<double>], such as
/// an [AnimationController].
static HSLColor? lerp(HSLColor? a, HSLColor? b, double t) {
if (identical(a, b)) {
return a;
}
if (a == null) {
return b!._scaleAlpha(t);
}
if (b == null) {
return a._scaleAlpha(1.0 - t);
}
return HSLColor.fromAHSL(
clampDouble(lerpDouble(a.alpha, b.alpha, t)!, 0.0, 1.0),
lerpDouble(a.hue, b.hue, t)! % 360.0,
clampDouble(lerpDouble(a.saturation, b.saturation, t)!, 0.0, 1.0),
clampDouble(lerpDouble(a.lightness, b.lightness, t)!, 0.0, 1.0),
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is HSLColor
&& other.alpha == alpha
&& other.hue == hue
&& other.saturation == saturation
&& other.lightness == lightness;
}
@override
int get hashCode => Object.hash(alpha, hue, saturation, lightness);
@override
String toString() => '${objectRuntimeType(this, 'HSLColor')}($alpha, $hue, $saturation, $lightness)';
}
/// A color that has a small table of related colors called a "swatch".
///
/// The table is indexed by values of type `T`.
///
/// See also:
///
/// * [MaterialColor] and [MaterialAccentColor], which define Material Design
/// primary and accent color swatches.
/// * [material.Colors], which defines all of the standard Material Design
/// colors.
@immutable
class ColorSwatch<T> extends Color {
/// Creates a color that has a small table of related colors called a "swatch".
///
/// The `primary` argument should be the 32 bit ARGB value of one of the
/// values in the swatch, as would be passed to the [Color.new] constructor
/// for that same color, and as is exposed by [value]. (This is distinct from
/// the specific index of the color in the swatch.)
const ColorSwatch(super.primary, this._swatch);
@protected
final Map<T, Color> _swatch;
/// Returns an element of the swatch table.
Color? operator [](T index) => _swatch[index];
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return super == other
&& other is ColorSwatch<T>
&& mapEquals<T, Color>(other._swatch, _swatch);
}
@override
int get hashCode => Object.hash(runtimeType, value, _swatch);
@override
String toString() => '${objectRuntimeType(this, 'ColorSwatch')}(primary value: ${super.toString()})';
/// Linearly interpolate between two [ColorSwatch]es.
///
/// It delegates to [Color.lerp] to interpolate the different colors of the
/// swatch.
///
/// If either color is null, this function linearly interpolates from a
/// transparent instance of the other color.
///
/// The `t` argument represents position on the timeline, with 0.0 meaning
/// that the interpolation has not started, returning `a` (or something
/// equivalent to `a`), 1.0 meaning that the interpolation has finished,
/// returning `b` (or something equivalent to `b`), and values in between
/// meaning that the interpolation is at the relevant point on the timeline
/// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
/// 1.0, so negative values and values greater than 1.0 are valid (and can
/// easily be generated by curves such as [Curves.elasticInOut]). Each channel
/// will be clamped to the range 0 to 255.
///
/// Values for `t` are usually obtained from an [Animation<double>], such as
/// an [AnimationController].
static ColorSwatch<T>? lerp<T>(ColorSwatch<T>? a, ColorSwatch<T>? b, double t) {
if (identical(a, b)) {
return a;
}
final Map<T, Color> swatch;
if (b == null) {
swatch = a!._swatch.map((T key, Color color) => MapEntry<T, Color>(key, Color.lerp(color, null, t)!));
} else {
if (a == null) {
swatch = b._swatch.map((T key, Color color) => MapEntry<T, Color>(key, Color.lerp(null, color, t)!));
} else {
swatch = a._swatch.map((T key, Color color) => MapEntry<T, Color>(key, Color.lerp(color, b[key], t)!));
}
}
return ColorSwatch<T>(Color.lerp(a, b, t)!.value, swatch);
}
}
/// [DiagnosticsProperty] that has an [Color] as value.
class ColorProperty extends DiagnosticsProperty<Color> {
/// Create a diagnostics property for [Color].
ColorProperty(
String super.name,
super.value, {
super.showName,
super.defaultValue,
super.style,
super.level,
});
@override
Map<String, Object?> toJsonMap(DiagnosticsSerializationDelegate delegate) {
final Map<String, Object?> json = super.toJsonMap(delegate);
if (value != null) {
json['valueProperties'] = <String, Object>{
'red': value!.red,
'green': value!.green,
'blue': value!.blue,
'alpha': value!.alpha,
};
}
return json;
}
}
| flutter/packages/flutter/lib/src/painting/colors.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/colors.dart",
"repo_id": "flutter",
"token_count": 6412
} | 640 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'basic_types.dart';
import 'borders.dart';
import 'edge_insets.dart';
/// Defines the relative size and alignment of one <LinearBorder> edge.
///
/// A [LinearBorder] defines a box outline as zero to four edges, each
/// of which is rendered as a single line. The width and color of the
/// lines is defined by [LinearBorder.side].
///
/// Each line's length is defined by [size], a value between 0.0 and 1.0
/// (the default) which defines the length as a percentage of the
/// length of a box edge.
///
/// When [size] is less than 1.0, the line is aligned within the
/// available space according to [alignment], a value between -1.0 and
/// 1.0. The default is 0.0, which means centered, -1.0 means align on the
/// "start" side, and 1.0 means align on the "end" side. The meaning of
/// start and end depend on the current [TextDirection], see
/// [Directionality].
@immutable
class LinearBorderEdge {
/// Defines one side of a [LinearBorder].
///
/// The values of [size] and [alignment] must be between
/// 0.0 and 1.0, and -1.0 and 1.0 respectively.
const LinearBorderEdge({
this.size = 1.0,
this.alignment = 0.0,
}) : assert(size >= 0.0 && size <= 1.0);
/// A value between 0.0 and 1.0 that defines the length of the edge as a
/// percentage of the length of the corresponding box
/// edge. Default is 1.0.
final double size;
/// A value between -1.0 and 1.0 that defines how edges for which [size]
/// is less than 1.0 are aligned relative to the corresponding box edge.
///
/// * -1.0, aligned in the "start" direction. That's left
/// for [TextDirection.ltr] and right for [TextDirection.rtl].
/// * 0.0, centered.
/// * 1.0, aligned in the "end" direction. That's right
/// for [TextDirection.ltr] and left for [TextDirection.rtl].
final double alignment;
/// Linearly interpolates between two [LinearBorder]s.
///
/// If both `a` and `b` are null then null is returned. If `a` is null
/// then we interpolate to `b` varying [size] from 0.0 to `b.size`. If `b`
/// is null then we interpolate from `a` varying size from `a.size` to zero.
/// Otherwise both values are interpolated.
static LinearBorderEdge? lerp(LinearBorderEdge? a, LinearBorderEdge? b, double t) {
if (identical(a, b)) {
return a;
}
a ??= LinearBorderEdge(alignment: b!.alignment, size: 0);
b ??= LinearBorderEdge(alignment: a.alignment, size: 0);
return LinearBorderEdge(
size: lerpDouble(a.size, b.size, t)!,
alignment: lerpDouble(a.alignment, b.alignment, t)!,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is LinearBorderEdge
&& other.size == size
&& other.alignment == alignment;
}
@override
int get hashCode => Object.hash(size, alignment);
@override
String toString() {
final StringBuffer s = StringBuffer('${objectRuntimeType(this, 'LinearBorderEdge')}(');
if (size != 1.0 ) {
s.write('size: $size');
}
if (alignment != 0) {
final String comma = size != 1.0 ? ', ' : '';
s.write('${comma}alignment: $alignment');
}
s.write(')');
return s.toString();
}
}
/// An [OutlinedBorder] like [BoxBorder] that allows one to define a rectangular (box) border
/// in terms of zero to four [LinearBorderEdge]s, each of which is rendered as a single line.
///
/// The color and width of each line are defined by [side]. When [LinearBorder] is used
/// with a class whose border sides and shape are defined by a [ButtonStyle], then a non-null
/// [ButtonStyle.side] will override the one specified here. For example the [LinearBorder]
/// in the [TextButton] example below adds a red underline to the button. This is because
/// TextButton's `side` parameter overrides the `side` property of its [ButtonStyle.shape].
///
/// ```dart
/// TextButton(
/// style: TextButton.styleFrom(
/// side: const BorderSide(color: Colors.red),
/// shape: const LinearBorder(
/// side: BorderSide(color: Colors.blue),
/// bottom: LinearBorderEdge(),
/// ),
/// ),
/// onPressed: () { },
/// child: const Text('Red LinearBorder'),
/// )
///```
///
/// This class resolves itself against the current [TextDirection] (see [Directionality]).
/// Start and end values resolve to left and right for [TextDirection.ltr] and to
/// right and left for [TextDirection.rtl].
///
/// Convenience constructors are included for the common case where just one edge is specified:
/// [LinearBorder.start], [LinearBorder.end], [LinearBorder.top], [LinearBorder.bottom].
///
/// {@tool dartpad}
/// This example shows how to draw different kinds of [LinearBorder]s.
///
/// ** See code in examples/api/lib/painting/linear_border/linear_border.0.dart **
/// {@end-tool}
class LinearBorder extends OutlinedBorder {
/// Creates a rectangular box border that's rendered as zero to four lines.
const LinearBorder({
super.side,
this.start,
this.end,
this.top,
this.bottom,
});
/// Creates a rectangular box border with an edge on the left for [TextDirection.ltr]
/// or on the right for [TextDirection.rtl].
LinearBorder.start({
super.side,
double alignment = 0.0,
double size = 1.0
}) : start = LinearBorderEdge(alignment: alignment, size: size),
end = null,
top = null,
bottom = null;
/// Creates a rectangular box border with an edge on the right for [TextDirection.ltr]
/// or on the left for [TextDirection.rtl].
LinearBorder.end({
super.side,
double alignment = 0.0,
double size = 1.0
}) : start = null,
end = LinearBorderEdge(alignment: alignment, size: size),
top = null,
bottom = null;
/// Creates a rectangular box border with an edge on the top.
LinearBorder.top({
super.side,
double alignment = 0.0,
double size = 1.0
}) : start = null,
end = null,
top = LinearBorderEdge(alignment: alignment, size: size),
bottom = null;
/// Creates a rectangular box border with an edge on the bottom.
LinearBorder.bottom({
super.side,
double alignment = 0.0,
double size = 1.0
}) : start = null,
end = null,
top = null,
bottom = LinearBorderEdge(alignment: alignment, size: size);
/// No border.
static const LinearBorder none = LinearBorder();
/// Defines the left edge for [TextDirection.ltr] or the right
/// for [TextDirection.rtl].
final LinearBorderEdge? start;
/// Defines the right edge for [TextDirection.ltr] or the left
/// for [TextDirection.rtl].
final LinearBorderEdge? end;
/// Defines the top edge.
final LinearBorderEdge? top;
/// Defines the bottom edge.
final LinearBorderEdge? bottom;
@override
LinearBorder scale(double t) {
return LinearBorder(
side: side.scale(t),
);
}
@override
EdgeInsetsGeometry get dimensions {
final double width = side.width;
return EdgeInsetsDirectional.fromSTEB(
start == null ? 0.0 : width,
top == null ? 0.0 : width,
end == null ? 0.0 : width,
bottom == null ? 0.0 : width,
);
}
@override
ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
if (a is LinearBorder) {
return LinearBorder(
side: BorderSide.lerp(a.side, side, t),
start: LinearBorderEdge.lerp(a.start, start, t),
end: LinearBorderEdge.lerp(a.end, end, t),
top: LinearBorderEdge.lerp(a.top, top, t),
bottom: LinearBorderEdge.lerp(a.bottom, bottom, t),
);
}
return super.lerpFrom(a, t);
}
@override
ShapeBorder? lerpTo(ShapeBorder? b, double t) {
if (b is LinearBorder) {
return LinearBorder(
side: BorderSide.lerp(side, b.side, t),
start: LinearBorderEdge.lerp(start, b.start, t),
end: LinearBorderEdge.lerp(end, b.end, t),
top: LinearBorderEdge.lerp(top, b.top, t),
bottom: LinearBorderEdge.lerp(bottom, b.bottom, t),
);
}
return super.lerpTo(b, t);
}
/// Returns a copy of this LinearBorder with the given fields replaced with
/// the new values.
@override
LinearBorder copyWith({
BorderSide? side,
LinearBorderEdge? start,
LinearBorderEdge? end,
LinearBorderEdge? top,
LinearBorderEdge? bottom,
}) {
return LinearBorder(
side: side ?? this.side,
start: start ?? this.start,
end: end ?? this.end,
top: top ?? this.top,
bottom: bottom ?? this.bottom,
);
}
@override
Path getInnerPath(Rect rect, { TextDirection? textDirection }) {
final Rect adjustedRect = dimensions.resolve(textDirection).deflateRect(rect);
return Path()
..addRect(adjustedRect);
}
@override
Path getOuterPath(Rect rect, { TextDirection? textDirection }) {
return Path()
..addRect(rect);
}
@override
void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) {
final EdgeInsets insets = dimensions.resolve(textDirection);
final bool rtl = textDirection == TextDirection.rtl;
final Path path = Path();
final Paint paint = Paint()
..strokeWidth = 0.0;
void drawEdge(Rect rect, Color color) {
paint.color = color;
path.reset();
path.moveTo(rect.left, rect.top);
if (rect.width == 0.0) {
paint.style = PaintingStyle.stroke;
path.lineTo(rect.left, rect.bottom);
} else if (rect.height == 0.0) {
paint.style = PaintingStyle.stroke;
path.lineTo(rect.right, rect.top);
} else {
paint.style = PaintingStyle.fill;
path.lineTo(rect.right, rect.top);
path.lineTo(rect.right, rect.bottom);
path.lineTo(rect.left, rect.bottom);
}
canvas.drawPath(path, paint);
}
if (start != null && start!.size != 0.0 && side.style != BorderStyle.none) {
final Rect insetRect = Rect.fromLTWH(rect.left, rect.top + insets.top, rect.width, rect.height - insets.vertical);
final double x = rtl ? rect.right - insets.right : rect.left;
final double width = rtl ? insets.right : insets.left;
final double height = insetRect.height * start!.size;
final double y = (insetRect.height - height) * ((start!.alignment + 1.0) / 2.0);
final Rect r = Rect.fromLTWH(x, y, width, height);
drawEdge(r, side.color);
}
if (end != null && end!.size != 0.0 && side.style != BorderStyle.none) {
final Rect insetRect = Rect.fromLTWH(rect.left, rect.top + insets.top, rect.width, rect.height - insets.vertical);
final double x = rtl ? rect.left : rect.right - insets.right;
final double width = rtl ? insets.left : insets.right;
final double height = insetRect.height * end!.size;
final double y = (insetRect.height - height) * ((end!.alignment + 1.0) / 2.0);
final Rect r = Rect.fromLTWH(x, y, width, height);
drawEdge(r, side.color);
}
if (top != null && top!.size != 0.0 && side.style != BorderStyle.none) {
final double width = rect.width * top!.size;
final double startX = (rect.width - width) * ((top!.alignment + 1.0) / 2.0);
final double x = rtl ? rect.width - startX - width : startX;
final Rect r = Rect.fromLTWH(x, rect.top, width, insets.top);
drawEdge(r, side.color);
}
if (bottom != null && bottom!.size != 0.0 && side.style != BorderStyle.none) {
final double width = rect.width * bottom!.size;
final double startX = (rect.width - width) * ((bottom!.alignment + 1.0) / 2.0);
final double x = rtl ? rect.width - startX - width: startX;
final Rect r = Rect.fromLTWH(x, rect.bottom - insets.bottom, width, side.width);
drawEdge(r, side.color);
}
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is LinearBorder
&& other.side == side
&& other.start == start
&& other.end == end
&& other.top == top
&& other.bottom == bottom;
}
@override
int get hashCode => Object.hash(side, start, end, top, bottom);
@override
String toString() {
if (this == LinearBorder.none) {
return 'LinearBorder.none';
}
final StringBuffer s = StringBuffer('${objectRuntimeType(this, 'LinearBorder')}(side: $side');
if (start != null ) {
s.write(', start: $start');
}
if (end != null ) {
s.write(', end: $end');
}
if (top != null ) {
s.write(', top: $top');
}
if (bottom != null ) {
s.write(', bottom: $bottom');
}
s.write(')');
return s.toString();
}
}
| flutter/packages/flutter/lib/src/painting/linear_border.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/linear_border.dart",
"repo_id": "flutter",
"token_count": 4775
} | 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 'package:flutter/foundation.dart';
import 'simulation.dart';
export 'simulation.dart' show Simulation;
/// A simulation that applies limits to another simulation.
///
/// The limits are only applied to the other simulation's outputs. For example,
/// if a maximum position was applied to a gravity simulation with the
/// particle's initial velocity being up, and the acceleration being down, and
/// the maximum position being between the initial position and the curve's
/// apogee, then the particle would return to its initial position in the same
/// amount of time as it would have if the maximum had not been applied; the
/// difference would just be that the position would be reported as pinned to
/// the maximum value for the times that it would otherwise have been reported
/// as higher.
///
/// Similarly, this means that the [x] value will change at a rate that does not
/// match the reported [dx] value while one or the other is being clamped.
///
/// The [isDone] logic is unaffected by the clamping; it reflects the logic of
/// the underlying simulation.
class ClampedSimulation extends Simulation {
/// Creates a [ClampedSimulation] that clamps the given simulation.
///
/// The named arguments specify the ranges for the clamping behavior, as
/// applied to [x] and [dx].
ClampedSimulation(
this.simulation, {
this.xMin = double.negativeInfinity,
this.xMax = double.infinity,
this.dxMin = double.negativeInfinity,
this.dxMax = double.infinity,
}) : assert(xMax >= xMin),
assert(dxMax >= dxMin);
/// The simulation being clamped. Calls to [x], [dx], and [isDone] are
/// forwarded to the simulation.
final Simulation simulation;
/// The minimum to apply to [x].
final double xMin;
/// The maximum to apply to [x].
final double xMax;
/// The minimum to apply to [dx].
final double dxMin;
/// The maximum to apply to [dx].
final double dxMax;
@override
double x(double time) => clampDouble(simulation.x(time), xMin, xMax);
@override
double dx(double time) => clampDouble(simulation.dx(time), dxMin, dxMax);
@override
bool isDone(double time) => simulation.isDone(time);
@override
String toString() => '${objectRuntimeType(this, 'ClampedSimulation')}(simulation: $simulation, x: ${xMin.toStringAsFixed(1)}..${xMax.toStringAsFixed(1)}, dx: ${dxMin.toStringAsFixed(1)}..${dxMax.toStringAsFixed(1)})';
}
| flutter/packages/flutter/lib/src/physics/clamped_simulation.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/physics/clamped_simulation.dart",
"repo_id": "flutter",
"token_count": 735
} | 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' as ui show Paragraph, ParagraphBuilder, ParagraphConstraints, ParagraphStyle, TextStyle;
import 'package:flutter/foundation.dart';
import 'box.dart';
import 'object.dart';
const double _kMaxWidth = 100000.0;
const double _kMaxHeight = 100000.0;
/// A render object used as a placeholder when an error occurs.
///
/// The box will be painted in the color given by the
/// [RenderErrorBox.backgroundColor] static property.
///
/// A message can be provided. To simplify the class and thus help reduce the
/// likelihood of this class itself being the source of errors, the message
/// cannot be changed once the object has been created. If provided, the text
/// will be painted on top of the background, using the styles given by the
/// [RenderErrorBox.textStyle] and [RenderErrorBox.paragraphStyle] static
/// properties.
///
/// Again to help simplify the class, if the parent has left the constraints
/// unbounded, this box tries to be 100000.0 pixels wide and high, to
/// approximate being infinitely high but without using infinities.
class RenderErrorBox extends RenderBox {
/// Creates a RenderErrorBox render object.
///
/// A message can optionally be provided. If a message is provided, an attempt
/// will be made to render the message when the box paints.
RenderErrorBox([ this.message = '' ]) {
try {
if (message != '') {
// This class is intentionally doing things using the low-level
// primitives to avoid depending on any subsystems that may have ended
// up in an unstable state -- after all, this class is mainly used when
// things have gone wrong.
//
// Generally, the much better way to draw text in a RenderObject is to
// use the TextPainter class. If you're looking for code to crib from,
// see the paragraph.dart file and the RenderParagraph class.
final ui.ParagraphBuilder builder = ui.ParagraphBuilder(paragraphStyle);
builder.pushStyle(textStyle);
builder.addText(message);
_paragraph = builder.build();
} else {
_paragraph = null;
}
} catch (error) {
// If an error happens here we're in a terrible state, so we really should
// just forget about it and let the developer deal with the already-reported
// errors. It's unlikely that these errors are going to help with that.
}
}
/// The message to attempt to display at paint time.
final String message;
late final ui.Paragraph? _paragraph;
@override
double computeMaxIntrinsicWidth(double height) {
return _kMaxWidth;
}
@override
double computeMaxIntrinsicHeight(double width) {
return _kMaxHeight;
}
@override
bool get sizedByParent => true;
@override
bool hitTestSelf(Offset position) => true;
@override
@protected
Size computeDryLayout(covariant BoxConstraints constraints) {
return constraints.constrain(const Size(_kMaxWidth, _kMaxHeight));
}
/// The distance to place around the text.
///
/// This is intended to ensure that if the [RenderErrorBox] is placed at the top left
/// of the screen, under the system's status bar, the error text is still visible in
/// the area below the status bar.
///
/// The padding is ignored if the error box is smaller than the padding.
///
/// See also:
///
/// * [minimumWidth], which controls how wide the box must be before the
/// horizontal padding is applied.
static EdgeInsets padding = const EdgeInsets.fromLTRB(64.0, 96.0, 64.0, 12.0);
/// The width below which the horizontal padding is not applied.
///
/// If the left and right padding would reduce the available width to less than
/// this value, then the text is rendered flush with the left edge.
static double minimumWidth = 200.0;
/// The color to use when painting the background of [RenderErrorBox] objects.
///
/// Defaults to red in debug mode, a light gray otherwise.
static Color backgroundColor = _initBackgroundColor();
static Color _initBackgroundColor() {
Color result = const Color(0xF0C0C0C0);
assert(() {
result = const Color(0xF0900000);
return true;
}());
return result;
}
/// The text style to use when painting [RenderErrorBox] objects.
///
/// Defaults to a yellow monospace font in debug mode, and a dark gray
/// sans-serif font otherwise.
static ui.TextStyle textStyle = _initTextStyle();
static ui.TextStyle _initTextStyle() {
ui.TextStyle result = ui.TextStyle(
color: const Color(0xFF303030),
fontFamily: 'sans-serif',
fontSize: 18.0,
);
assert(() {
result = ui.TextStyle(
color: const Color(0xFFFFFF66),
fontFamily: 'monospace',
fontSize: 14.0,
fontWeight: FontWeight.bold,
);
return true;
}());
return result;
}
/// The paragraph style to use when painting [RenderErrorBox] objects.
static ui.ParagraphStyle paragraphStyle = ui.ParagraphStyle(
textDirection: TextDirection.ltr,
textAlign: TextAlign.left,
);
@override
void paint(PaintingContext context, Offset offset) {
try {
context.canvas.drawRect(offset & size, Paint() .. color = backgroundColor);
if (_paragraph != null) {
double width = size.width;
double left = 0.0;
double top = 0.0;
if (width > padding.left + minimumWidth + padding.right) {
width -= padding.left + padding.right;
left += padding.left;
}
_paragraph.layout(ui.ParagraphConstraints(width: width));
if (size.height > padding.top + _paragraph.height + padding.bottom) {
top += padding.top;
}
context.canvas.drawParagraph(_paragraph, offset + Offset(left, top));
}
} catch (error) {
// If an error happens here we're in a terrible state, so we really should
// just forget about it and let the developer deal with the already-reported
// errors. It's unlikely that these errors are going to help with that.
}
}
}
| flutter/packages/flutter/lib/src/rendering/error.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/error.dart",
"repo_id": "flutter",
"token_count": 2009
} | 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 'package:flutter/foundation.dart';
import 'package:vector_math/vector_math_64.dart';
import 'layer.dart';
import 'object.dart';
/// The result after handling a [SelectionEvent].
///
/// [SelectionEvent]s are sent from [SelectionRegistrar] to be handled by
/// [SelectionHandler.dispatchSelectionEvent]. The subclasses of
/// [SelectionHandler] or [Selectable] must return appropriate
/// [SelectionResult]s after handling the events.
///
/// This is used by the [SelectionContainer] to determine how a selection
/// expands across its [Selectable] children.
enum SelectionResult {
/// There is nothing left to select forward in this [Selectable], and further
/// selection should extend to the next [Selectable] in screen order.
///
/// {@template flutter.rendering.selection.SelectionResult.footNote}
/// This is used after subclasses [SelectionHandler] or [Selectable] handled
/// [SelectionEdgeUpdateEvent].
/// {@endtemplate}
next,
/// Selection does not reach this [Selectable] and is located before it in
/// screen order.
///
/// {@macro flutter.rendering.selection.SelectionResult.footNote}
previous,
/// Selection ends in this [Selectable].
///
/// Part of the [Selectable] may or may not be selected, but there is still
/// content to select forward or backward.
///
/// {@macro flutter.rendering.selection.SelectionResult.footNote}
end,
/// The result can't be determined in this frame.
///
/// This is typically used when the subtree is scrolling to reveal more
/// content.
///
/// {@macro flutter.rendering.selection.SelectionResult.footNote}
// See `_SelectableRegionState._triggerSelectionEndEdgeUpdate` for how this
// result affects the selection.
pending,
/// There is no result for the selection event.
///
/// This is used when a selection result is not applicable, e.g.
/// [SelectAllSelectionEvent], [ClearSelectionEvent], and
/// [SelectWordSelectionEvent].
none,
}
/// The abstract interface to handle [SelectionEvent]s.
///
/// This interface is extended by [Selectable] and [SelectionContainerDelegate]
/// and is typically not used directly.
///
/// {@template flutter.rendering.SelectionHandler}
/// This class returns a [SelectionGeometry] as its [value], and is responsible
/// to notify its listener when its selection geometry has changed as the result
/// of receiving selection events.
/// {@endtemplate}
abstract class SelectionHandler implements ValueListenable<SelectionGeometry> {
/// Marks this handler to be responsible for pushing [LeaderLayer]s for the
/// selection handles.
///
/// This handler is responsible for pushing the leader layers with the
/// given layer links if they are not null. It is possible that only one layer
/// is non-null if this handler is only responsible for pushing one layer
/// link.
///
/// The `startHandle` needs to be placed at the visual location of selection
/// start, the `endHandle` needs to be placed at the visual location of selection
/// end. Typically, the visual locations should be the same as
/// [SelectionGeometry.startSelectionPoint] and
/// [SelectionGeometry.endSelectionPoint].
void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle);
/// Gets the selected content in this object.
///
/// Return `null` if nothing is selected.
SelectedContent? getSelectedContent();
/// Handles the [SelectionEvent] sent to this object.
///
/// The subclasses need to update their selections or delegate the
/// [SelectionEvent]s to their subtrees.
///
/// The `event`s are subclasses of [SelectionEvent]. Check
/// [SelectionEvent.type] to determine what kinds of event are dispatched to
/// this handler and handle them accordingly.
///
/// See also:
/// * [SelectionEventType], which contains all of the possible types.
SelectionResult dispatchSelectionEvent(SelectionEvent event);
}
/// The selected content in a [Selectable] or [SelectionHandler].
// TODO(chunhtai): Add more support for rich content.
// https://github.com/flutter/flutter/issues/104206.
class SelectedContent {
/// Creates a selected content object.
///
/// Only supports plain text.
const SelectedContent({required this.plainText});
/// The selected content in plain text format.
final String plainText;
}
/// A mixin that can be selected by users when under a [SelectionArea] widget.
///
/// This object receives selection events and the [value] must reflect the
/// current selection in this [Selectable]. The object must also notify its
/// listener if the [value] ever changes.
///
/// This object is responsible for drawing the selection highlight.
///
/// In order to receive the selection event, the mixer needs to register
/// itself to [SelectionRegistrar]s. Use
/// [SelectionContainer.maybeOf] to get the selection registrar, and
/// mix the [SelectionRegistrant] to subscribe to the [SelectionRegistrar]
/// automatically.
///
/// This mixin is typically mixed by [RenderObject]s. The [RenderObject.paint]
/// methods are responsible to push the [LayerLink]s provided to
/// [pushHandleLayers].
///
/// {@macro flutter.rendering.SelectionHandler}
///
/// See also:
/// * [SelectionArea], which provides an overview of selection system.
mixin Selectable implements SelectionHandler {
/// {@macro flutter.rendering.RenderObject.getTransformTo}
Matrix4 getTransformTo(RenderObject? ancestor);
/// The size of this [Selectable].
Size get size;
/// A list of [Rect]s that represent the bounding box of this [Selectable]
/// in local coordinates.
List<Rect> get boundingBoxes;
/// Disposes resources held by the mixer.
void dispose();
}
/// A mixin to auto-register the mixer to the [registrar].
///
/// To use this mixin, the mixer needs to set the [registrar] to the
/// [SelectionRegistrar] it wants to register to.
///
/// This mixin only registers the mixer with the [registrar] if the
/// [SelectionGeometry.hasContent] returned by the mixer is true.
mixin SelectionRegistrant on Selectable {
/// The [SelectionRegistrar] the mixer will be or is registered to.
///
/// This [Selectable] only registers the mixer if the
/// [SelectionGeometry.hasContent] returned by the [Selectable] is true.
SelectionRegistrar? get registrar => _registrar;
SelectionRegistrar? _registrar;
set registrar(SelectionRegistrar? value) {
if (value == _registrar) {
return;
}
if (value == null) {
// When registrar goes from non-null to null;
removeListener(_updateSelectionRegistrarSubscription);
} else if (_registrar == null) {
// When registrar goes from null to non-null;
addListener(_updateSelectionRegistrarSubscription);
}
_removeSelectionRegistrarSubscription();
_registrar = value;
_updateSelectionRegistrarSubscription();
}
@override
void dispose() {
_removeSelectionRegistrarSubscription();
super.dispose();
}
bool _subscribedToSelectionRegistrar = false;
void _updateSelectionRegistrarSubscription() {
if (_registrar == null) {
_subscribedToSelectionRegistrar = false;
return;
}
if (_subscribedToSelectionRegistrar && !value.hasContent) {
_registrar!.remove(this);
_subscribedToSelectionRegistrar = false;
} else if (!_subscribedToSelectionRegistrar && value.hasContent) {
_registrar!.add(this);
_subscribedToSelectionRegistrar = true;
}
}
void _removeSelectionRegistrarSubscription() {
if (_subscribedToSelectionRegistrar) {
_registrar!.remove(this);
_subscribedToSelectionRegistrar = false;
}
}
}
/// A utility class that provides useful methods for handling selection events.
abstract final class SelectionUtils {
/// Determines [SelectionResult] purely based on the target rectangle.
///
/// This method returns [SelectionResult.end] if the `point` is inside the
/// `targetRect`. Returns [SelectionResult.previous] if the `point` is
/// considered to be lower than `targetRect` in screen order. Returns
/// [SelectionResult.next] if the point is considered to be higher than
/// `targetRect` in screen order.
static SelectionResult getResultBasedOnRect(Rect targetRect, Offset point) {
if (targetRect.contains(point)) {
return SelectionResult.end;
}
if (point.dy < targetRect.top) {
return SelectionResult.previous;
}
if (point.dy > targetRect.bottom) {
return SelectionResult.next;
}
return point.dx >= targetRect.right
? SelectionResult.next
: SelectionResult.previous;
}
/// Adjusts the dragging offset based on the target rect.
///
/// This method moves the offsets to be within the target rect in case they are
/// outside the rect.
///
/// This is used in the case where a drag happens outside of the rectangle
/// of a [Selectable].
///
/// The logic works as the following:
/// 
///
/// For points inside the rect:
/// Their effective locations are unchanged.
///
/// For points in Area 1:
/// Move them to top-left of the rect if text direction is ltr, or top-right
/// if rtl.
///
/// For points in Area 2:
/// Move them to bottom-right of the rect if text direction is ltr, or
/// bottom-left if rtl.
static Offset adjustDragOffset(Rect targetRect, Offset point, {TextDirection direction = TextDirection.ltr}) {
if (targetRect.contains(point)) {
return point;
}
if (point.dy <= targetRect.top ||
point.dy <= targetRect.bottom && point.dx <= targetRect.left) {
// Area 1
return direction == TextDirection.ltr ? targetRect.topLeft : targetRect.topRight;
} else {
// Area 2
return direction == TextDirection.ltr ? targetRect.bottomRight : targetRect.bottomLeft;
}
}
}
/// The type of a [SelectionEvent].
///
/// Used by [SelectionEvent.type] to distinguish different types of events.
enum SelectionEventType {
/// An event to update the selection start edge.
///
/// Used by [SelectionEdgeUpdateEvent].
startEdgeUpdate,
/// An event to update the selection end edge.
///
/// Used by [SelectionEdgeUpdateEvent].
endEdgeUpdate,
/// An event to clear the current selection.
///
/// Used by [ClearSelectionEvent].
clear,
/// An event to select all the available content.
///
/// Used by [SelectAllSelectionEvent].
selectAll,
/// An event to select a word at the location
/// [SelectWordSelectionEvent.globalPosition].
///
/// Used by [SelectWordSelectionEvent].
selectWord,
/// An event that extends the selection by a specific [TextGranularity].
granularlyExtendSelection,
/// An event that extends the selection in a specific direction.
directionallyExtendSelection,
}
/// The unit of how selection handles move in text.
///
/// The [GranularlyExtendSelectionEvent] uses this enum to describe how
/// [Selectable] should extend its selection.
enum TextGranularity {
/// Treats each character as an atomic unit when moving the selection handles.
character,
/// Treats word as an atomic unit when moving the selection handles.
word,
/// Treats each line break as an atomic unit when moving the selection handles.
line,
/// Treats the entire document as an atomic unit when moving the selection handles.
document,
}
/// An abstract base class for selection events.
///
/// This should not be directly used. To handle a selection event, it should
/// be downcast to a specific subclass. One can use [type] to look up which
/// subclasses to downcast to.
///
/// See also:
/// * [SelectAllSelectionEvent], for events to select all contents.
/// * [ClearSelectionEvent], for events to clear selections.
/// * [SelectWordSelectionEvent], for events to select words at the locations.
/// * [SelectionEdgeUpdateEvent], for events to update selection edges.
/// * [SelectionEventType], for determining the subclass types.
abstract class SelectionEvent {
const SelectionEvent._(this.type);
/// The type of this selection event.
final SelectionEventType type;
}
/// Selects all selectable contents.
///
/// This event can be sent as the result of keyboard select-all, i.e.
/// ctrl + A, or cmd + A in macOS.
class SelectAllSelectionEvent extends SelectionEvent {
/// Creates a select all selection event.
const SelectAllSelectionEvent(): super._(SelectionEventType.selectAll);
}
/// Clears the selection from the [Selectable] and removes any existing
/// highlight as if there is no selection at all.
class ClearSelectionEvent extends SelectionEvent {
/// Create a clear selection event.
const ClearSelectionEvent(): super._(SelectionEventType.clear);
}
/// Selects the whole word at the location.
///
/// This event can be sent as the result of mobile long press selection.
class SelectWordSelectionEvent extends SelectionEvent {
/// Creates a select word event at the [globalPosition].
const SelectWordSelectionEvent({required this.globalPosition}): super._(SelectionEventType.selectWord);
/// The position in global coordinates to select word at.
final Offset globalPosition;
}
/// Updates a selection edge.
///
/// An active selection contains two edges, start and end. Use the [type] to
/// determine which edge this event applies to. If the [type] is
/// [SelectionEventType.startEdgeUpdate], the event updates start edge. If the
/// [type] is [SelectionEventType.endEdgeUpdate], the event updates end edge.
///
/// The [globalPosition] contains the new offset of the edge.
///
/// The [granularity] contains the granularity that the selection edge should move by.
/// Only [TextGranularity.character] and [TextGranularity.word] are currently supported.
///
/// This event is dispatched when the framework detects [TapDragStartDetails] in
/// [SelectionArea]'s gesture recognizers for mouse devices, or the selection
/// handles have been dragged to new locations.
class SelectionEdgeUpdateEvent extends SelectionEvent {
/// Creates a selection start edge update event.
///
/// The [globalPosition] contains the location of the selection start edge.
///
/// The [granularity] contains the granularity which the selection edge should move by.
/// This value defaults to [TextGranularity.character].
const SelectionEdgeUpdateEvent.forStart({
required this.globalPosition,
TextGranularity? granularity
}) : granularity = granularity ?? TextGranularity.character, super._(SelectionEventType.startEdgeUpdate);
/// Creates a selection end edge update event.
///
/// The [globalPosition] contains the new location of the selection end edge.
///
/// The [granularity] contains the granularity which the selection edge should move by.
/// This value defaults to [TextGranularity.character].
const SelectionEdgeUpdateEvent.forEnd({
required this.globalPosition,
TextGranularity? granularity
}) : granularity = granularity ?? TextGranularity.character, super._(SelectionEventType.endEdgeUpdate);
/// The new location of the selection edge.
final Offset globalPosition;
/// The granularity for which the selection moves.
///
/// Only [TextGranularity.character] and [TextGranularity.word] are currently supported.
///
/// Defaults to [TextGranularity.character].
final TextGranularity granularity;
}
/// Extends the start or end of the selection by a given [TextGranularity].
///
/// To handle this event, move the associated selection edge, as dictated by
/// [isEnd], according to the [granularity].
class GranularlyExtendSelectionEvent extends SelectionEvent {
/// Creates a [GranularlyExtendSelectionEvent].
const GranularlyExtendSelectionEvent({
required this.forward,
required this.isEnd,
required this.granularity,
}) : super._(SelectionEventType.granularlyExtendSelection);
/// Whether to extend the selection forward.
final bool forward;
/// Whether this event is updating the end selection edge.
final bool isEnd;
/// The granularity for which the selection extend.
final TextGranularity granularity;
}
/// The direction to extend a selection.
///
/// The [DirectionallyExtendSelectionEvent] uses this enum to describe how
/// [Selectable] should extend their selection.
enum SelectionExtendDirection {
/// Move one edge of the selection vertically to the previous adjacent line.
///
/// For text selection, it should consider both soft and hard linebreak.
///
/// See [DirectionallyExtendSelectionEvent.dx] on how to
/// calculate the horizontal offset.
previousLine,
/// Move one edge of the selection vertically to the next adjacent line.
///
/// For text selection, it should consider both soft and hard linebreak.
///
/// See [DirectionallyExtendSelectionEvent.dx] on how to
/// calculate the horizontal offset.
nextLine,
/// Move the selection edges forward to a certain horizontal offset in the
/// same line.
///
/// If there is no on-going selection, the selection must start with the first
/// line (or equivalence of first line in a non-text selectable) and select
/// toward the horizontal offset in the same line.
///
/// The selectable that receives [DirectionallyExtendSelectionEvent] with this
/// enum must return [SelectionResult.end].
///
/// See [DirectionallyExtendSelectionEvent.dx] on how to
/// calculate the horizontal offset.
forward,
/// Move the selection edges backward to a certain horizontal offset in the
/// same line.
///
/// If there is no on-going selection, the selection must start with the last
/// line (or equivalence of last line in a non-text selectable) and select
/// backward the horizontal offset in the same line.
///
/// The selectable that receives [DirectionallyExtendSelectionEvent] with this
/// enum must return [SelectionResult.end].
///
/// See [DirectionallyExtendSelectionEvent.dx] on how to
/// calculate the horizontal offset.
backward,
}
/// Extends the current selection with respect to a [direction].
///
/// To handle this event, move the associated selection edge, as dictated by
/// [isEnd], according to the [direction].
///
/// The movements are always based on [dx]. The value is in
/// global coordinates and is the horizontal offset the selection edge should
/// move to when moving to across lines.
class DirectionallyExtendSelectionEvent extends SelectionEvent {
/// Creates a [DirectionallyExtendSelectionEvent].
const DirectionallyExtendSelectionEvent({
required this.dx,
required this.isEnd,
required this.direction,
}) : super._(SelectionEventType.directionallyExtendSelection);
/// The horizontal offset the selection should move to.
///
/// The offset is in global coordinates.
final double dx;
/// Whether this event is updating the end selection edge.
final bool isEnd;
/// The directional movement of this event.
///
/// See also:
/// * [SelectionExtendDirection], which explains how to handle each enum.
final SelectionExtendDirection direction;
/// Makes a copy of this object with its property replaced with the new
/// values.
DirectionallyExtendSelectionEvent copyWith({
double? dx,
bool? isEnd,
SelectionExtendDirection? direction,
}) {
return DirectionallyExtendSelectionEvent(
dx: dx ?? this.dx,
isEnd: isEnd ?? this.isEnd,
direction: direction ?? this.direction,
);
}
}
/// A registrar that keeps track of [Selectable]s in the subtree.
///
/// A [Selectable] is only included in the [SelectableRegion] if they are
/// registered with a [SelectionRegistrar]. Once a [Selectable] is registered,
/// it will receive [SelectionEvent]s in
/// [SelectionHandler.dispatchSelectionEvent].
///
/// Use [SelectionContainer.maybeOf] to get the immediate [SelectionRegistrar]
/// in the ancestor chain above the build context.
///
/// See also:
/// * [SelectableRegion], which provides an overview of the selection system.
/// * [SelectionRegistrarScope], which hosts the [SelectionRegistrar] for the
/// subtree.
/// * [SelectionRegistrant], which auto registers the object with the mixin to
/// [SelectionRegistrar].
abstract class SelectionRegistrar {
/// Adds the [selectable] into the registrar.
///
/// A [Selectable] must register with the [SelectionRegistrar] in order to
/// receive selection events.
void add(Selectable selectable);
/// Removes the [selectable] from the registrar.
///
/// A [Selectable] must unregister itself if it is removed from the rendering
/// tree.
void remove(Selectable selectable);
}
/// The status that indicates whether there is a selection and whether the
/// selection is collapsed.
///
/// A collapsed selection means the selection starts and ends at the same
/// location.
enum SelectionStatus {
/// The selection is not collapsed.
///
/// For example if `{}` represent the selection edges:
/// 'ab{cd}', the collapsing status is [uncollapsed].
/// '{abcd}', the collapsing status is [uncollapsed].
uncollapsed,
/// The selection is collapsed.
///
/// For example if `{}` represent the selection edges:
/// 'ab{}cd', the collapsing status is [collapsed].
/// '{}abcd', the collapsing status is [collapsed].
/// 'abcd{}', the collapsing status is [collapsed].
collapsed,
/// No selection.
none,
}
/// The geometry of the current selection.
///
/// This includes details such as the locations of the selection start and end,
/// line height, the rects that encompass the selection, etc. This information
/// is used for drawing selection controls for mobile platforms.
///
/// The positions in geometry are in local coordinates of the [SelectionHandler]
/// or [Selectable].
@immutable
class SelectionGeometry {
/// Creates a selection geometry object.
///
/// If any of the [startSelectionPoint] and [endSelectionPoint] is not null,
/// the [status] must not be [SelectionStatus.none].
const SelectionGeometry({
this.startSelectionPoint,
this.endSelectionPoint,
this.selectionRects = const <Rect>[],
required this.status,
required this.hasContent,
}) : assert((startSelectionPoint == null && endSelectionPoint == null) || status != SelectionStatus.none);
/// The geometry information at the selection start.
///
/// This information is used for drawing mobile selection controls. The
/// [SelectionPoint.localPosition] of the selection start is typically at the
/// start of the selection highlight at where the start selection handle
/// should be drawn.
///
/// The [SelectionPoint.handleType] should be [TextSelectionHandleType.left]
/// for forward selection or [TextSelectionHandleType.right] for backward
/// selection in most cases.
///
/// Can be null if the selection start is offstage, for example, when the
/// selection is outside of the viewport or is kept alive by a scrollable.
final SelectionPoint? startSelectionPoint;
/// The geometry information at the selection end.
///
/// This information is used for drawing mobile selection controls. The
/// [SelectionPoint.localPosition] of the selection end is typically at the end
/// of the selection highlight at where the end selection handle should be
/// drawn.
///
/// The [SelectionPoint.handleType] should be [TextSelectionHandleType.right]
/// for forward selection or [TextSelectionHandleType.left] for backward
/// selection in most cases.
///
/// Can be null if the selection end is offstage, for example, when the
/// selection is outside of the viewport or is kept alive by a scrollable.
final SelectionPoint? endSelectionPoint;
/// The status of ongoing selection in the [Selectable] or [SelectionHandler].
final SelectionStatus status;
/// The rects in the local coordinates of the containing [Selectable] that
/// represent the selection if there is any.
final List<Rect> selectionRects;
/// Whether there is any selectable content in the [Selectable] or
/// [SelectionHandler].
final bool hasContent;
/// Whether there is an ongoing selection.
bool get hasSelection => status != SelectionStatus.none;
/// Makes a copy of this object with the given values updated.
SelectionGeometry copyWith({
SelectionPoint? startSelectionPoint,
SelectionPoint? endSelectionPoint,
List<Rect>? selectionRects,
SelectionStatus? status,
bool? hasContent,
}) {
return SelectionGeometry(
startSelectionPoint: startSelectionPoint ?? this.startSelectionPoint,
endSelectionPoint: endSelectionPoint ?? this.endSelectionPoint,
selectionRects: selectionRects ?? this.selectionRects,
status: status ?? this.status,
hasContent: hasContent ?? this.hasContent,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is SelectionGeometry
&& other.startSelectionPoint == startSelectionPoint
&& other.endSelectionPoint == endSelectionPoint
&& other.selectionRects == selectionRects
&& other.status == status
&& other.hasContent == hasContent;
}
@override
int get hashCode {
return Object.hash(
startSelectionPoint,
endSelectionPoint,
selectionRects,
status,
hasContent,
);
}
}
/// The geometry information of a selection point.
@immutable
class SelectionPoint with Diagnosticable {
/// Creates a selection point object.
const SelectionPoint({
required this.localPosition,
required this.lineHeight,
required this.handleType,
});
/// The position of the selection point in the local coordinates of the
/// containing [Selectable].
final Offset localPosition;
/// The line height at the selection point.
final double lineHeight;
/// The selection handle type that should be used at the selection point.
///
/// This is used for building the mobile selection handle.
final TextSelectionHandleType handleType;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is SelectionPoint
&& other.localPosition == localPosition
&& other.lineHeight == lineHeight
&& other.handleType == handleType;
}
@override
int get hashCode {
return Object.hash(
localPosition,
lineHeight,
handleType,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('localPosition', localPosition));
properties.add(DoubleProperty('lineHeight', lineHeight));
properties.add(EnumProperty<TextSelectionHandleType>('handleType', handleType));
}
}
/// The type of selection handle to be displayed.
///
/// With mixed-direction text, both handles may be the same type. Examples:
///
/// * LTR text: 'the <quick brown> fox':
///
/// The '<' is drawn with the [left] type, the '>' with the [right]
///
/// * RTL text: 'XOF <NWORB KCIUQ> EHT':
///
/// Same as above.
///
/// * mixed text: '<the NWOR<B KCIUQ fox'
///
/// Here 'the QUICK B' is selected, but 'QUICK BROWN' is RTL. Both are drawn
/// with the [left] type.
///
/// See also:
///
/// * [TextDirection], which discusses left-to-right and right-to-left text in
/// more detail.
enum TextSelectionHandleType {
/// The selection handle is to the left of the selection end point.
left,
/// The selection handle is to the right of the selection end point.
right,
/// The start and end of the selection are co-incident at this point.
collapsed,
}
| flutter/packages/flutter/lib/src/rendering/selection.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/selection.dart",
"repo_id": "flutter",
"token_count": 7946
} | 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/animation.dart';
import 'package:flutter/painting.dart';
/// An interpolation between two fractional offsets.
///
/// This class specializes the interpolation of [Tween<FractionalOffset>] to be
/// appropriate for fractional offsets.
///
/// See [Tween] for a discussion on how to use interpolation objects.
///
/// See also:
///
/// * [AlignmentTween], which interpolates between to [Alignment] objects.
class FractionalOffsetTween extends Tween<FractionalOffset?> {
/// Creates a fractional offset tween.
///
/// The [begin] and [end] properties may be null; the null value
/// is treated as meaning the center.
FractionalOffsetTween({ super.begin, super.end });
/// Returns the value this variable has at the given animation clock value.
@override
FractionalOffset? lerp(double t) => FractionalOffset.lerp(begin, end, t);
}
/// An interpolation between two alignments.
///
/// This class specializes the interpolation of [Tween<Alignment>] to be
/// appropriate for alignments.
///
/// See [Tween] for a discussion on how to use interpolation objects.
///
/// See also:
///
/// * [AlignmentGeometryTween], which interpolates between two
/// [AlignmentGeometry] objects.
class AlignmentTween extends Tween<Alignment> {
/// Creates a fractional offset tween.
///
/// The [begin] and [end] properties may be null; the null value
/// is treated as meaning the center.
AlignmentTween({ super.begin, super.end });
/// Returns the value this variable has at the given animation clock value.
@override
Alignment lerp(double t) => Alignment.lerp(begin, end, t)!;
}
/// An interpolation between two [AlignmentGeometry].
///
/// This class specializes the interpolation of [Tween<AlignmentGeometry>]
/// to be appropriate for alignments.
///
/// See [Tween] for a discussion on how to use interpolation objects.
///
/// See also:
///
/// * [AlignmentTween], which interpolates between two [Alignment] objects.
class AlignmentGeometryTween extends Tween<AlignmentGeometry?> {
/// Creates a fractional offset geometry tween.
///
/// The [begin] and [end] properties may be null; the null value
/// is treated as meaning the center.
AlignmentGeometryTween({
super.begin,
super.end,
});
/// Returns the value this variable has at the given animation clock value.
@override
AlignmentGeometry? lerp(double t) => AlignmentGeometry.lerp(begin, end, t);
}
| flutter/packages/flutter/lib/src/rendering/tweens.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/tweens.dart",
"repo_id": "flutter",
"token_count": 749
} | 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 'binding.dart';
/// Stand-in for non-web platforms' [BackgroundIsolateBinaryMessenger].
class BackgroundIsolateBinaryMessenger {
/// Throws an [UnsupportedError].
static BinaryMessenger get instance {
throw UnsupportedError('Isolates not supported on web.');
}
}
| flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_web.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_web.dart",
"repo_id": "flutter",
"token_count": 124
} | 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.
// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT
// This file is generated by dev/tools/gen_keycodes/bin/gen_keycodes.dart and
// should not be edited directly.
//
// Edit the template dev/tools/gen_keycodes/data/keyboard_maps.tmpl instead.
// See dev/tools/gen_keycodes/README.md for more information.
import 'keyboard_key.g.dart';
export 'keyboard_key.g.dart' show LogicalKeyboardKey, PhysicalKeyboardKey;
/// Maps Android-specific key codes to the matching [LogicalKeyboardKey].
const Map<int, LogicalKeyboardKey> kAndroidToLogicalKey = <int, LogicalKeyboardKey>{
3: LogicalKeyboardKey.goHome,
4: LogicalKeyboardKey.goBack,
5: LogicalKeyboardKey.call,
6: LogicalKeyboardKey.endCall,
7: LogicalKeyboardKey.digit0,
8: LogicalKeyboardKey.digit1,
9: LogicalKeyboardKey.digit2,
10: LogicalKeyboardKey.digit3,
11: LogicalKeyboardKey.digit4,
12: LogicalKeyboardKey.digit5,
13: LogicalKeyboardKey.digit6,
14: LogicalKeyboardKey.digit7,
15: LogicalKeyboardKey.digit8,
16: LogicalKeyboardKey.digit9,
17: LogicalKeyboardKey.asterisk,
18: LogicalKeyboardKey.numberSign,
19: LogicalKeyboardKey.arrowUp,
20: LogicalKeyboardKey.arrowDown,
21: LogicalKeyboardKey.arrowLeft,
22: LogicalKeyboardKey.arrowRight,
23: LogicalKeyboardKey.select,
24: LogicalKeyboardKey.audioVolumeUp,
25: LogicalKeyboardKey.audioVolumeDown,
26: LogicalKeyboardKey.power,
27: LogicalKeyboardKey.camera,
28: LogicalKeyboardKey.clear,
29: LogicalKeyboardKey.keyA,
30: LogicalKeyboardKey.keyB,
31: LogicalKeyboardKey.keyC,
32: LogicalKeyboardKey.keyD,
33: LogicalKeyboardKey.keyE,
34: LogicalKeyboardKey.keyF,
35: LogicalKeyboardKey.keyG,
36: LogicalKeyboardKey.keyH,
37: LogicalKeyboardKey.keyI,
38: LogicalKeyboardKey.keyJ,
39: LogicalKeyboardKey.keyK,
40: LogicalKeyboardKey.keyL,
41: LogicalKeyboardKey.keyM,
42: LogicalKeyboardKey.keyN,
43: LogicalKeyboardKey.keyO,
44: LogicalKeyboardKey.keyP,
45: LogicalKeyboardKey.keyQ,
46: LogicalKeyboardKey.keyR,
47: LogicalKeyboardKey.keyS,
48: LogicalKeyboardKey.keyT,
49: LogicalKeyboardKey.keyU,
50: LogicalKeyboardKey.keyV,
51: LogicalKeyboardKey.keyW,
52: LogicalKeyboardKey.keyX,
53: LogicalKeyboardKey.keyY,
54: LogicalKeyboardKey.keyZ,
55: LogicalKeyboardKey.comma,
56: LogicalKeyboardKey.period,
57: LogicalKeyboardKey.altLeft,
58: LogicalKeyboardKey.altRight,
59: LogicalKeyboardKey.shiftLeft,
60: LogicalKeyboardKey.shiftRight,
61: LogicalKeyboardKey.tab,
62: LogicalKeyboardKey.space,
63: LogicalKeyboardKey.symbol,
64: LogicalKeyboardKey.launchWebBrowser,
65: LogicalKeyboardKey.launchMail,
66: LogicalKeyboardKey.enter,
67: LogicalKeyboardKey.backspace,
68: LogicalKeyboardKey.backquote,
69: LogicalKeyboardKey.minus,
70: LogicalKeyboardKey.equal,
71: LogicalKeyboardKey.bracketLeft,
72: LogicalKeyboardKey.bracketRight,
73: LogicalKeyboardKey.backslash,
74: LogicalKeyboardKey.semicolon,
75: LogicalKeyboardKey.quote,
76: LogicalKeyboardKey.slash,
77: LogicalKeyboardKey.at,
79: LogicalKeyboardKey.headsetHook,
80: LogicalKeyboardKey.cameraFocus,
81: LogicalKeyboardKey.add,
82: LogicalKeyboardKey.contextMenu,
83: LogicalKeyboardKey.notification,
84: LogicalKeyboardKey.browserSearch,
85: LogicalKeyboardKey.mediaPlayPause,
86: LogicalKeyboardKey.mediaStop,
87: LogicalKeyboardKey.mediaTrackNext,
88: LogicalKeyboardKey.mediaTrackPrevious,
89: LogicalKeyboardKey.mediaRewind,
90: LogicalKeyboardKey.mediaFastForward,
91: LogicalKeyboardKey.microphoneVolumeMute,
92: LogicalKeyboardKey.pageUp,
93: LogicalKeyboardKey.pageDown,
95: LogicalKeyboardKey.modeChange,
96: LogicalKeyboardKey.gameButtonA,
97: LogicalKeyboardKey.gameButtonB,
98: LogicalKeyboardKey.gameButtonC,
99: LogicalKeyboardKey.gameButtonX,
100: LogicalKeyboardKey.gameButtonY,
101: LogicalKeyboardKey.gameButtonZ,
102: LogicalKeyboardKey.gameButtonLeft1,
103: LogicalKeyboardKey.gameButtonRight1,
104: LogicalKeyboardKey.gameButtonLeft2,
105: LogicalKeyboardKey.gameButtonRight2,
106: LogicalKeyboardKey.gameButtonThumbLeft,
107: LogicalKeyboardKey.gameButtonThumbRight,
108: LogicalKeyboardKey.gameButtonStart,
109: LogicalKeyboardKey.gameButtonSelect,
110: LogicalKeyboardKey.gameButtonMode,
111: LogicalKeyboardKey.escape,
112: LogicalKeyboardKey.delete,
113: LogicalKeyboardKey.controlLeft,
114: LogicalKeyboardKey.controlRight,
115: LogicalKeyboardKey.capsLock,
116: LogicalKeyboardKey.scrollLock,
117: LogicalKeyboardKey.metaLeft,
118: LogicalKeyboardKey.metaRight,
119: LogicalKeyboardKey.fn,
120: LogicalKeyboardKey.printScreen,
121: LogicalKeyboardKey.pause,
122: LogicalKeyboardKey.home,
123: LogicalKeyboardKey.end,
124: LogicalKeyboardKey.insert,
125: LogicalKeyboardKey.browserForward,
126: LogicalKeyboardKey.mediaPlay,
127: LogicalKeyboardKey.mediaPause,
128: LogicalKeyboardKey.close,
129: LogicalKeyboardKey.eject,
130: LogicalKeyboardKey.mediaRecord,
131: LogicalKeyboardKey.f1,
132: LogicalKeyboardKey.f2,
133: LogicalKeyboardKey.f3,
134: LogicalKeyboardKey.f4,
135: LogicalKeyboardKey.f5,
136: LogicalKeyboardKey.f6,
137: LogicalKeyboardKey.f7,
138: LogicalKeyboardKey.f8,
139: LogicalKeyboardKey.f9,
140: LogicalKeyboardKey.f10,
141: LogicalKeyboardKey.f11,
142: LogicalKeyboardKey.f12,
143: LogicalKeyboardKey.numLock,
144: LogicalKeyboardKey.numpad0,
145: LogicalKeyboardKey.numpad1,
146: LogicalKeyboardKey.numpad2,
147: LogicalKeyboardKey.numpad3,
148: LogicalKeyboardKey.numpad4,
149: LogicalKeyboardKey.numpad5,
150: LogicalKeyboardKey.numpad6,
151: LogicalKeyboardKey.numpad7,
152: LogicalKeyboardKey.numpad8,
153: LogicalKeyboardKey.numpad9,
154: LogicalKeyboardKey.numpadDivide,
155: LogicalKeyboardKey.numpadMultiply,
156: LogicalKeyboardKey.numpadSubtract,
157: LogicalKeyboardKey.numpadAdd,
158: LogicalKeyboardKey.numpadDecimal,
159: LogicalKeyboardKey.numpadComma,
160: LogicalKeyboardKey.numpadEnter,
161: LogicalKeyboardKey.numpadEqual,
162: LogicalKeyboardKey.numpadParenLeft,
163: LogicalKeyboardKey.numpadParenRight,
164: LogicalKeyboardKey.audioVolumeMute,
165: LogicalKeyboardKey.info,
166: LogicalKeyboardKey.channelUp,
167: LogicalKeyboardKey.channelDown,
168: LogicalKeyboardKey.zoomIn,
169: LogicalKeyboardKey.zoomOut,
170: LogicalKeyboardKey.tv,
172: LogicalKeyboardKey.guide,
173: LogicalKeyboardKey.dvr,
174: LogicalKeyboardKey.browserFavorites,
175: LogicalKeyboardKey.closedCaptionToggle,
176: LogicalKeyboardKey.settings,
177: LogicalKeyboardKey.tvPower,
178: LogicalKeyboardKey.tvInput,
179: LogicalKeyboardKey.stbPower,
180: LogicalKeyboardKey.stbInput,
181: LogicalKeyboardKey.avrPower,
182: LogicalKeyboardKey.avrInput,
183: LogicalKeyboardKey.colorF0Red,
184: LogicalKeyboardKey.colorF1Green,
185: LogicalKeyboardKey.colorF2Yellow,
186: LogicalKeyboardKey.colorF3Blue,
187: LogicalKeyboardKey.appSwitch,
188: LogicalKeyboardKey.gameButton1,
189: LogicalKeyboardKey.gameButton2,
190: LogicalKeyboardKey.gameButton3,
191: LogicalKeyboardKey.gameButton4,
192: LogicalKeyboardKey.gameButton5,
193: LogicalKeyboardKey.gameButton6,
194: LogicalKeyboardKey.gameButton7,
195: LogicalKeyboardKey.gameButton8,
196: LogicalKeyboardKey.gameButton9,
197: LogicalKeyboardKey.gameButton10,
198: LogicalKeyboardKey.gameButton11,
199: LogicalKeyboardKey.gameButton12,
200: LogicalKeyboardKey.gameButton13,
201: LogicalKeyboardKey.gameButton14,
202: LogicalKeyboardKey.gameButton15,
203: LogicalKeyboardKey.gameButton16,
204: LogicalKeyboardKey.groupNext,
205: LogicalKeyboardKey.mannerMode,
206: LogicalKeyboardKey.tv3DMode,
207: LogicalKeyboardKey.launchContacts,
208: LogicalKeyboardKey.launchCalendar,
209: LogicalKeyboardKey.launchMusicPlayer,
211: LogicalKeyboardKey.zenkakuHankaku,
212: LogicalKeyboardKey.eisu,
213: LogicalKeyboardKey.nonConvert,
214: LogicalKeyboardKey.convert,
215: LogicalKeyboardKey.hiraganaKatakana,
216: LogicalKeyboardKey.intlYen,
217: LogicalKeyboardKey.intlRo,
218: LogicalKeyboardKey.kanjiMode,
219: LogicalKeyboardKey.launchAssistant,
220: LogicalKeyboardKey.brightnessDown,
221: LogicalKeyboardKey.brightnessUp,
222: LogicalKeyboardKey.mediaAudioTrack,
223: LogicalKeyboardKey.sleep,
224: LogicalKeyboardKey.wakeUp,
225: LogicalKeyboardKey.pairing,
226: LogicalKeyboardKey.mediaTopMenu,
229: LogicalKeyboardKey.mediaLast,
230: LogicalKeyboardKey.tvDataService,
232: LogicalKeyboardKey.tvRadioService,
233: LogicalKeyboardKey.teletext,
234: LogicalKeyboardKey.tvNumberEntry,
235: LogicalKeyboardKey.tvTerrestrialAnalog,
236: LogicalKeyboardKey.tvTerrestrialDigital,
237: LogicalKeyboardKey.tvSatellite,
238: LogicalKeyboardKey.tvSatelliteBS,
239: LogicalKeyboardKey.tvSatelliteCS,
240: LogicalKeyboardKey.tvSatelliteToggle,
241: LogicalKeyboardKey.tvNetwork,
242: LogicalKeyboardKey.tvAntennaCable,
243: LogicalKeyboardKey.tvInputHDMI1,
244: LogicalKeyboardKey.tvInputHDMI2,
245: LogicalKeyboardKey.tvInputHDMI3,
246: LogicalKeyboardKey.tvInputHDMI4,
247: LogicalKeyboardKey.tvInputComposite1,
248: LogicalKeyboardKey.tvInputComposite2,
249: LogicalKeyboardKey.tvInputComponent1,
250: LogicalKeyboardKey.tvInputComponent2,
251: LogicalKeyboardKey.tvInputVGA1,
252: LogicalKeyboardKey.tvAudioDescription,
253: LogicalKeyboardKey.tvAudioDescriptionMixUp,
254: LogicalKeyboardKey.tvAudioDescriptionMixDown,
255: LogicalKeyboardKey.zoomToggle,
256: LogicalKeyboardKey.tvContentsMenu,
258: LogicalKeyboardKey.tvTimer,
259: LogicalKeyboardKey.help,
260: LogicalKeyboardKey.navigatePrevious,
261: LogicalKeyboardKey.navigateNext,
262: LogicalKeyboardKey.navigateIn,
263: LogicalKeyboardKey.navigateOut,
272: LogicalKeyboardKey.mediaSkipForward,
273: LogicalKeyboardKey.mediaSkipBackward,
274: LogicalKeyboardKey.mediaStepForward,
275: LogicalKeyboardKey.mediaStepBackward,
277: LogicalKeyboardKey.cut,
278: LogicalKeyboardKey.copy,
279: LogicalKeyboardKey.paste,
};
/// Maps Android-specific scan codes to the matching [PhysicalKeyboardKey].
const Map<int, PhysicalKeyboardKey> kAndroidToPhysicalKey = <int, PhysicalKeyboardKey>{
1: PhysicalKeyboardKey.escape,
2: PhysicalKeyboardKey.digit1,
3: PhysicalKeyboardKey.digit2,
4: PhysicalKeyboardKey.digit3,
5: PhysicalKeyboardKey.digit4,
6: PhysicalKeyboardKey.digit5,
7: PhysicalKeyboardKey.digit6,
8: PhysicalKeyboardKey.digit7,
9: PhysicalKeyboardKey.digit8,
10: PhysicalKeyboardKey.digit9,
11: PhysicalKeyboardKey.digit0,
12: PhysicalKeyboardKey.minus,
13: PhysicalKeyboardKey.equal,
14: PhysicalKeyboardKey.backspace,
15: PhysicalKeyboardKey.tab,
16: PhysicalKeyboardKey.keyQ,
17: PhysicalKeyboardKey.keyW,
18: PhysicalKeyboardKey.keyE,
19: PhysicalKeyboardKey.keyR,
20: PhysicalKeyboardKey.keyT,
21: PhysicalKeyboardKey.keyY,
22: PhysicalKeyboardKey.keyU,
23: PhysicalKeyboardKey.keyI,
24: PhysicalKeyboardKey.keyO,
25: PhysicalKeyboardKey.keyP,
26: PhysicalKeyboardKey.bracketLeft,
27: PhysicalKeyboardKey.bracketRight,
28: PhysicalKeyboardKey.enter,
29: PhysicalKeyboardKey.controlLeft,
30: PhysicalKeyboardKey.keyA,
31: PhysicalKeyboardKey.keyS,
32: PhysicalKeyboardKey.keyD,
33: PhysicalKeyboardKey.keyF,
34: PhysicalKeyboardKey.keyG,
35: PhysicalKeyboardKey.keyH,
36: PhysicalKeyboardKey.keyJ,
37: PhysicalKeyboardKey.keyK,
38: PhysicalKeyboardKey.keyL,
39: PhysicalKeyboardKey.semicolon,
40: PhysicalKeyboardKey.quote,
41: PhysicalKeyboardKey.backquote,
42: PhysicalKeyboardKey.shiftLeft,
43: PhysicalKeyboardKey.backslash,
44: PhysicalKeyboardKey.keyZ,
45: PhysicalKeyboardKey.keyX,
46: PhysicalKeyboardKey.keyC,
47: PhysicalKeyboardKey.keyV,
48: PhysicalKeyboardKey.keyB,
49: PhysicalKeyboardKey.keyN,
50: PhysicalKeyboardKey.keyM,
51: PhysicalKeyboardKey.comma,
52: PhysicalKeyboardKey.period,
53: PhysicalKeyboardKey.slash,
54: PhysicalKeyboardKey.shiftRight,
55: PhysicalKeyboardKey.numpadMultiply,
56: PhysicalKeyboardKey.altLeft,
57: PhysicalKeyboardKey.space,
58: PhysicalKeyboardKey.capsLock,
59: PhysicalKeyboardKey.f1,
60: PhysicalKeyboardKey.f2,
61: PhysicalKeyboardKey.f3,
62: PhysicalKeyboardKey.f4,
63: PhysicalKeyboardKey.f5,
64: PhysicalKeyboardKey.f6,
65: PhysicalKeyboardKey.f7,
66: PhysicalKeyboardKey.f8,
67: PhysicalKeyboardKey.f9,
68: PhysicalKeyboardKey.f10,
69: PhysicalKeyboardKey.numLock,
70: PhysicalKeyboardKey.scrollLock,
71: PhysicalKeyboardKey.numpad7,
72: PhysicalKeyboardKey.numpad8,
73: PhysicalKeyboardKey.numpad9,
74: PhysicalKeyboardKey.numpadSubtract,
75: PhysicalKeyboardKey.numpad4,
76: PhysicalKeyboardKey.numpad5,
77: PhysicalKeyboardKey.numpad6,
78: PhysicalKeyboardKey.numpadAdd,
79: PhysicalKeyboardKey.numpad1,
80: PhysicalKeyboardKey.numpad2,
81: PhysicalKeyboardKey.numpad3,
82: PhysicalKeyboardKey.numpad0,
83: PhysicalKeyboardKey.numpadDecimal,
86: PhysicalKeyboardKey.backslash,
87: PhysicalKeyboardKey.f11,
88: PhysicalKeyboardKey.f12,
89: PhysicalKeyboardKey.intlRo,
90: PhysicalKeyboardKey.lang3,
91: PhysicalKeyboardKey.lang4,
92: PhysicalKeyboardKey.convert,
94: PhysicalKeyboardKey.nonConvert,
95: PhysicalKeyboardKey.numpadComma,
96: PhysicalKeyboardKey.numpadEnter,
97: PhysicalKeyboardKey.controlRight,
98: PhysicalKeyboardKey.numpadDivide,
99: PhysicalKeyboardKey.printScreen,
100: PhysicalKeyboardKey.altRight,
102: PhysicalKeyboardKey.home,
103: PhysicalKeyboardKey.arrowUp,
104: PhysicalKeyboardKey.pageUp,
105: PhysicalKeyboardKey.arrowLeft,
106: PhysicalKeyboardKey.arrowRight,
107: PhysicalKeyboardKey.end,
108: PhysicalKeyboardKey.arrowDown,
109: PhysicalKeyboardKey.pageDown,
110: PhysicalKeyboardKey.insert,
111: PhysicalKeyboardKey.delete,
113: PhysicalKeyboardKey.audioVolumeMute,
114: PhysicalKeyboardKey.audioVolumeDown,
115: PhysicalKeyboardKey.audioVolumeUp,
116: PhysicalKeyboardKey.power,
117: PhysicalKeyboardKey.numpadEqual,
119: PhysicalKeyboardKey.pause,
121: PhysicalKeyboardKey.numpadComma,
124: PhysicalKeyboardKey.intlYen,
125: PhysicalKeyboardKey.metaLeft,
126: PhysicalKeyboardKey.metaRight,
127: PhysicalKeyboardKey.contextMenu,
128: PhysicalKeyboardKey.mediaStop,
129: PhysicalKeyboardKey.again,
130: PhysicalKeyboardKey.props,
131: PhysicalKeyboardKey.undo,
133: PhysicalKeyboardKey.copy,
134: PhysicalKeyboardKey.open,
135: PhysicalKeyboardKey.paste,
136: PhysicalKeyboardKey.find,
137: PhysicalKeyboardKey.cut,
138: PhysicalKeyboardKey.help,
139: PhysicalKeyboardKey.contextMenu,
142: PhysicalKeyboardKey.sleep,
143: PhysicalKeyboardKey.wakeUp,
152: PhysicalKeyboardKey.power,
155: PhysicalKeyboardKey.launchMail,
156: PhysicalKeyboardKey.browserFavorites,
159: PhysicalKeyboardKey.browserForward,
160: PhysicalKeyboardKey.close,
161: PhysicalKeyboardKey.eject,
162: PhysicalKeyboardKey.eject,
163: PhysicalKeyboardKey.mediaTrackNext,
164: PhysicalKeyboardKey.mediaPlayPause,
165: PhysicalKeyboardKey.mediaTrackPrevious,
166: PhysicalKeyboardKey.mediaStop,
167: PhysicalKeyboardKey.mediaRecord,
168: PhysicalKeyboardKey.mediaRewind,
174: PhysicalKeyboardKey.exit,
177: PhysicalKeyboardKey.pageUp,
178: PhysicalKeyboardKey.pageDown,
179: PhysicalKeyboardKey.numpadParenLeft,
180: PhysicalKeyboardKey.numpadParenRight,
182: PhysicalKeyboardKey.redo,
183: PhysicalKeyboardKey.f13,
184: PhysicalKeyboardKey.f14,
185: PhysicalKeyboardKey.f15,
186: PhysicalKeyboardKey.f16,
187: PhysicalKeyboardKey.f17,
188: PhysicalKeyboardKey.f18,
189: PhysicalKeyboardKey.f19,
190: PhysicalKeyboardKey.f20,
191: PhysicalKeyboardKey.f21,
192: PhysicalKeyboardKey.f22,
193: PhysicalKeyboardKey.f23,
194: PhysicalKeyboardKey.f24,
200: PhysicalKeyboardKey.mediaPlay,
201: PhysicalKeyboardKey.mediaPause,
205: PhysicalKeyboardKey.suspend,
206: PhysicalKeyboardKey.close,
207: PhysicalKeyboardKey.mediaPlay,
208: PhysicalKeyboardKey.mediaFastForward,
209: PhysicalKeyboardKey.bassBoost,
210: PhysicalKeyboardKey.print,
215: PhysicalKeyboardKey.launchMail,
217: PhysicalKeyboardKey.browserSearch,
224: PhysicalKeyboardKey.brightnessDown,
225: PhysicalKeyboardKey.brightnessUp,
256: PhysicalKeyboardKey.gameButton1,
257: PhysicalKeyboardKey.gameButton2,
258: PhysicalKeyboardKey.gameButton3,
259: PhysicalKeyboardKey.gameButton4,
260: PhysicalKeyboardKey.gameButton5,
261: PhysicalKeyboardKey.gameButton6,
262: PhysicalKeyboardKey.gameButton7,
263: PhysicalKeyboardKey.gameButton8,
264: PhysicalKeyboardKey.gameButton9,
265: PhysicalKeyboardKey.gameButton10,
266: PhysicalKeyboardKey.gameButton11,
267: PhysicalKeyboardKey.gameButton12,
268: PhysicalKeyboardKey.gameButton13,
269: PhysicalKeyboardKey.gameButton14,
270: PhysicalKeyboardKey.gameButton15,
271: PhysicalKeyboardKey.gameButton16,
288: PhysicalKeyboardKey.gameButton1,
289: PhysicalKeyboardKey.gameButton2,
290: PhysicalKeyboardKey.gameButton3,
291: PhysicalKeyboardKey.gameButton4,
292: PhysicalKeyboardKey.gameButton5,
293: PhysicalKeyboardKey.gameButton6,
294: PhysicalKeyboardKey.gameButton7,
295: PhysicalKeyboardKey.gameButton8,
296: PhysicalKeyboardKey.gameButton9,
297: PhysicalKeyboardKey.gameButton10,
298: PhysicalKeyboardKey.gameButton11,
299: PhysicalKeyboardKey.gameButton12,
300: PhysicalKeyboardKey.gameButton13,
301: PhysicalKeyboardKey.gameButton14,
302: PhysicalKeyboardKey.gameButton15,
303: PhysicalKeyboardKey.gameButton16,
304: PhysicalKeyboardKey.gameButtonA,
305: PhysicalKeyboardKey.gameButtonB,
306: PhysicalKeyboardKey.gameButtonC,
307: PhysicalKeyboardKey.gameButtonX,
308: PhysicalKeyboardKey.gameButtonY,
309: PhysicalKeyboardKey.gameButtonZ,
310: PhysicalKeyboardKey.gameButtonLeft1,
311: PhysicalKeyboardKey.gameButtonRight1,
312: PhysicalKeyboardKey.gameButtonLeft2,
313: PhysicalKeyboardKey.gameButtonRight2,
314: PhysicalKeyboardKey.gameButtonSelect,
315: PhysicalKeyboardKey.gameButtonStart,
316: PhysicalKeyboardKey.gameButtonMode,
317: PhysicalKeyboardKey.gameButtonThumbLeft,
318: PhysicalKeyboardKey.gameButtonThumbRight,
353: PhysicalKeyboardKey.select,
358: PhysicalKeyboardKey.info,
370: PhysicalKeyboardKey.closedCaptionToggle,
397: PhysicalKeyboardKey.launchCalendar,
402: PhysicalKeyboardKey.channelUp,
403: PhysicalKeyboardKey.channelDown,
405: PhysicalKeyboardKey.mediaLast,
411: PhysicalKeyboardKey.pause,
429: PhysicalKeyboardKey.launchContacts,
464: PhysicalKeyboardKey.fn,
583: PhysicalKeyboardKey.launchAssistant,
};
/// A map of Android key codes which have printable representations, but appear
/// on the number pad. Used to provide different key objects for keys like
/// KEY_EQUALS and NUMPAD_EQUALS.
const Map<int, LogicalKeyboardKey> kAndroidNumPadMap = <int, LogicalKeyboardKey>{
144: LogicalKeyboardKey.numpad0,
145: LogicalKeyboardKey.numpad1,
146: LogicalKeyboardKey.numpad2,
147: LogicalKeyboardKey.numpad3,
148: LogicalKeyboardKey.numpad4,
149: LogicalKeyboardKey.numpad5,
150: LogicalKeyboardKey.numpad6,
151: LogicalKeyboardKey.numpad7,
152: LogicalKeyboardKey.numpad8,
153: LogicalKeyboardKey.numpad9,
154: LogicalKeyboardKey.numpadDivide,
155: LogicalKeyboardKey.numpadMultiply,
156: LogicalKeyboardKey.numpadSubtract,
157: LogicalKeyboardKey.numpadAdd,
158: LogicalKeyboardKey.numpadDecimal,
159: LogicalKeyboardKey.numpadComma,
161: LogicalKeyboardKey.numpadEqual,
162: LogicalKeyboardKey.numpadParenLeft,
163: LogicalKeyboardKey.numpadParenRight,
};
/// Maps Fuchsia-specific IDs to the matching [LogicalKeyboardKey].
const Map<int, LogicalKeyboardKey> kFuchsiaToLogicalKey = <int, LogicalKeyboardKey>{
0x1200000010: LogicalKeyboardKey.hyper,
0x1200000011: LogicalKeyboardKey.superKey,
0x1200000012: LogicalKeyboardKey.fn,
0x1200000013: LogicalKeyboardKey.fnLock,
0x1200000014: LogicalKeyboardKey.suspend,
0x1200000015: LogicalKeyboardKey.resume,
0x1200010082: LogicalKeyboardKey.sleep,
0x1200010083: LogicalKeyboardKey.wakeUp,
0x120005ff01: LogicalKeyboardKey.gameButton1,
0x120005ff02: LogicalKeyboardKey.gameButton2,
0x120005ff03: LogicalKeyboardKey.gameButton3,
0x120005ff04: LogicalKeyboardKey.gameButton4,
0x120005ff05: LogicalKeyboardKey.gameButton5,
0x120005ff06: LogicalKeyboardKey.gameButton6,
0x120005ff07: LogicalKeyboardKey.gameButton7,
0x120005ff08: LogicalKeyboardKey.gameButton8,
0x120005ff09: LogicalKeyboardKey.gameButton9,
0x120005ff0a: LogicalKeyboardKey.gameButton10,
0x120005ff0b: LogicalKeyboardKey.gameButton11,
0x120005ff0c: LogicalKeyboardKey.gameButton12,
0x120005ff0d: LogicalKeyboardKey.gameButton13,
0x120005ff0e: LogicalKeyboardKey.gameButton14,
0x120005ff0f: LogicalKeyboardKey.gameButton15,
0x120005ff10: LogicalKeyboardKey.gameButton16,
0x120005ff11: LogicalKeyboardKey.gameButtonA,
0x120005ff12: LogicalKeyboardKey.gameButtonB,
0x120005ff13: LogicalKeyboardKey.gameButtonC,
0x120005ff14: LogicalKeyboardKey.gameButtonLeft1,
0x120005ff15: LogicalKeyboardKey.gameButtonLeft2,
0x120005ff16: LogicalKeyboardKey.gameButtonMode,
0x120005ff17: LogicalKeyboardKey.gameButtonRight1,
0x120005ff18: LogicalKeyboardKey.gameButtonRight2,
0x120005ff19: LogicalKeyboardKey.gameButtonSelect,
0x120005ff1a: LogicalKeyboardKey.gameButtonStart,
0x120005ff1b: LogicalKeyboardKey.gameButtonThumbLeft,
0x120005ff1c: LogicalKeyboardKey.gameButtonThumbRight,
0x120005ff1d: LogicalKeyboardKey.gameButtonX,
0x120005ff1e: LogicalKeyboardKey.gameButtonY,
0x120005ff1f: LogicalKeyboardKey.gameButtonZ,
0x1200070004: LogicalKeyboardKey.keyA,
0x1200070005: LogicalKeyboardKey.keyB,
0x1200070006: LogicalKeyboardKey.keyC,
0x1200070007: LogicalKeyboardKey.keyD,
0x1200070008: LogicalKeyboardKey.keyE,
0x1200070009: LogicalKeyboardKey.keyF,
0x120007000a: LogicalKeyboardKey.keyG,
0x120007000b: LogicalKeyboardKey.keyH,
0x120007000c: LogicalKeyboardKey.keyI,
0x120007000d: LogicalKeyboardKey.keyJ,
0x120007000e: LogicalKeyboardKey.keyK,
0x120007000f: LogicalKeyboardKey.keyL,
0x1200070010: LogicalKeyboardKey.keyM,
0x1200070011: LogicalKeyboardKey.keyN,
0x1200070012: LogicalKeyboardKey.keyO,
0x1200070013: LogicalKeyboardKey.keyP,
0x1200070014: LogicalKeyboardKey.keyQ,
0x1200070015: LogicalKeyboardKey.keyR,
0x1200070016: LogicalKeyboardKey.keyS,
0x1200070017: LogicalKeyboardKey.keyT,
0x1200070018: LogicalKeyboardKey.keyU,
0x1200070019: LogicalKeyboardKey.keyV,
0x120007001a: LogicalKeyboardKey.keyW,
0x120007001b: LogicalKeyboardKey.keyX,
0x120007001c: LogicalKeyboardKey.keyY,
0x120007001d: LogicalKeyboardKey.keyZ,
0x120007001e: LogicalKeyboardKey.digit1,
0x120007001f: LogicalKeyboardKey.digit2,
0x1200070020: LogicalKeyboardKey.digit3,
0x1200070021: LogicalKeyboardKey.digit4,
0x1200070022: LogicalKeyboardKey.digit5,
0x1200070023: LogicalKeyboardKey.digit6,
0x1200070024: LogicalKeyboardKey.digit7,
0x1200070025: LogicalKeyboardKey.digit8,
0x1200070026: LogicalKeyboardKey.digit9,
0x1200070027: LogicalKeyboardKey.digit0,
0x1200070028: LogicalKeyboardKey.enter,
0x1200070029: LogicalKeyboardKey.escape,
0x120007002a: LogicalKeyboardKey.backspace,
0x120007002b: LogicalKeyboardKey.tab,
0x120007002c: LogicalKeyboardKey.space,
0x120007002d: LogicalKeyboardKey.minus,
0x120007002e: LogicalKeyboardKey.equal,
0x120007002f: LogicalKeyboardKey.bracketLeft,
0x1200070030: LogicalKeyboardKey.bracketRight,
0x1200070031: LogicalKeyboardKey.backslash,
0x1200070033: LogicalKeyboardKey.semicolon,
0x1200070034: LogicalKeyboardKey.quote,
0x1200070035: LogicalKeyboardKey.backquote,
0x1200070036: LogicalKeyboardKey.comma,
0x1200070037: LogicalKeyboardKey.period,
0x1200070038: LogicalKeyboardKey.slash,
0x1200070039: LogicalKeyboardKey.capsLock,
0x120007003a: LogicalKeyboardKey.f1,
0x120007003b: LogicalKeyboardKey.f2,
0x120007003c: LogicalKeyboardKey.f3,
0x120007003d: LogicalKeyboardKey.f4,
0x120007003e: LogicalKeyboardKey.f5,
0x120007003f: LogicalKeyboardKey.f6,
0x1200070040: LogicalKeyboardKey.f7,
0x1200070041: LogicalKeyboardKey.f8,
0x1200070042: LogicalKeyboardKey.f9,
0x1200070043: LogicalKeyboardKey.f10,
0x1200070044: LogicalKeyboardKey.f11,
0x1200070045: LogicalKeyboardKey.f12,
0x1200070046: LogicalKeyboardKey.printScreen,
0x1200070047: LogicalKeyboardKey.scrollLock,
0x1200070048: LogicalKeyboardKey.pause,
0x1200070049: LogicalKeyboardKey.insert,
0x120007004a: LogicalKeyboardKey.home,
0x120007004b: LogicalKeyboardKey.pageUp,
0x120007004c: LogicalKeyboardKey.delete,
0x120007004d: LogicalKeyboardKey.end,
0x120007004e: LogicalKeyboardKey.pageDown,
0x120007004f: LogicalKeyboardKey.arrowRight,
0x1200070050: LogicalKeyboardKey.arrowLeft,
0x1200070051: LogicalKeyboardKey.arrowDown,
0x1200070052: LogicalKeyboardKey.arrowUp,
0x1200070053: LogicalKeyboardKey.numLock,
0x1200070054: LogicalKeyboardKey.numpadDivide,
0x1200070055: LogicalKeyboardKey.numpadMultiply,
0x1200070056: LogicalKeyboardKey.numpadSubtract,
0x1200070057: LogicalKeyboardKey.numpadAdd,
0x1200070058: LogicalKeyboardKey.numpadEnter,
0x1200070059: LogicalKeyboardKey.numpad1,
0x120007005a: LogicalKeyboardKey.numpad2,
0x120007005b: LogicalKeyboardKey.numpad3,
0x120007005c: LogicalKeyboardKey.numpad4,
0x120007005d: LogicalKeyboardKey.numpad5,
0x120007005e: LogicalKeyboardKey.numpad6,
0x120007005f: LogicalKeyboardKey.numpad7,
0x1200070060: LogicalKeyboardKey.numpad8,
0x1200070061: LogicalKeyboardKey.numpad9,
0x1200070062: LogicalKeyboardKey.numpad0,
0x1200070063: LogicalKeyboardKey.numpadDecimal,
0x1200070064: LogicalKeyboardKey.intlBackslash,
0x1200070065: LogicalKeyboardKey.contextMenu,
0x1200070066: LogicalKeyboardKey.power,
0x1200070067: LogicalKeyboardKey.numpadEqual,
0x1200070068: LogicalKeyboardKey.f13,
0x1200070069: LogicalKeyboardKey.f14,
0x120007006a: LogicalKeyboardKey.f15,
0x120007006b: LogicalKeyboardKey.f16,
0x120007006c: LogicalKeyboardKey.f17,
0x120007006d: LogicalKeyboardKey.f18,
0x120007006e: LogicalKeyboardKey.f19,
0x120007006f: LogicalKeyboardKey.f20,
0x1200070070: LogicalKeyboardKey.f21,
0x1200070071: LogicalKeyboardKey.f22,
0x1200070072: LogicalKeyboardKey.f23,
0x1200070073: LogicalKeyboardKey.f24,
0x1200070074: LogicalKeyboardKey.open,
0x1200070075: LogicalKeyboardKey.help,
0x1200070077: LogicalKeyboardKey.select,
0x1200070079: LogicalKeyboardKey.again,
0x120007007a: LogicalKeyboardKey.undo,
0x120007007b: LogicalKeyboardKey.cut,
0x120007007c: LogicalKeyboardKey.copy,
0x120007007d: LogicalKeyboardKey.paste,
0x120007007e: LogicalKeyboardKey.find,
0x120007007f: LogicalKeyboardKey.audioVolumeMute,
0x1200070080: LogicalKeyboardKey.audioVolumeUp,
0x1200070081: LogicalKeyboardKey.audioVolumeDown,
0x1200070085: LogicalKeyboardKey.numpadComma,
0x1200070087: LogicalKeyboardKey.intlRo,
0x1200070088: LogicalKeyboardKey.kanaMode,
0x1200070089: LogicalKeyboardKey.intlYen,
0x120007008a: LogicalKeyboardKey.convert,
0x120007008b: LogicalKeyboardKey.nonConvert,
0x1200070090: LogicalKeyboardKey.lang1,
0x1200070091: LogicalKeyboardKey.lang2,
0x1200070092: LogicalKeyboardKey.lang3,
0x1200070093: LogicalKeyboardKey.lang4,
0x1200070094: LogicalKeyboardKey.lang5,
0x120007009b: LogicalKeyboardKey.abort,
0x12000700a3: LogicalKeyboardKey.props,
0x12000700b6: LogicalKeyboardKey.numpadParenLeft,
0x12000700b7: LogicalKeyboardKey.numpadParenRight,
0x12000700e0: LogicalKeyboardKey.controlLeft,
0x12000700e1: LogicalKeyboardKey.shiftLeft,
0x12000700e2: LogicalKeyboardKey.altLeft,
0x12000700e3: LogicalKeyboardKey.metaLeft,
0x12000700e4: LogicalKeyboardKey.controlRight,
0x12000700e5: LogicalKeyboardKey.shiftRight,
0x12000700e6: LogicalKeyboardKey.altRight,
0x12000700e7: LogicalKeyboardKey.metaRight,
0x12000c0060: LogicalKeyboardKey.info,
0x12000c0061: LogicalKeyboardKey.closedCaptionToggle,
0x12000c006f: LogicalKeyboardKey.brightnessUp,
0x12000c0070: LogicalKeyboardKey.brightnessDown,
0x12000c0083: LogicalKeyboardKey.mediaLast,
0x12000c008c: LogicalKeyboardKey.launchPhone,
0x12000c0094: LogicalKeyboardKey.exit,
0x12000c009c: LogicalKeyboardKey.channelUp,
0x12000c009d: LogicalKeyboardKey.channelDown,
0x12000c00b0: LogicalKeyboardKey.mediaPlay,
0x12000c00b1: LogicalKeyboardKey.mediaPause,
0x12000c00b2: LogicalKeyboardKey.mediaRecord,
0x12000c00b3: LogicalKeyboardKey.mediaFastForward,
0x12000c00b4: LogicalKeyboardKey.mediaRewind,
0x12000c00b5: LogicalKeyboardKey.mediaTrackNext,
0x12000c00b6: LogicalKeyboardKey.mediaTrackPrevious,
0x12000c00b7: LogicalKeyboardKey.mediaStop,
0x12000c00b8: LogicalKeyboardKey.eject,
0x12000c00cd: LogicalKeyboardKey.mediaPlayPause,
0x12000c00cf: LogicalKeyboardKey.speechInputToggle,
0x12000c0184: LogicalKeyboardKey.launchWordProcessor,
0x12000c0186: LogicalKeyboardKey.launchSpreadsheet,
0x12000c018a: LogicalKeyboardKey.launchMail,
0x12000c018d: LogicalKeyboardKey.launchContacts,
0x12000c018e: LogicalKeyboardKey.launchCalendar,
0x12000c019c: LogicalKeyboardKey.logOff,
0x12000c019f: LogicalKeyboardKey.launchControlPanel,
0x12000c01ab: LogicalKeyboardKey.spellCheck,
0x12000c01b1: LogicalKeyboardKey.launchScreenSaver,
0x12000c01cb: LogicalKeyboardKey.launchAssistant,
0x12000c0201: LogicalKeyboardKey.newKey,
0x12000c0203: LogicalKeyboardKey.close,
0x12000c0207: LogicalKeyboardKey.save,
0x12000c0208: LogicalKeyboardKey.print,
0x12000c0221: LogicalKeyboardKey.browserSearch,
0x12000c0223: LogicalKeyboardKey.browserHome,
0x12000c0224: LogicalKeyboardKey.browserBack,
0x12000c0225: LogicalKeyboardKey.browserForward,
0x12000c0226: LogicalKeyboardKey.browserStop,
0x12000c0227: LogicalKeyboardKey.browserRefresh,
0x12000c022a: LogicalKeyboardKey.browserFavorites,
0x12000c022d: LogicalKeyboardKey.zoomIn,
0x12000c022e: LogicalKeyboardKey.zoomOut,
0x12000c0232: LogicalKeyboardKey.zoomToggle,
0x12000c0279: LogicalKeyboardKey.redo,
0x12000c0289: LogicalKeyboardKey.mailReply,
0x12000c028b: LogicalKeyboardKey.mailForward,
0x12000c028c: LogicalKeyboardKey.mailSend,
};
/// Maps Fuchsia-specific USB HID Usage IDs to the matching
/// [PhysicalKeyboardKey].
const Map<int, PhysicalKeyboardKey> kFuchsiaToPhysicalKey = <int, PhysicalKeyboardKey>{
0x00000010: PhysicalKeyboardKey.hyper,
0x00000011: PhysicalKeyboardKey.superKey,
0x00000012: PhysicalKeyboardKey.fn,
0x00000013: PhysicalKeyboardKey.fnLock,
0x00000014: PhysicalKeyboardKey.suspend,
0x00000015: PhysicalKeyboardKey.resume,
0x00000016: PhysicalKeyboardKey.turbo,
0x00000017: PhysicalKeyboardKey.privacyScreenToggle,
0x00000018: PhysicalKeyboardKey.microphoneMuteToggle,
0x00010082: PhysicalKeyboardKey.sleep,
0x00010083: PhysicalKeyboardKey.wakeUp,
0x000100b5: PhysicalKeyboardKey.displayToggleIntExt,
0x0005ff01: PhysicalKeyboardKey.gameButton1,
0x0005ff02: PhysicalKeyboardKey.gameButton2,
0x0005ff03: PhysicalKeyboardKey.gameButton3,
0x0005ff04: PhysicalKeyboardKey.gameButton4,
0x0005ff05: PhysicalKeyboardKey.gameButton5,
0x0005ff06: PhysicalKeyboardKey.gameButton6,
0x0005ff07: PhysicalKeyboardKey.gameButton7,
0x0005ff08: PhysicalKeyboardKey.gameButton8,
0x0005ff09: PhysicalKeyboardKey.gameButton9,
0x0005ff0a: PhysicalKeyboardKey.gameButton10,
0x0005ff0b: PhysicalKeyboardKey.gameButton11,
0x0005ff0c: PhysicalKeyboardKey.gameButton12,
0x0005ff0d: PhysicalKeyboardKey.gameButton13,
0x0005ff0e: PhysicalKeyboardKey.gameButton14,
0x0005ff0f: PhysicalKeyboardKey.gameButton15,
0x0005ff10: PhysicalKeyboardKey.gameButton16,
0x0005ff11: PhysicalKeyboardKey.gameButtonA,
0x0005ff12: PhysicalKeyboardKey.gameButtonB,
0x0005ff13: PhysicalKeyboardKey.gameButtonC,
0x0005ff14: PhysicalKeyboardKey.gameButtonLeft1,
0x0005ff15: PhysicalKeyboardKey.gameButtonLeft2,
0x0005ff16: PhysicalKeyboardKey.gameButtonMode,
0x0005ff17: PhysicalKeyboardKey.gameButtonRight1,
0x0005ff18: PhysicalKeyboardKey.gameButtonRight2,
0x0005ff19: PhysicalKeyboardKey.gameButtonSelect,
0x0005ff1a: PhysicalKeyboardKey.gameButtonStart,
0x0005ff1b: PhysicalKeyboardKey.gameButtonThumbLeft,
0x0005ff1c: PhysicalKeyboardKey.gameButtonThumbRight,
0x0005ff1d: PhysicalKeyboardKey.gameButtonX,
0x0005ff1e: PhysicalKeyboardKey.gameButtonY,
0x0005ff1f: PhysicalKeyboardKey.gameButtonZ,
0x00070000: PhysicalKeyboardKey.usbReserved,
0x00070001: PhysicalKeyboardKey.usbErrorRollOver,
0x00070002: PhysicalKeyboardKey.usbPostFail,
0x00070003: PhysicalKeyboardKey.usbErrorUndefined,
0x00070004: PhysicalKeyboardKey.keyA,
0x00070005: PhysicalKeyboardKey.keyB,
0x00070006: PhysicalKeyboardKey.keyC,
0x00070007: PhysicalKeyboardKey.keyD,
0x00070008: PhysicalKeyboardKey.keyE,
0x00070009: PhysicalKeyboardKey.keyF,
0x0007000a: PhysicalKeyboardKey.keyG,
0x0007000b: PhysicalKeyboardKey.keyH,
0x0007000c: PhysicalKeyboardKey.keyI,
0x0007000d: PhysicalKeyboardKey.keyJ,
0x0007000e: PhysicalKeyboardKey.keyK,
0x0007000f: PhysicalKeyboardKey.keyL,
0x00070010: PhysicalKeyboardKey.keyM,
0x00070011: PhysicalKeyboardKey.keyN,
0x00070012: PhysicalKeyboardKey.keyO,
0x00070013: PhysicalKeyboardKey.keyP,
0x00070014: PhysicalKeyboardKey.keyQ,
0x00070015: PhysicalKeyboardKey.keyR,
0x00070016: PhysicalKeyboardKey.keyS,
0x00070017: PhysicalKeyboardKey.keyT,
0x00070018: PhysicalKeyboardKey.keyU,
0x00070019: PhysicalKeyboardKey.keyV,
0x0007001a: PhysicalKeyboardKey.keyW,
0x0007001b: PhysicalKeyboardKey.keyX,
0x0007001c: PhysicalKeyboardKey.keyY,
0x0007001d: PhysicalKeyboardKey.keyZ,
0x0007001e: PhysicalKeyboardKey.digit1,
0x0007001f: PhysicalKeyboardKey.digit2,
0x00070020: PhysicalKeyboardKey.digit3,
0x00070021: PhysicalKeyboardKey.digit4,
0x00070022: PhysicalKeyboardKey.digit5,
0x00070023: PhysicalKeyboardKey.digit6,
0x00070024: PhysicalKeyboardKey.digit7,
0x00070025: PhysicalKeyboardKey.digit8,
0x00070026: PhysicalKeyboardKey.digit9,
0x00070027: PhysicalKeyboardKey.digit0,
0x00070028: PhysicalKeyboardKey.enter,
0x00070029: PhysicalKeyboardKey.escape,
0x0007002a: PhysicalKeyboardKey.backspace,
0x0007002b: PhysicalKeyboardKey.tab,
0x0007002c: PhysicalKeyboardKey.space,
0x0007002d: PhysicalKeyboardKey.minus,
0x0007002e: PhysicalKeyboardKey.equal,
0x0007002f: PhysicalKeyboardKey.bracketLeft,
0x00070030: PhysicalKeyboardKey.bracketRight,
0x00070031: PhysicalKeyboardKey.backslash,
0x00070033: PhysicalKeyboardKey.semicolon,
0x00070034: PhysicalKeyboardKey.quote,
0x00070035: PhysicalKeyboardKey.backquote,
0x00070036: PhysicalKeyboardKey.comma,
0x00070037: PhysicalKeyboardKey.period,
0x00070038: PhysicalKeyboardKey.slash,
0x00070039: PhysicalKeyboardKey.capsLock,
0x0007003a: PhysicalKeyboardKey.f1,
0x0007003b: PhysicalKeyboardKey.f2,
0x0007003c: PhysicalKeyboardKey.f3,
0x0007003d: PhysicalKeyboardKey.f4,
0x0007003e: PhysicalKeyboardKey.f5,
0x0007003f: PhysicalKeyboardKey.f6,
0x00070040: PhysicalKeyboardKey.f7,
0x00070041: PhysicalKeyboardKey.f8,
0x00070042: PhysicalKeyboardKey.f9,
0x00070043: PhysicalKeyboardKey.f10,
0x00070044: PhysicalKeyboardKey.f11,
0x00070045: PhysicalKeyboardKey.f12,
0x00070046: PhysicalKeyboardKey.printScreen,
0x00070047: PhysicalKeyboardKey.scrollLock,
0x00070048: PhysicalKeyboardKey.pause,
0x00070049: PhysicalKeyboardKey.insert,
0x0007004a: PhysicalKeyboardKey.home,
0x0007004b: PhysicalKeyboardKey.pageUp,
0x0007004c: PhysicalKeyboardKey.delete,
0x0007004d: PhysicalKeyboardKey.end,
0x0007004e: PhysicalKeyboardKey.pageDown,
0x0007004f: PhysicalKeyboardKey.arrowRight,
0x00070050: PhysicalKeyboardKey.arrowLeft,
0x00070051: PhysicalKeyboardKey.arrowDown,
0x00070052: PhysicalKeyboardKey.arrowUp,
0x00070053: PhysicalKeyboardKey.numLock,
0x00070054: PhysicalKeyboardKey.numpadDivide,
0x00070055: PhysicalKeyboardKey.numpadMultiply,
0x00070056: PhysicalKeyboardKey.numpadSubtract,
0x00070057: PhysicalKeyboardKey.numpadAdd,
0x00070058: PhysicalKeyboardKey.numpadEnter,
0x00070059: PhysicalKeyboardKey.numpad1,
0x0007005a: PhysicalKeyboardKey.numpad2,
0x0007005b: PhysicalKeyboardKey.numpad3,
0x0007005c: PhysicalKeyboardKey.numpad4,
0x0007005d: PhysicalKeyboardKey.numpad5,
0x0007005e: PhysicalKeyboardKey.numpad6,
0x0007005f: PhysicalKeyboardKey.numpad7,
0x00070060: PhysicalKeyboardKey.numpad8,
0x00070061: PhysicalKeyboardKey.numpad9,
0x00070062: PhysicalKeyboardKey.numpad0,
0x00070063: PhysicalKeyboardKey.numpadDecimal,
0x00070064: PhysicalKeyboardKey.intlBackslash,
0x00070065: PhysicalKeyboardKey.contextMenu,
0x00070066: PhysicalKeyboardKey.power,
0x00070067: PhysicalKeyboardKey.numpadEqual,
0x00070068: PhysicalKeyboardKey.f13,
0x00070069: PhysicalKeyboardKey.f14,
0x0007006a: PhysicalKeyboardKey.f15,
0x0007006b: PhysicalKeyboardKey.f16,
0x0007006c: PhysicalKeyboardKey.f17,
0x0007006d: PhysicalKeyboardKey.f18,
0x0007006e: PhysicalKeyboardKey.f19,
0x0007006f: PhysicalKeyboardKey.f20,
0x00070070: PhysicalKeyboardKey.f21,
0x00070071: PhysicalKeyboardKey.f22,
0x00070072: PhysicalKeyboardKey.f23,
0x00070073: PhysicalKeyboardKey.f24,
0x00070074: PhysicalKeyboardKey.open,
0x00070075: PhysicalKeyboardKey.help,
0x00070077: PhysicalKeyboardKey.select,
0x00070079: PhysicalKeyboardKey.again,
0x0007007a: PhysicalKeyboardKey.undo,
0x0007007b: PhysicalKeyboardKey.cut,
0x0007007c: PhysicalKeyboardKey.copy,
0x0007007d: PhysicalKeyboardKey.paste,
0x0007007e: PhysicalKeyboardKey.find,
0x0007007f: PhysicalKeyboardKey.audioVolumeMute,
0x00070080: PhysicalKeyboardKey.audioVolumeUp,
0x00070081: PhysicalKeyboardKey.audioVolumeDown,
0x00070085: PhysicalKeyboardKey.numpadComma,
0x00070087: PhysicalKeyboardKey.intlRo,
0x00070088: PhysicalKeyboardKey.kanaMode,
0x00070089: PhysicalKeyboardKey.intlYen,
0x0007008a: PhysicalKeyboardKey.convert,
0x0007008b: PhysicalKeyboardKey.nonConvert,
0x00070090: PhysicalKeyboardKey.lang1,
0x00070091: PhysicalKeyboardKey.lang2,
0x00070092: PhysicalKeyboardKey.lang3,
0x00070093: PhysicalKeyboardKey.lang4,
0x00070094: PhysicalKeyboardKey.lang5,
0x0007009b: PhysicalKeyboardKey.abort,
0x000700a3: PhysicalKeyboardKey.props,
0x000700b6: PhysicalKeyboardKey.numpadParenLeft,
0x000700b7: PhysicalKeyboardKey.numpadParenRight,
0x000700bb: PhysicalKeyboardKey.numpadBackspace,
0x000700d0: PhysicalKeyboardKey.numpadMemoryStore,
0x000700d1: PhysicalKeyboardKey.numpadMemoryRecall,
0x000700d2: PhysicalKeyboardKey.numpadMemoryClear,
0x000700d3: PhysicalKeyboardKey.numpadMemoryAdd,
0x000700d4: PhysicalKeyboardKey.numpadMemorySubtract,
0x000700d7: PhysicalKeyboardKey.numpadSignChange,
0x000700d8: PhysicalKeyboardKey.numpadClear,
0x000700d9: PhysicalKeyboardKey.numpadClearEntry,
0x000700e0: PhysicalKeyboardKey.controlLeft,
0x000700e1: PhysicalKeyboardKey.shiftLeft,
0x000700e2: PhysicalKeyboardKey.altLeft,
0x000700e3: PhysicalKeyboardKey.metaLeft,
0x000700e4: PhysicalKeyboardKey.controlRight,
0x000700e5: PhysicalKeyboardKey.shiftRight,
0x000700e6: PhysicalKeyboardKey.altRight,
0x000700e7: PhysicalKeyboardKey.metaRight,
0x000c0060: PhysicalKeyboardKey.info,
0x000c0061: PhysicalKeyboardKey.closedCaptionToggle,
0x000c006f: PhysicalKeyboardKey.brightnessUp,
0x000c0070: PhysicalKeyboardKey.brightnessDown,
0x000c0072: PhysicalKeyboardKey.brightnessToggle,
0x000c0073: PhysicalKeyboardKey.brightnessMinimum,
0x000c0074: PhysicalKeyboardKey.brightnessMaximum,
0x000c0075: PhysicalKeyboardKey.brightnessAuto,
0x000c0079: PhysicalKeyboardKey.kbdIllumUp,
0x000c007a: PhysicalKeyboardKey.kbdIllumDown,
0x000c0083: PhysicalKeyboardKey.mediaLast,
0x000c008c: PhysicalKeyboardKey.launchPhone,
0x000c008d: PhysicalKeyboardKey.programGuide,
0x000c0094: PhysicalKeyboardKey.exit,
0x000c009c: PhysicalKeyboardKey.channelUp,
0x000c009d: PhysicalKeyboardKey.channelDown,
0x000c00b0: PhysicalKeyboardKey.mediaPlay,
0x000c00b1: PhysicalKeyboardKey.mediaPause,
0x000c00b2: PhysicalKeyboardKey.mediaRecord,
0x000c00b3: PhysicalKeyboardKey.mediaFastForward,
0x000c00b4: PhysicalKeyboardKey.mediaRewind,
0x000c00b5: PhysicalKeyboardKey.mediaTrackNext,
0x000c00b6: PhysicalKeyboardKey.mediaTrackPrevious,
0x000c00b7: PhysicalKeyboardKey.mediaStop,
0x000c00b8: PhysicalKeyboardKey.eject,
0x000c00cd: PhysicalKeyboardKey.mediaPlayPause,
0x000c00cf: PhysicalKeyboardKey.speechInputToggle,
0x000c00e5: PhysicalKeyboardKey.bassBoost,
0x000c0183: PhysicalKeyboardKey.mediaSelect,
0x000c0184: PhysicalKeyboardKey.launchWordProcessor,
0x000c0186: PhysicalKeyboardKey.launchSpreadsheet,
0x000c018a: PhysicalKeyboardKey.launchMail,
0x000c018d: PhysicalKeyboardKey.launchContacts,
0x000c018e: PhysicalKeyboardKey.launchCalendar,
0x000c0192: PhysicalKeyboardKey.launchApp2,
0x000c0194: PhysicalKeyboardKey.launchApp1,
0x000c0196: PhysicalKeyboardKey.launchInternetBrowser,
0x000c019c: PhysicalKeyboardKey.logOff,
0x000c019e: PhysicalKeyboardKey.lockScreen,
0x000c019f: PhysicalKeyboardKey.launchControlPanel,
0x000c01a2: PhysicalKeyboardKey.selectTask,
0x000c01a7: PhysicalKeyboardKey.launchDocuments,
0x000c01ab: PhysicalKeyboardKey.spellCheck,
0x000c01ae: PhysicalKeyboardKey.launchKeyboardLayout,
0x000c01b1: PhysicalKeyboardKey.launchScreenSaver,
0x000c01b7: PhysicalKeyboardKey.launchAudioBrowser,
0x000c01cb: PhysicalKeyboardKey.launchAssistant,
0x000c0201: PhysicalKeyboardKey.newKey,
0x000c0203: PhysicalKeyboardKey.close,
0x000c0207: PhysicalKeyboardKey.save,
0x000c0208: PhysicalKeyboardKey.print,
0x000c0221: PhysicalKeyboardKey.browserSearch,
0x000c0223: PhysicalKeyboardKey.browserHome,
0x000c0224: PhysicalKeyboardKey.browserBack,
0x000c0225: PhysicalKeyboardKey.browserForward,
0x000c0226: PhysicalKeyboardKey.browserStop,
0x000c0227: PhysicalKeyboardKey.browserRefresh,
0x000c022a: PhysicalKeyboardKey.browserFavorites,
0x000c022d: PhysicalKeyboardKey.zoomIn,
0x000c022e: PhysicalKeyboardKey.zoomOut,
0x000c0232: PhysicalKeyboardKey.zoomToggle,
0x000c0279: PhysicalKeyboardKey.redo,
0x000c0289: PhysicalKeyboardKey.mailReply,
0x000c028b: PhysicalKeyboardKey.mailForward,
0x000c028c: PhysicalKeyboardKey.mailSend,
0x000c029d: PhysicalKeyboardKey.keyboardLayoutSelect,
0x000c029f: PhysicalKeyboardKey.showAllWindows,
};
/// Maps macOS-specific key code values representing [PhysicalKeyboardKey].
///
/// MacOS doesn't provide a scan code, but a virtual keycode to represent a physical key.
const Map<int, PhysicalKeyboardKey> kMacOsToPhysicalKey = <int, PhysicalKeyboardKey>{
0x00000000: PhysicalKeyboardKey.keyA,
0x00000001: PhysicalKeyboardKey.keyS,
0x00000002: PhysicalKeyboardKey.keyD,
0x00000003: PhysicalKeyboardKey.keyF,
0x00000004: PhysicalKeyboardKey.keyH,
0x00000005: PhysicalKeyboardKey.keyG,
0x00000006: PhysicalKeyboardKey.keyZ,
0x00000007: PhysicalKeyboardKey.keyX,
0x00000008: PhysicalKeyboardKey.keyC,
0x00000009: PhysicalKeyboardKey.keyV,
0x0000000a: PhysicalKeyboardKey.intlBackslash,
0x0000000b: PhysicalKeyboardKey.keyB,
0x0000000c: PhysicalKeyboardKey.keyQ,
0x0000000d: PhysicalKeyboardKey.keyW,
0x0000000e: PhysicalKeyboardKey.keyE,
0x0000000f: PhysicalKeyboardKey.keyR,
0x00000010: PhysicalKeyboardKey.keyY,
0x00000011: PhysicalKeyboardKey.keyT,
0x00000012: PhysicalKeyboardKey.digit1,
0x00000013: PhysicalKeyboardKey.digit2,
0x00000014: PhysicalKeyboardKey.digit3,
0x00000015: PhysicalKeyboardKey.digit4,
0x00000016: PhysicalKeyboardKey.digit6,
0x00000017: PhysicalKeyboardKey.digit5,
0x00000018: PhysicalKeyboardKey.equal,
0x00000019: PhysicalKeyboardKey.digit9,
0x0000001a: PhysicalKeyboardKey.digit7,
0x0000001b: PhysicalKeyboardKey.minus,
0x0000001c: PhysicalKeyboardKey.digit8,
0x0000001d: PhysicalKeyboardKey.digit0,
0x0000001e: PhysicalKeyboardKey.bracketRight,
0x0000001f: PhysicalKeyboardKey.keyO,
0x00000020: PhysicalKeyboardKey.keyU,
0x00000021: PhysicalKeyboardKey.bracketLeft,
0x00000022: PhysicalKeyboardKey.keyI,
0x00000023: PhysicalKeyboardKey.keyP,
0x00000024: PhysicalKeyboardKey.enter,
0x00000025: PhysicalKeyboardKey.keyL,
0x00000026: PhysicalKeyboardKey.keyJ,
0x00000027: PhysicalKeyboardKey.quote,
0x00000028: PhysicalKeyboardKey.keyK,
0x00000029: PhysicalKeyboardKey.semicolon,
0x0000002a: PhysicalKeyboardKey.backslash,
0x0000002b: PhysicalKeyboardKey.comma,
0x0000002c: PhysicalKeyboardKey.slash,
0x0000002d: PhysicalKeyboardKey.keyN,
0x0000002e: PhysicalKeyboardKey.keyM,
0x0000002f: PhysicalKeyboardKey.period,
0x00000030: PhysicalKeyboardKey.tab,
0x00000031: PhysicalKeyboardKey.space,
0x00000032: PhysicalKeyboardKey.backquote,
0x00000033: PhysicalKeyboardKey.backspace,
0x00000035: PhysicalKeyboardKey.escape,
0x00000036: PhysicalKeyboardKey.metaRight,
0x00000037: PhysicalKeyboardKey.metaLeft,
0x00000038: PhysicalKeyboardKey.shiftLeft,
0x00000039: PhysicalKeyboardKey.capsLock,
0x0000003a: PhysicalKeyboardKey.altLeft,
0x0000003b: PhysicalKeyboardKey.controlLeft,
0x0000003c: PhysicalKeyboardKey.shiftRight,
0x0000003d: PhysicalKeyboardKey.altRight,
0x0000003e: PhysicalKeyboardKey.controlRight,
0x0000003f: PhysicalKeyboardKey.fn,
0x00000040: PhysicalKeyboardKey.f17,
0x00000041: PhysicalKeyboardKey.numpadDecimal,
0x00000043: PhysicalKeyboardKey.numpadMultiply,
0x00000045: PhysicalKeyboardKey.numpadAdd,
0x00000047: PhysicalKeyboardKey.numLock,
0x00000048: PhysicalKeyboardKey.audioVolumeUp,
0x00000049: PhysicalKeyboardKey.audioVolumeDown,
0x0000004a: PhysicalKeyboardKey.audioVolumeMute,
0x0000004b: PhysicalKeyboardKey.numpadDivide,
0x0000004c: PhysicalKeyboardKey.numpadEnter,
0x0000004e: PhysicalKeyboardKey.numpadSubtract,
0x0000004f: PhysicalKeyboardKey.f18,
0x00000050: PhysicalKeyboardKey.f19,
0x00000051: PhysicalKeyboardKey.numpadEqual,
0x00000052: PhysicalKeyboardKey.numpad0,
0x00000053: PhysicalKeyboardKey.numpad1,
0x00000054: PhysicalKeyboardKey.numpad2,
0x00000055: PhysicalKeyboardKey.numpad3,
0x00000056: PhysicalKeyboardKey.numpad4,
0x00000057: PhysicalKeyboardKey.numpad5,
0x00000058: PhysicalKeyboardKey.numpad6,
0x00000059: PhysicalKeyboardKey.numpad7,
0x0000005a: PhysicalKeyboardKey.f20,
0x0000005b: PhysicalKeyboardKey.numpad8,
0x0000005c: PhysicalKeyboardKey.numpad9,
0x0000005d: PhysicalKeyboardKey.intlYen,
0x0000005e: PhysicalKeyboardKey.intlRo,
0x0000005f: PhysicalKeyboardKey.numpadComma,
0x00000060: PhysicalKeyboardKey.f5,
0x00000061: PhysicalKeyboardKey.f6,
0x00000062: PhysicalKeyboardKey.f7,
0x00000063: PhysicalKeyboardKey.f3,
0x00000064: PhysicalKeyboardKey.f8,
0x00000065: PhysicalKeyboardKey.f9,
0x00000066: PhysicalKeyboardKey.lang2,
0x00000067: PhysicalKeyboardKey.f11,
0x00000068: PhysicalKeyboardKey.lang1,
0x00000069: PhysicalKeyboardKey.f13,
0x0000006a: PhysicalKeyboardKey.f16,
0x0000006b: PhysicalKeyboardKey.f14,
0x0000006d: PhysicalKeyboardKey.f10,
0x0000006e: PhysicalKeyboardKey.contextMenu,
0x0000006f: PhysicalKeyboardKey.f12,
0x00000071: PhysicalKeyboardKey.f15,
0x00000072: PhysicalKeyboardKey.insert,
0x00000073: PhysicalKeyboardKey.home,
0x00000074: PhysicalKeyboardKey.pageUp,
0x00000075: PhysicalKeyboardKey.delete,
0x00000076: PhysicalKeyboardKey.f4,
0x00000077: PhysicalKeyboardKey.end,
0x00000078: PhysicalKeyboardKey.f2,
0x00000079: PhysicalKeyboardKey.pageDown,
0x0000007a: PhysicalKeyboardKey.f1,
0x0000007b: PhysicalKeyboardKey.arrowLeft,
0x0000007c: PhysicalKeyboardKey.arrowRight,
0x0000007d: PhysicalKeyboardKey.arrowDown,
0x0000007e: PhysicalKeyboardKey.arrowUp,
};
/// A map of macOS key codes which have printable representations, but appear
/// on the number pad. Used to provide different key objects for keys like
/// KEY_EQUALS and NUMPAD_EQUALS.
const Map<int, LogicalKeyboardKey> kMacOsNumPadMap = <int, LogicalKeyboardKey>{
0x00000041: LogicalKeyboardKey.numpadDecimal,
0x00000043: LogicalKeyboardKey.numpadMultiply,
0x00000045: LogicalKeyboardKey.numpadAdd,
0x0000004b: LogicalKeyboardKey.numpadDivide,
0x0000004e: LogicalKeyboardKey.numpadSubtract,
0x00000051: LogicalKeyboardKey.numpadEqual,
0x00000052: LogicalKeyboardKey.numpad0,
0x00000053: LogicalKeyboardKey.numpad1,
0x00000054: LogicalKeyboardKey.numpad2,
0x00000055: LogicalKeyboardKey.numpad3,
0x00000056: LogicalKeyboardKey.numpad4,
0x00000057: LogicalKeyboardKey.numpad5,
0x00000058: LogicalKeyboardKey.numpad6,
0x00000059: LogicalKeyboardKey.numpad7,
0x0000005b: LogicalKeyboardKey.numpad8,
0x0000005c: LogicalKeyboardKey.numpad9,
0x0000005f: LogicalKeyboardKey.numpadComma,
};
/// A map of macOS key codes which are numbered function keys, so that they
/// can be excluded when asking "is the Fn modifier down?".
const Map<int, LogicalKeyboardKey> kMacOsFunctionKeyMap = <int, LogicalKeyboardKey>{
0x00000040: LogicalKeyboardKey.f17,
0x0000004f: LogicalKeyboardKey.f18,
0x00000050: LogicalKeyboardKey.f19,
0x0000005a: LogicalKeyboardKey.f20,
0x00000060: LogicalKeyboardKey.f5,
0x00000061: LogicalKeyboardKey.f6,
0x00000062: LogicalKeyboardKey.f7,
0x00000063: LogicalKeyboardKey.f3,
0x00000064: LogicalKeyboardKey.f8,
0x00000065: LogicalKeyboardKey.f9,
0x00000067: LogicalKeyboardKey.f11,
0x00000069: LogicalKeyboardKey.f13,
0x0000006a: LogicalKeyboardKey.f16,
0x0000006b: LogicalKeyboardKey.f14,
0x0000006d: LogicalKeyboardKey.f10,
0x0000006f: LogicalKeyboardKey.f12,
0x00000071: LogicalKeyboardKey.f15,
0x00000076: LogicalKeyboardKey.f4,
0x00000078: LogicalKeyboardKey.f2,
0x0000007a: LogicalKeyboardKey.f1,
};
/// A map of macOS key codes presenting [LogicalKeyboardKey].
///
/// Logical key codes are not available in macOS key events. Most of the logical keys
/// are derived from its `characterIgnoringModifiers`, but those keys that don't
/// have a character representation will be derived from their key codes using
/// this map.
const Map<int, LogicalKeyboardKey> kMacOsToLogicalKey = <int, LogicalKeyboardKey>{
36: LogicalKeyboardKey.enter,
48: LogicalKeyboardKey.tab,
51: LogicalKeyboardKey.backspace,
53: LogicalKeyboardKey.escape,
54: LogicalKeyboardKey.metaRight,
55: LogicalKeyboardKey.metaLeft,
56: LogicalKeyboardKey.shiftLeft,
57: LogicalKeyboardKey.capsLock,
58: LogicalKeyboardKey.altLeft,
59: LogicalKeyboardKey.controlLeft,
60: LogicalKeyboardKey.shiftRight,
61: LogicalKeyboardKey.altRight,
62: LogicalKeyboardKey.controlRight,
63: LogicalKeyboardKey.fn,
64: LogicalKeyboardKey.f17,
65: LogicalKeyboardKey.numpadDecimal,
67: LogicalKeyboardKey.numpadMultiply,
69: LogicalKeyboardKey.numpadAdd,
71: LogicalKeyboardKey.numLock,
72: LogicalKeyboardKey.audioVolumeUp,
73: LogicalKeyboardKey.audioVolumeDown,
74: LogicalKeyboardKey.audioVolumeMute,
75: LogicalKeyboardKey.numpadDivide,
76: LogicalKeyboardKey.numpadEnter,
78: LogicalKeyboardKey.numpadSubtract,
79: LogicalKeyboardKey.f18,
80: LogicalKeyboardKey.f19,
81: LogicalKeyboardKey.numpadEqual,
82: LogicalKeyboardKey.numpad0,
83: LogicalKeyboardKey.numpad1,
84: LogicalKeyboardKey.numpad2,
85: LogicalKeyboardKey.numpad3,
86: LogicalKeyboardKey.numpad4,
87: LogicalKeyboardKey.numpad5,
88: LogicalKeyboardKey.numpad6,
89: LogicalKeyboardKey.numpad7,
90: LogicalKeyboardKey.f20,
91: LogicalKeyboardKey.numpad8,
92: LogicalKeyboardKey.numpad9,
93: LogicalKeyboardKey.intlYen,
94: LogicalKeyboardKey.intlRo,
95: LogicalKeyboardKey.numpadComma,
96: LogicalKeyboardKey.f5,
97: LogicalKeyboardKey.f6,
98: LogicalKeyboardKey.f7,
99: LogicalKeyboardKey.f3,
100: LogicalKeyboardKey.f8,
101: LogicalKeyboardKey.f9,
102: LogicalKeyboardKey.lang2,
103: LogicalKeyboardKey.f11,
104: LogicalKeyboardKey.lang1,
105: LogicalKeyboardKey.f13,
106: LogicalKeyboardKey.f16,
107: LogicalKeyboardKey.f14,
109: LogicalKeyboardKey.f10,
110: LogicalKeyboardKey.contextMenu,
111: LogicalKeyboardKey.f12,
113: LogicalKeyboardKey.f15,
114: LogicalKeyboardKey.insert,
115: LogicalKeyboardKey.home,
116: LogicalKeyboardKey.pageUp,
117: LogicalKeyboardKey.delete,
118: LogicalKeyboardKey.f4,
119: LogicalKeyboardKey.end,
120: LogicalKeyboardKey.f2,
121: LogicalKeyboardKey.pageDown,
122: LogicalKeyboardKey.f1,
123: LogicalKeyboardKey.arrowLeft,
124: LogicalKeyboardKey.arrowRight,
125: LogicalKeyboardKey.arrowDown,
126: LogicalKeyboardKey.arrowUp,
};
/// Maps iOS-specific key code values representing [PhysicalKeyboardKey].
///
/// iOS doesn't provide a scan code, but a virtual keycode to represent a physical key.
const Map<int, PhysicalKeyboardKey> kIosToPhysicalKey = <int, PhysicalKeyboardKey>{
0x00000000: PhysicalKeyboardKey.usbReserved,
0x00000001: PhysicalKeyboardKey.usbErrorRollOver,
0x00000002: PhysicalKeyboardKey.usbPostFail,
0x00000003: PhysicalKeyboardKey.usbErrorUndefined,
0x00000004: PhysicalKeyboardKey.keyA,
0x00000005: PhysicalKeyboardKey.keyB,
0x00000006: PhysicalKeyboardKey.keyC,
0x00000007: PhysicalKeyboardKey.keyD,
0x00000008: PhysicalKeyboardKey.keyE,
0x00000009: PhysicalKeyboardKey.keyF,
0x0000000a: PhysicalKeyboardKey.keyG,
0x0000000b: PhysicalKeyboardKey.keyH,
0x0000000c: PhysicalKeyboardKey.keyI,
0x0000000d: PhysicalKeyboardKey.keyJ,
0x0000000e: PhysicalKeyboardKey.keyK,
0x0000000f: PhysicalKeyboardKey.keyL,
0x00000010: PhysicalKeyboardKey.keyM,
0x00000011: PhysicalKeyboardKey.keyN,
0x00000012: PhysicalKeyboardKey.keyO,
0x00000013: PhysicalKeyboardKey.keyP,
0x00000014: PhysicalKeyboardKey.keyQ,
0x00000015: PhysicalKeyboardKey.keyR,
0x00000016: PhysicalKeyboardKey.keyS,
0x00000017: PhysicalKeyboardKey.keyT,
0x00000018: PhysicalKeyboardKey.keyU,
0x00000019: PhysicalKeyboardKey.keyV,
0x0000001a: PhysicalKeyboardKey.keyW,
0x0000001b: PhysicalKeyboardKey.keyX,
0x0000001c: PhysicalKeyboardKey.keyY,
0x0000001d: PhysicalKeyboardKey.keyZ,
0x0000001e: PhysicalKeyboardKey.digit1,
0x0000001f: PhysicalKeyboardKey.digit2,
0x00000020: PhysicalKeyboardKey.digit3,
0x00000021: PhysicalKeyboardKey.digit4,
0x00000022: PhysicalKeyboardKey.digit5,
0x00000023: PhysicalKeyboardKey.digit6,
0x00000024: PhysicalKeyboardKey.digit7,
0x00000025: PhysicalKeyboardKey.digit8,
0x00000026: PhysicalKeyboardKey.digit9,
0x00000027: PhysicalKeyboardKey.digit0,
0x00000028: PhysicalKeyboardKey.enter,
0x00000029: PhysicalKeyboardKey.escape,
0x0000002a: PhysicalKeyboardKey.backspace,
0x0000002b: PhysicalKeyboardKey.tab,
0x0000002c: PhysicalKeyboardKey.space,
0x0000002d: PhysicalKeyboardKey.minus,
0x0000002e: PhysicalKeyboardKey.equal,
0x0000002f: PhysicalKeyboardKey.bracketLeft,
0x00000030: PhysicalKeyboardKey.bracketRight,
0x00000031: PhysicalKeyboardKey.backslash,
0x00000033: PhysicalKeyboardKey.semicolon,
0x00000034: PhysicalKeyboardKey.quote,
0x00000035: PhysicalKeyboardKey.backquote,
0x00000036: PhysicalKeyboardKey.comma,
0x00000037: PhysicalKeyboardKey.period,
0x00000038: PhysicalKeyboardKey.slash,
0x00000039: PhysicalKeyboardKey.capsLock,
0x0000003a: PhysicalKeyboardKey.f1,
0x0000003b: PhysicalKeyboardKey.f2,
0x0000003c: PhysicalKeyboardKey.f3,
0x0000003d: PhysicalKeyboardKey.f4,
0x0000003e: PhysicalKeyboardKey.f5,
0x0000003f: PhysicalKeyboardKey.f6,
0x00000040: PhysicalKeyboardKey.f7,
0x00000041: PhysicalKeyboardKey.f8,
0x00000042: PhysicalKeyboardKey.f9,
0x00000043: PhysicalKeyboardKey.f10,
0x00000044: PhysicalKeyboardKey.f11,
0x00000045: PhysicalKeyboardKey.f12,
0x00000046: PhysicalKeyboardKey.printScreen,
0x00000047: PhysicalKeyboardKey.scrollLock,
0x00000048: PhysicalKeyboardKey.pause,
0x00000049: PhysicalKeyboardKey.insert,
0x0000004a: PhysicalKeyboardKey.home,
0x0000004b: PhysicalKeyboardKey.pageUp,
0x0000004c: PhysicalKeyboardKey.delete,
0x0000004d: PhysicalKeyboardKey.end,
0x0000004e: PhysicalKeyboardKey.pageDown,
0x0000004f: PhysicalKeyboardKey.arrowRight,
0x00000050: PhysicalKeyboardKey.arrowLeft,
0x00000051: PhysicalKeyboardKey.arrowDown,
0x00000052: PhysicalKeyboardKey.arrowUp,
0x00000053: PhysicalKeyboardKey.numLock,
0x00000054: PhysicalKeyboardKey.numpadDivide,
0x00000055: PhysicalKeyboardKey.numpadMultiply,
0x00000056: PhysicalKeyboardKey.numpadSubtract,
0x00000057: PhysicalKeyboardKey.numpadAdd,
0x00000058: PhysicalKeyboardKey.numpadEnter,
0x00000059: PhysicalKeyboardKey.numpad1,
0x0000005a: PhysicalKeyboardKey.numpad2,
0x0000005b: PhysicalKeyboardKey.numpad3,
0x0000005c: PhysicalKeyboardKey.numpad4,
0x0000005d: PhysicalKeyboardKey.numpad5,
0x0000005e: PhysicalKeyboardKey.numpad6,
0x0000005f: PhysicalKeyboardKey.numpad7,
0x00000060: PhysicalKeyboardKey.numpad8,
0x00000061: PhysicalKeyboardKey.numpad9,
0x00000062: PhysicalKeyboardKey.numpad0,
0x00000063: PhysicalKeyboardKey.numpadDecimal,
0x00000064: PhysicalKeyboardKey.intlBackslash,
0x00000065: PhysicalKeyboardKey.contextMenu,
0x00000066: PhysicalKeyboardKey.power,
0x00000067: PhysicalKeyboardKey.numpadEqual,
0x00000068: PhysicalKeyboardKey.f13,
0x00000069: PhysicalKeyboardKey.f14,
0x0000006a: PhysicalKeyboardKey.f15,
0x0000006b: PhysicalKeyboardKey.f16,
0x0000006c: PhysicalKeyboardKey.f17,
0x0000006d: PhysicalKeyboardKey.f18,
0x0000006e: PhysicalKeyboardKey.f19,
0x0000006f: PhysicalKeyboardKey.f20,
0x00000070: PhysicalKeyboardKey.f21,
0x00000071: PhysicalKeyboardKey.f22,
0x00000072: PhysicalKeyboardKey.f23,
0x00000073: PhysicalKeyboardKey.f24,
0x00000074: PhysicalKeyboardKey.open,
0x00000075: PhysicalKeyboardKey.help,
0x00000077: PhysicalKeyboardKey.select,
0x00000079: PhysicalKeyboardKey.again,
0x0000007a: PhysicalKeyboardKey.undo,
0x0000007b: PhysicalKeyboardKey.cut,
0x0000007c: PhysicalKeyboardKey.copy,
0x0000007d: PhysicalKeyboardKey.paste,
0x0000007e: PhysicalKeyboardKey.find,
0x0000007f: PhysicalKeyboardKey.audioVolumeMute,
0x00000080: PhysicalKeyboardKey.audioVolumeUp,
0x00000081: PhysicalKeyboardKey.audioVolumeDown,
0x00000085: PhysicalKeyboardKey.numpadComma,
0x00000087: PhysicalKeyboardKey.intlRo,
0x00000088: PhysicalKeyboardKey.kanaMode,
0x00000089: PhysicalKeyboardKey.intlYen,
0x0000008a: PhysicalKeyboardKey.convert,
0x0000008b: PhysicalKeyboardKey.nonConvert,
0x00000090: PhysicalKeyboardKey.lang1,
0x00000091: PhysicalKeyboardKey.lang2,
0x00000092: PhysicalKeyboardKey.lang3,
0x00000093: PhysicalKeyboardKey.lang4,
0x00000094: PhysicalKeyboardKey.lang5,
0x0000009b: PhysicalKeyboardKey.abort,
0x000000a3: PhysicalKeyboardKey.props,
0x000000b6: PhysicalKeyboardKey.numpadParenLeft,
0x000000b7: PhysicalKeyboardKey.numpadParenRight,
0x000000bb: PhysicalKeyboardKey.numpadBackspace,
0x000000d0: PhysicalKeyboardKey.numpadMemoryStore,
0x000000d1: PhysicalKeyboardKey.numpadMemoryRecall,
0x000000d2: PhysicalKeyboardKey.numpadMemoryClear,
0x000000d3: PhysicalKeyboardKey.numpadMemoryAdd,
0x000000d4: PhysicalKeyboardKey.numpadMemorySubtract,
0x000000d7: PhysicalKeyboardKey.numpadSignChange,
0x000000d8: PhysicalKeyboardKey.numpadClear,
0x000000d9: PhysicalKeyboardKey.numpadClearEntry,
0x000000e0: PhysicalKeyboardKey.controlLeft,
0x000000e1: PhysicalKeyboardKey.shiftLeft,
0x000000e2: PhysicalKeyboardKey.altLeft,
0x000000e3: PhysicalKeyboardKey.metaLeft,
0x000000e4: PhysicalKeyboardKey.controlRight,
0x000000e5: PhysicalKeyboardKey.shiftRight,
0x000000e6: PhysicalKeyboardKey.altRight,
0x000000e7: PhysicalKeyboardKey.metaRight,
};
/// Maps iOS specific string values of nonvisible keys to logical keys
///
/// Some unprintable keys on iOS has literal names on their key label, such as
/// "UIKeyInputEscape". See:
/// https://developer.apple.com/documentation/uikit/uikeycommand/input_strings_for_special_keys?language=objc
const Map<String, LogicalKeyboardKey> kIosSpecialLogicalMap = <String, LogicalKeyboardKey>{
'UIKeyInputEscape': LogicalKeyboardKey.escape,
'UIKeyInputF1': LogicalKeyboardKey.f1,
'UIKeyInputF2': LogicalKeyboardKey.f2,
'UIKeyInputF3': LogicalKeyboardKey.f3,
'UIKeyInputF4': LogicalKeyboardKey.f4,
'UIKeyInputF5': LogicalKeyboardKey.f5,
'UIKeyInputF6': LogicalKeyboardKey.f6,
'UIKeyInputF7': LogicalKeyboardKey.f7,
'UIKeyInputF8': LogicalKeyboardKey.f8,
'UIKeyInputF9': LogicalKeyboardKey.f9,
'UIKeyInputF10': LogicalKeyboardKey.f10,
'UIKeyInputF11': LogicalKeyboardKey.f11,
'UIKeyInputF12': LogicalKeyboardKey.f12,
'UIKeyInputUpArrow': LogicalKeyboardKey.arrowUp,
'UIKeyInputDownArrow': LogicalKeyboardKey.arrowDown,
'UIKeyInputLeftArrow': LogicalKeyboardKey.arrowLeft,
'UIKeyInputRightArrow': LogicalKeyboardKey.arrowRight,
'UIKeyInputHome': LogicalKeyboardKey.home,
'UIKeyInputEnd': LogicalKeyboardKey.enter,
'UIKeyInputPageUp': LogicalKeyboardKey.pageUp,
'UIKeyInputPageDown': LogicalKeyboardKey.pageDown,
};
/// A map of iOS key codes which have printable representations, but appear
/// on the number pad. Used to provide different key objects for keys like
/// KEY_EQUALS and NUMPAD_EQUALS.
const Map<int, LogicalKeyboardKey> kIosNumPadMap = <int, LogicalKeyboardKey>{
0x00000054: LogicalKeyboardKey.numpadDivide,
0x00000055: LogicalKeyboardKey.numpadMultiply,
0x00000056: LogicalKeyboardKey.numpadSubtract,
0x00000057: LogicalKeyboardKey.numpadAdd,
0x00000059: LogicalKeyboardKey.numpad1,
0x0000005a: LogicalKeyboardKey.numpad2,
0x0000005b: LogicalKeyboardKey.numpad3,
0x0000005c: LogicalKeyboardKey.numpad4,
0x0000005d: LogicalKeyboardKey.numpad5,
0x0000005e: LogicalKeyboardKey.numpad6,
0x0000005f: LogicalKeyboardKey.numpad7,
0x00000060: LogicalKeyboardKey.numpad8,
0x00000061: LogicalKeyboardKey.numpad9,
0x00000062: LogicalKeyboardKey.numpad0,
0x00000063: LogicalKeyboardKey.numpadDecimal,
0x00000067: LogicalKeyboardKey.numpadEqual,
0x00000085: LogicalKeyboardKey.numpadComma,
0x000000b6: LogicalKeyboardKey.numpadParenLeft,
0x000000b7: LogicalKeyboardKey.numpadParenRight,
};
/// A map of iOS key codes presenting [LogicalKeyboardKey].
///
/// Logical key codes are not available in iOS key events. Most of the logical keys
/// are derived from its `characterIgnoringModifiers`, but those keys that don't
/// have a character representation will be derived from their key codes using
/// this map.
const Map<int, LogicalKeyboardKey> kIosToLogicalKey = <int, LogicalKeyboardKey>{
40: LogicalKeyboardKey.enter,
41: LogicalKeyboardKey.escape,
42: LogicalKeyboardKey.backspace,
43: LogicalKeyboardKey.tab,
57: LogicalKeyboardKey.capsLock,
58: LogicalKeyboardKey.f1,
59: LogicalKeyboardKey.f2,
60: LogicalKeyboardKey.f3,
61: LogicalKeyboardKey.f4,
62: LogicalKeyboardKey.f5,
63: LogicalKeyboardKey.f6,
64: LogicalKeyboardKey.f7,
65: LogicalKeyboardKey.f8,
66: LogicalKeyboardKey.f9,
67: LogicalKeyboardKey.f10,
68: LogicalKeyboardKey.f11,
69: LogicalKeyboardKey.f12,
73: LogicalKeyboardKey.insert,
74: LogicalKeyboardKey.home,
75: LogicalKeyboardKey.pageUp,
76: LogicalKeyboardKey.delete,
77: LogicalKeyboardKey.end,
78: LogicalKeyboardKey.pageDown,
79: LogicalKeyboardKey.arrowRight,
80: LogicalKeyboardKey.arrowLeft,
81: LogicalKeyboardKey.arrowDown,
82: LogicalKeyboardKey.arrowUp,
83: LogicalKeyboardKey.numLock,
84: LogicalKeyboardKey.numpadDivide,
85: LogicalKeyboardKey.numpadMultiply,
86: LogicalKeyboardKey.numpadSubtract,
87: LogicalKeyboardKey.numpadAdd,
88: LogicalKeyboardKey.numpadEnter,
89: LogicalKeyboardKey.numpad1,
90: LogicalKeyboardKey.numpad2,
91: LogicalKeyboardKey.numpad3,
92: LogicalKeyboardKey.numpad4,
93: LogicalKeyboardKey.numpad5,
94: LogicalKeyboardKey.numpad6,
95: LogicalKeyboardKey.numpad7,
96: LogicalKeyboardKey.numpad8,
97: LogicalKeyboardKey.numpad9,
98: LogicalKeyboardKey.numpad0,
99: LogicalKeyboardKey.numpadDecimal,
101: LogicalKeyboardKey.contextMenu,
103: LogicalKeyboardKey.numpadEqual,
104: LogicalKeyboardKey.f13,
105: LogicalKeyboardKey.f14,
106: LogicalKeyboardKey.f15,
107: LogicalKeyboardKey.f16,
108: LogicalKeyboardKey.f17,
109: LogicalKeyboardKey.f18,
110: LogicalKeyboardKey.f19,
111: LogicalKeyboardKey.f20,
127: LogicalKeyboardKey.audioVolumeMute,
128: LogicalKeyboardKey.audioVolumeUp,
129: LogicalKeyboardKey.audioVolumeDown,
133: LogicalKeyboardKey.numpadComma,
135: LogicalKeyboardKey.intlRo,
137: LogicalKeyboardKey.intlYen,
144: LogicalKeyboardKey.lang1,
145: LogicalKeyboardKey.lang2,
146: LogicalKeyboardKey.lang3,
147: LogicalKeyboardKey.lang4,
148: LogicalKeyboardKey.lang5,
224: LogicalKeyboardKey.controlLeft,
225: LogicalKeyboardKey.shiftLeft,
226: LogicalKeyboardKey.altLeft,
227: LogicalKeyboardKey.metaLeft,
228: LogicalKeyboardKey.controlRight,
229: LogicalKeyboardKey.shiftRight,
230: LogicalKeyboardKey.altRight,
231: LogicalKeyboardKey.metaRight,
};
/// Maps GLFW-specific key codes to the matching [LogicalKeyboardKey].
const Map<int, LogicalKeyboardKey> kGlfwToLogicalKey = <int, LogicalKeyboardKey>{
32: LogicalKeyboardKey.space,
39: LogicalKeyboardKey.quote,
44: LogicalKeyboardKey.comma,
45: LogicalKeyboardKey.minus,
46: LogicalKeyboardKey.period,
47: LogicalKeyboardKey.slash,
48: LogicalKeyboardKey.digit0,
49: LogicalKeyboardKey.digit1,
50: LogicalKeyboardKey.digit2,
51: LogicalKeyboardKey.digit3,
52: LogicalKeyboardKey.digit4,
53: LogicalKeyboardKey.digit5,
54: LogicalKeyboardKey.digit6,
55: LogicalKeyboardKey.digit7,
56: LogicalKeyboardKey.digit8,
57: LogicalKeyboardKey.digit9,
59: LogicalKeyboardKey.semicolon,
61: LogicalKeyboardKey.equal,
65: LogicalKeyboardKey.keyA,
66: LogicalKeyboardKey.keyB,
67: LogicalKeyboardKey.keyC,
68: LogicalKeyboardKey.keyD,
69: LogicalKeyboardKey.keyE,
70: LogicalKeyboardKey.keyF,
71: LogicalKeyboardKey.keyG,
72: LogicalKeyboardKey.keyH,
73: LogicalKeyboardKey.keyI,
74: LogicalKeyboardKey.keyJ,
75: LogicalKeyboardKey.keyK,
76: LogicalKeyboardKey.keyL,
77: LogicalKeyboardKey.keyM,
78: LogicalKeyboardKey.keyN,
79: LogicalKeyboardKey.keyO,
80: LogicalKeyboardKey.keyP,
81: LogicalKeyboardKey.keyQ,
82: LogicalKeyboardKey.keyR,
83: LogicalKeyboardKey.keyS,
84: LogicalKeyboardKey.keyT,
85: LogicalKeyboardKey.keyU,
86: LogicalKeyboardKey.keyV,
87: LogicalKeyboardKey.keyW,
88: LogicalKeyboardKey.keyX,
89: LogicalKeyboardKey.keyY,
90: LogicalKeyboardKey.keyZ,
91: LogicalKeyboardKey.bracketLeft,
92: LogicalKeyboardKey.backslash,
93: LogicalKeyboardKey.bracketRight,
96: LogicalKeyboardKey.backquote,
256: LogicalKeyboardKey.escape,
257: LogicalKeyboardKey.enter,
258: LogicalKeyboardKey.tab,
259: LogicalKeyboardKey.backspace,
260: LogicalKeyboardKey.insert,
261: LogicalKeyboardKey.delete,
262: LogicalKeyboardKey.arrowRight,
263: LogicalKeyboardKey.arrowLeft,
264: LogicalKeyboardKey.arrowDown,
265: LogicalKeyboardKey.arrowUp,
266: LogicalKeyboardKey.pageUp,
267: LogicalKeyboardKey.pageDown,
268: LogicalKeyboardKey.home,
269: LogicalKeyboardKey.end,
280: LogicalKeyboardKey.capsLock,
282: LogicalKeyboardKey.numLock,
283: LogicalKeyboardKey.printScreen,
284: LogicalKeyboardKey.pause,
290: LogicalKeyboardKey.f1,
291: LogicalKeyboardKey.f2,
292: LogicalKeyboardKey.f3,
293: LogicalKeyboardKey.f4,
294: LogicalKeyboardKey.f5,
295: LogicalKeyboardKey.f6,
296: LogicalKeyboardKey.f7,
297: LogicalKeyboardKey.f8,
298: LogicalKeyboardKey.f9,
299: LogicalKeyboardKey.f10,
300: LogicalKeyboardKey.f11,
301: LogicalKeyboardKey.f12,
302: LogicalKeyboardKey.f13,
303: LogicalKeyboardKey.f14,
304: LogicalKeyboardKey.f15,
305: LogicalKeyboardKey.f16,
306: LogicalKeyboardKey.f17,
307: LogicalKeyboardKey.f18,
308: LogicalKeyboardKey.f19,
309: LogicalKeyboardKey.f20,
310: LogicalKeyboardKey.f21,
311: LogicalKeyboardKey.f22,
312: LogicalKeyboardKey.f23,
320: LogicalKeyboardKey.numpad0,
321: LogicalKeyboardKey.numpad1,
322: LogicalKeyboardKey.numpad2,
323: LogicalKeyboardKey.numpad3,
324: LogicalKeyboardKey.numpad4,
325: LogicalKeyboardKey.numpad5,
326: LogicalKeyboardKey.numpad6,
327: LogicalKeyboardKey.numpad7,
328: LogicalKeyboardKey.numpad8,
329: LogicalKeyboardKey.numpad9,
330: LogicalKeyboardKey.numpadDecimal,
331: LogicalKeyboardKey.numpadDivide,
332: LogicalKeyboardKey.numpadMultiply,
334: LogicalKeyboardKey.numpadAdd,
335: LogicalKeyboardKey.numpadEnter,
336: LogicalKeyboardKey.numpadEqual,
340: LogicalKeyboardKey.shiftLeft,
341: LogicalKeyboardKey.controlLeft,
342: LogicalKeyboardKey.altLeft,
343: LogicalKeyboardKey.metaLeft,
344: LogicalKeyboardKey.shiftRight,
345: LogicalKeyboardKey.controlRight,
346: LogicalKeyboardKey.altRight,
347: LogicalKeyboardKey.metaRight,
348: LogicalKeyboardKey.contextMenu,
};
/// A map of GLFW key codes which have printable representations, but appear
/// on the number pad. Used to provide different key objects for keys like
/// KEY_EQUALS and NUMPAD_EQUALS.
const Map<int, LogicalKeyboardKey> kGlfwNumpadMap = <int, LogicalKeyboardKey>{
320: LogicalKeyboardKey.numpad0,
321: LogicalKeyboardKey.numpad1,
322: LogicalKeyboardKey.numpad2,
323: LogicalKeyboardKey.numpad3,
324: LogicalKeyboardKey.numpad4,
325: LogicalKeyboardKey.numpad5,
326: LogicalKeyboardKey.numpad6,
327: LogicalKeyboardKey.numpad7,
328: LogicalKeyboardKey.numpad8,
329: LogicalKeyboardKey.numpad9,
330: LogicalKeyboardKey.numpadDecimal,
331: LogicalKeyboardKey.numpadDivide,
332: LogicalKeyboardKey.numpadMultiply,
334: LogicalKeyboardKey.numpadAdd,
336: LogicalKeyboardKey.numpadEqual,
};
/// Maps GTK-specific key codes to the matching [LogicalKeyboardKey].
const Map<int, LogicalKeyboardKey> kGtkToLogicalKey = <int, LogicalKeyboardKey>{
165: LogicalKeyboardKey.intlYen,
64774: LogicalKeyboardKey.eraseEof,
64782: LogicalKeyboardKey.attn,
64789: LogicalKeyboardKey.copy,
64790: LogicalKeyboardKey.mediaPlay,
64795: LogicalKeyboardKey.exSel,
64797: LogicalKeyboardKey.printScreen,
64798: LogicalKeyboardKey.enter,
65027: LogicalKeyboardKey.altRight,
65032: LogicalKeyboardKey.groupNext,
65034: LogicalKeyboardKey.groupPrevious,
65036: LogicalKeyboardKey.groupFirst,
65038: LogicalKeyboardKey.groupLast,
65056: LogicalKeyboardKey.tab,
65076: LogicalKeyboardKey.enter,
65288: LogicalKeyboardKey.backspace,
65289: LogicalKeyboardKey.tab,
65291: LogicalKeyboardKey.clear,
65293: LogicalKeyboardKey.enter,
65299: LogicalKeyboardKey.pause,
65300: LogicalKeyboardKey.scrollLock,
65307: LogicalKeyboardKey.escape,
65313: LogicalKeyboardKey.kanjiMode,
65316: LogicalKeyboardKey.romaji,
65317: LogicalKeyboardKey.hiragana,
65318: LogicalKeyboardKey.katakana,
65319: LogicalKeyboardKey.hiraganaKatakana,
65320: LogicalKeyboardKey.zenkaku,
65321: LogicalKeyboardKey.hankaku,
65322: LogicalKeyboardKey.zenkakuHankaku,
65327: LogicalKeyboardKey.eisu,
65329: LogicalKeyboardKey.hangulMode,
65332: LogicalKeyboardKey.hanjaMode,
65335: LogicalKeyboardKey.codeInput,
65340: LogicalKeyboardKey.singleCandidate,
65342: LogicalKeyboardKey.previousCandidate,
65360: LogicalKeyboardKey.home,
65361: LogicalKeyboardKey.arrowLeft,
65362: LogicalKeyboardKey.arrowUp,
65363: LogicalKeyboardKey.arrowRight,
65364: LogicalKeyboardKey.arrowDown,
65365: LogicalKeyboardKey.pageUp,
65366: LogicalKeyboardKey.pageDown,
65367: LogicalKeyboardKey.end,
65376: LogicalKeyboardKey.select,
65377: LogicalKeyboardKey.print,
65378: LogicalKeyboardKey.execute,
65379: LogicalKeyboardKey.insert,
65381: LogicalKeyboardKey.undo,
65382: LogicalKeyboardKey.redo,
65383: LogicalKeyboardKey.contextMenu,
65384: LogicalKeyboardKey.find,
65385: LogicalKeyboardKey.cancel,
65386: LogicalKeyboardKey.help,
65406: LogicalKeyboardKey.modeChange,
65407: LogicalKeyboardKey.numLock,
65408: LogicalKeyboardKey.space,
65417: LogicalKeyboardKey.tab,
65421: LogicalKeyboardKey.numpadEnter,
65425: LogicalKeyboardKey.f1,
65426: LogicalKeyboardKey.f2,
65427: LogicalKeyboardKey.f3,
65428: LogicalKeyboardKey.f4,
65429: LogicalKeyboardKey.numpad7,
65430: LogicalKeyboardKey.numpad4,
65431: LogicalKeyboardKey.numpad8,
65432: LogicalKeyboardKey.numpad6,
65433: LogicalKeyboardKey.numpad2,
65434: LogicalKeyboardKey.numpad9,
65435: LogicalKeyboardKey.numpad3,
65436: LogicalKeyboardKey.numpad1,
65438: LogicalKeyboardKey.numpad0,
65439: LogicalKeyboardKey.numpadDecimal,
65450: LogicalKeyboardKey.numpadMultiply,
65451: LogicalKeyboardKey.numpadAdd,
65453: LogicalKeyboardKey.numpadSubtract,
65454: LogicalKeyboardKey.period,
65455: LogicalKeyboardKey.numpadDivide,
65456: LogicalKeyboardKey.numpad0,
65457: LogicalKeyboardKey.numpad1,
65458: LogicalKeyboardKey.numpad2,
65459: LogicalKeyboardKey.numpad3,
65460: LogicalKeyboardKey.numpad4,
65461: LogicalKeyboardKey.numpad5,
65462: LogicalKeyboardKey.numpad6,
65463: LogicalKeyboardKey.numpad7,
65464: LogicalKeyboardKey.numpad8,
65465: LogicalKeyboardKey.numpad9,
65469: LogicalKeyboardKey.numpadEqual,
65470: LogicalKeyboardKey.f1,
65471: LogicalKeyboardKey.f2,
65472: LogicalKeyboardKey.f3,
65473: LogicalKeyboardKey.f4,
65474: LogicalKeyboardKey.f5,
65475: LogicalKeyboardKey.f6,
65476: LogicalKeyboardKey.f7,
65477: LogicalKeyboardKey.f8,
65478: LogicalKeyboardKey.f9,
65479: LogicalKeyboardKey.f10,
65480: LogicalKeyboardKey.f11,
65481: LogicalKeyboardKey.f12,
65482: LogicalKeyboardKey.f13,
65483: LogicalKeyboardKey.f14,
65484: LogicalKeyboardKey.f15,
65485: LogicalKeyboardKey.f16,
65486: LogicalKeyboardKey.f17,
65487: LogicalKeyboardKey.f18,
65488: LogicalKeyboardKey.f19,
65489: LogicalKeyboardKey.f20,
65490: LogicalKeyboardKey.f21,
65491: LogicalKeyboardKey.f22,
65492: LogicalKeyboardKey.f23,
65493: LogicalKeyboardKey.f24,
65505: LogicalKeyboardKey.shiftLeft,
65506: LogicalKeyboardKey.shiftRight,
65507: LogicalKeyboardKey.controlLeft,
65508: LogicalKeyboardKey.controlRight,
65509: LogicalKeyboardKey.capsLock,
65511: LogicalKeyboardKey.metaLeft,
65512: LogicalKeyboardKey.metaRight,
65513: LogicalKeyboardKey.altLeft,
65514: LogicalKeyboardKey.altRight,
65515: LogicalKeyboardKey.superKey,
65516: LogicalKeyboardKey.superKey,
65517: LogicalKeyboardKey.hyper,
65518: LogicalKeyboardKey.hyper,
65535: LogicalKeyboardKey.delete,
269025026: LogicalKeyboardKey.brightnessUp,
269025027: LogicalKeyboardKey.brightnessDown,
269025040: LogicalKeyboardKey.standby,
269025041: LogicalKeyboardKey.audioVolumeDown,
269025042: LogicalKeyboardKey.audioVolumeMute,
269025043: LogicalKeyboardKey.audioVolumeUp,
269025044: LogicalKeyboardKey.mediaPlay,
269025045: LogicalKeyboardKey.mediaStop,
269025046: LogicalKeyboardKey.mediaTrackPrevious,
269025047: LogicalKeyboardKey.mediaTrackNext,
269025048: LogicalKeyboardKey.browserHome,
269025049: LogicalKeyboardKey.launchMail,
269025051: LogicalKeyboardKey.browserSearch,
269025052: LogicalKeyboardKey.mediaRecord,
269025056: LogicalKeyboardKey.launchCalendar,
269025062: LogicalKeyboardKey.browserBack,
269025063: LogicalKeyboardKey.browserForward,
269025064: LogicalKeyboardKey.browserStop,
269025065: LogicalKeyboardKey.browserRefresh,
269025066: LogicalKeyboardKey.powerOff,
269025067: LogicalKeyboardKey.wakeUp,
269025068: LogicalKeyboardKey.eject,
269025069: LogicalKeyboardKey.launchScreenSaver,
269025071: LogicalKeyboardKey.sleep,
269025072: LogicalKeyboardKey.browserFavorites,
269025073: LogicalKeyboardKey.mediaPause,
269025086: LogicalKeyboardKey.mediaRewind,
269025110: LogicalKeyboardKey.close,
269025111: LogicalKeyboardKey.copy,
269025112: LogicalKeyboardKey.cut,
269025121: LogicalKeyboardKey.logOff,
269025128: LogicalKeyboardKey.newKey,
269025131: LogicalKeyboardKey.open,
269025133: LogicalKeyboardKey.paste,
269025134: LogicalKeyboardKey.launchPhone,
269025138: LogicalKeyboardKey.mailReply,
269025143: LogicalKeyboardKey.save,
269025147: LogicalKeyboardKey.mailSend,
269025148: LogicalKeyboardKey.spellCheck,
269025163: LogicalKeyboardKey.zoomIn,
269025164: LogicalKeyboardKey.zoomOut,
269025168: LogicalKeyboardKey.mailForward,
269025175: LogicalKeyboardKey.mediaFastForward,
269025191: LogicalKeyboardKey.suspend,
};
/// A map of GTK key codes which have printable representations, but appear
/// on the number pad. Used to provide different key objects for keys like
/// KEY_EQUALS and NUMPAD_EQUALS.
const Map<int, LogicalKeyboardKey> kGtkNumpadMap = <int, LogicalKeyboardKey>{
65429: LogicalKeyboardKey.numpad7,
65430: LogicalKeyboardKey.numpad4,
65431: LogicalKeyboardKey.numpad8,
65432: LogicalKeyboardKey.numpad6,
65433: LogicalKeyboardKey.numpad2,
65434: LogicalKeyboardKey.numpad9,
65435: LogicalKeyboardKey.numpad3,
65436: LogicalKeyboardKey.numpad1,
65438: LogicalKeyboardKey.numpad0,
65439: LogicalKeyboardKey.numpadDecimal,
65450: LogicalKeyboardKey.numpadMultiply,
65451: LogicalKeyboardKey.numpadAdd,
65453: LogicalKeyboardKey.numpadSubtract,
65455: LogicalKeyboardKey.numpadDivide,
65456: LogicalKeyboardKey.numpad0,
65457: LogicalKeyboardKey.numpad1,
65458: LogicalKeyboardKey.numpad2,
65459: LogicalKeyboardKey.numpad3,
65460: LogicalKeyboardKey.numpad4,
65461: LogicalKeyboardKey.numpad5,
65462: LogicalKeyboardKey.numpad6,
65463: LogicalKeyboardKey.numpad7,
65464: LogicalKeyboardKey.numpad8,
65465: LogicalKeyboardKey.numpad9,
65469: LogicalKeyboardKey.numpadEqual,
};
/// Maps XKB specific key code values representing [PhysicalKeyboardKey].
const Map<int, PhysicalKeyboardKey> kLinuxToPhysicalKey = <int, PhysicalKeyboardKey>{
0x00000009: PhysicalKeyboardKey.escape,
0x0000000a: PhysicalKeyboardKey.digit1,
0x0000000b: PhysicalKeyboardKey.digit2,
0x0000000c: PhysicalKeyboardKey.digit3,
0x0000000d: PhysicalKeyboardKey.digit4,
0x0000000e: PhysicalKeyboardKey.digit5,
0x0000000f: PhysicalKeyboardKey.digit6,
0x00000010: PhysicalKeyboardKey.digit7,
0x00000011: PhysicalKeyboardKey.digit8,
0x00000012: PhysicalKeyboardKey.digit9,
0x00000013: PhysicalKeyboardKey.digit0,
0x00000014: PhysicalKeyboardKey.minus,
0x00000015: PhysicalKeyboardKey.equal,
0x00000016: PhysicalKeyboardKey.backspace,
0x00000017: PhysicalKeyboardKey.tab,
0x00000018: PhysicalKeyboardKey.keyQ,
0x00000019: PhysicalKeyboardKey.keyW,
0x0000001a: PhysicalKeyboardKey.keyE,
0x0000001b: PhysicalKeyboardKey.keyR,
0x0000001c: PhysicalKeyboardKey.keyT,
0x0000001d: PhysicalKeyboardKey.keyY,
0x0000001e: PhysicalKeyboardKey.keyU,
0x0000001f: PhysicalKeyboardKey.keyI,
0x00000020: PhysicalKeyboardKey.keyO,
0x00000021: PhysicalKeyboardKey.keyP,
0x00000022: PhysicalKeyboardKey.bracketLeft,
0x00000023: PhysicalKeyboardKey.bracketRight,
0x00000024: PhysicalKeyboardKey.enter,
0x00000025: PhysicalKeyboardKey.controlLeft,
0x00000026: PhysicalKeyboardKey.keyA,
0x00000027: PhysicalKeyboardKey.keyS,
0x00000028: PhysicalKeyboardKey.keyD,
0x00000029: PhysicalKeyboardKey.keyF,
0x0000002a: PhysicalKeyboardKey.keyG,
0x0000002b: PhysicalKeyboardKey.keyH,
0x0000002c: PhysicalKeyboardKey.keyJ,
0x0000002d: PhysicalKeyboardKey.keyK,
0x0000002e: PhysicalKeyboardKey.keyL,
0x0000002f: PhysicalKeyboardKey.semicolon,
0x00000030: PhysicalKeyboardKey.quote,
0x00000031: PhysicalKeyboardKey.backquote,
0x00000032: PhysicalKeyboardKey.shiftLeft,
0x00000033: PhysicalKeyboardKey.backslash,
0x00000034: PhysicalKeyboardKey.keyZ,
0x00000035: PhysicalKeyboardKey.keyX,
0x00000036: PhysicalKeyboardKey.keyC,
0x00000037: PhysicalKeyboardKey.keyV,
0x00000038: PhysicalKeyboardKey.keyB,
0x00000039: PhysicalKeyboardKey.keyN,
0x0000003a: PhysicalKeyboardKey.keyM,
0x0000003b: PhysicalKeyboardKey.comma,
0x0000003c: PhysicalKeyboardKey.period,
0x0000003d: PhysicalKeyboardKey.slash,
0x0000003e: PhysicalKeyboardKey.shiftRight,
0x0000003f: PhysicalKeyboardKey.numpadMultiply,
0x00000040: PhysicalKeyboardKey.altLeft,
0x00000041: PhysicalKeyboardKey.space,
0x00000042: PhysicalKeyboardKey.capsLock,
0x00000043: PhysicalKeyboardKey.f1,
0x00000044: PhysicalKeyboardKey.f2,
0x00000045: PhysicalKeyboardKey.f3,
0x00000046: PhysicalKeyboardKey.f4,
0x00000047: PhysicalKeyboardKey.f5,
0x00000048: PhysicalKeyboardKey.f6,
0x00000049: PhysicalKeyboardKey.f7,
0x0000004a: PhysicalKeyboardKey.f8,
0x0000004b: PhysicalKeyboardKey.f9,
0x0000004c: PhysicalKeyboardKey.f10,
0x0000004d: PhysicalKeyboardKey.numLock,
0x0000004e: PhysicalKeyboardKey.scrollLock,
0x0000004f: PhysicalKeyboardKey.numpad7,
0x00000050: PhysicalKeyboardKey.numpad8,
0x00000051: PhysicalKeyboardKey.numpad9,
0x00000052: PhysicalKeyboardKey.numpadSubtract,
0x00000053: PhysicalKeyboardKey.numpad4,
0x00000054: PhysicalKeyboardKey.numpad5,
0x00000055: PhysicalKeyboardKey.numpad6,
0x00000056: PhysicalKeyboardKey.numpadAdd,
0x00000057: PhysicalKeyboardKey.numpad1,
0x00000058: PhysicalKeyboardKey.numpad2,
0x00000059: PhysicalKeyboardKey.numpad3,
0x0000005a: PhysicalKeyboardKey.numpad0,
0x0000005b: PhysicalKeyboardKey.numpadDecimal,
0x0000005d: PhysicalKeyboardKey.lang5,
0x0000005e: PhysicalKeyboardKey.intlBackslash,
0x0000005f: PhysicalKeyboardKey.f11,
0x00000060: PhysicalKeyboardKey.f12,
0x00000061: PhysicalKeyboardKey.intlRo,
0x00000062: PhysicalKeyboardKey.lang3,
0x00000063: PhysicalKeyboardKey.lang4,
0x00000064: PhysicalKeyboardKey.convert,
0x00000065: PhysicalKeyboardKey.kanaMode,
0x00000066: PhysicalKeyboardKey.nonConvert,
0x00000068: PhysicalKeyboardKey.numpadEnter,
0x00000069: PhysicalKeyboardKey.controlRight,
0x0000006a: PhysicalKeyboardKey.numpadDivide,
0x0000006b: PhysicalKeyboardKey.printScreen,
0x0000006c: PhysicalKeyboardKey.altRight,
0x0000006e: PhysicalKeyboardKey.home,
0x0000006f: PhysicalKeyboardKey.arrowUp,
0x00000070: PhysicalKeyboardKey.pageUp,
0x00000071: PhysicalKeyboardKey.arrowLeft,
0x00000072: PhysicalKeyboardKey.arrowRight,
0x00000073: PhysicalKeyboardKey.end,
0x00000074: PhysicalKeyboardKey.arrowDown,
0x00000075: PhysicalKeyboardKey.pageDown,
0x00000076: PhysicalKeyboardKey.insert,
0x00000077: PhysicalKeyboardKey.delete,
0x00000079: PhysicalKeyboardKey.audioVolumeMute,
0x0000007a: PhysicalKeyboardKey.audioVolumeDown,
0x0000007b: PhysicalKeyboardKey.audioVolumeUp,
0x0000007c: PhysicalKeyboardKey.power,
0x0000007d: PhysicalKeyboardKey.numpadEqual,
0x0000007e: PhysicalKeyboardKey.numpadSignChange,
0x0000007f: PhysicalKeyboardKey.pause,
0x00000080: PhysicalKeyboardKey.showAllWindows,
0x00000081: PhysicalKeyboardKey.numpadComma,
0x00000082: PhysicalKeyboardKey.lang1,
0x00000083: PhysicalKeyboardKey.lang2,
0x00000084: PhysicalKeyboardKey.intlYen,
0x00000085: PhysicalKeyboardKey.metaLeft,
0x00000086: PhysicalKeyboardKey.metaRight,
0x00000087: PhysicalKeyboardKey.contextMenu,
0x00000088: PhysicalKeyboardKey.browserStop,
0x00000089: PhysicalKeyboardKey.again,
0x0000008b: PhysicalKeyboardKey.undo,
0x0000008c: PhysicalKeyboardKey.select,
0x0000008d: PhysicalKeyboardKey.copy,
0x0000008e: PhysicalKeyboardKey.open,
0x0000008f: PhysicalKeyboardKey.paste,
0x00000090: PhysicalKeyboardKey.find,
0x00000091: PhysicalKeyboardKey.cut,
0x00000092: PhysicalKeyboardKey.help,
0x00000094: PhysicalKeyboardKey.launchApp2,
0x00000096: PhysicalKeyboardKey.sleep,
0x00000097: PhysicalKeyboardKey.wakeUp,
0x00000098: PhysicalKeyboardKey.launchApp1,
0x0000009e: PhysicalKeyboardKey.launchInternetBrowser,
0x000000a0: PhysicalKeyboardKey.lockScreen,
0x000000a3: PhysicalKeyboardKey.launchMail,
0x000000a4: PhysicalKeyboardKey.browserFavorites,
0x000000a6: PhysicalKeyboardKey.browserBack,
0x000000a7: PhysicalKeyboardKey.browserForward,
0x000000a9: PhysicalKeyboardKey.eject,
0x000000ab: PhysicalKeyboardKey.mediaTrackNext,
0x000000ac: PhysicalKeyboardKey.mediaPlayPause,
0x000000ad: PhysicalKeyboardKey.mediaTrackPrevious,
0x000000ae: PhysicalKeyboardKey.mediaStop,
0x000000af: PhysicalKeyboardKey.mediaRecord,
0x000000b0: PhysicalKeyboardKey.mediaRewind,
0x000000b1: PhysicalKeyboardKey.launchPhone,
0x000000b3: PhysicalKeyboardKey.mediaSelect,
0x000000b4: PhysicalKeyboardKey.browserHome,
0x000000b5: PhysicalKeyboardKey.browserRefresh,
0x000000b6: PhysicalKeyboardKey.exit,
0x000000bb: PhysicalKeyboardKey.numpadParenLeft,
0x000000bc: PhysicalKeyboardKey.numpadParenRight,
0x000000bd: PhysicalKeyboardKey.newKey,
0x000000be: PhysicalKeyboardKey.redo,
0x000000bf: PhysicalKeyboardKey.f13,
0x000000c0: PhysicalKeyboardKey.f14,
0x000000c1: PhysicalKeyboardKey.f15,
0x000000c2: PhysicalKeyboardKey.f16,
0x000000c3: PhysicalKeyboardKey.f17,
0x000000c4: PhysicalKeyboardKey.f18,
0x000000c5: PhysicalKeyboardKey.f19,
0x000000c6: PhysicalKeyboardKey.f20,
0x000000c7: PhysicalKeyboardKey.f21,
0x000000c8: PhysicalKeyboardKey.f22,
0x000000c9: PhysicalKeyboardKey.f23,
0x000000ca: PhysicalKeyboardKey.f24,
0x000000d1: PhysicalKeyboardKey.mediaPause,
0x000000d6: PhysicalKeyboardKey.close,
0x000000d7: PhysicalKeyboardKey.mediaPlay,
0x000000d8: PhysicalKeyboardKey.mediaFastForward,
0x000000d9: PhysicalKeyboardKey.bassBoost,
0x000000da: PhysicalKeyboardKey.print,
0x000000e1: PhysicalKeyboardKey.browserSearch,
0x000000e8: PhysicalKeyboardKey.brightnessDown,
0x000000e9: PhysicalKeyboardKey.brightnessUp,
0x000000eb: PhysicalKeyboardKey.displayToggleIntExt,
0x000000ed: PhysicalKeyboardKey.kbdIllumDown,
0x000000ee: PhysicalKeyboardKey.kbdIllumUp,
0x000000ef: PhysicalKeyboardKey.mailSend,
0x000000f0: PhysicalKeyboardKey.mailReply,
0x000000f1: PhysicalKeyboardKey.mailForward,
0x000000f2: PhysicalKeyboardKey.save,
0x000000f3: PhysicalKeyboardKey.launchDocuments,
0x000000fc: PhysicalKeyboardKey.brightnessAuto,
0x00000100: PhysicalKeyboardKey.microphoneMuteToggle,
0x0000016e: PhysicalKeyboardKey.info,
0x00000172: PhysicalKeyboardKey.programGuide,
0x0000017a: PhysicalKeyboardKey.closedCaptionToggle,
0x0000017c: PhysicalKeyboardKey.zoomToggle,
0x0000017e: PhysicalKeyboardKey.launchKeyboardLayout,
0x00000190: PhysicalKeyboardKey.launchAudioBrowser,
0x00000195: PhysicalKeyboardKey.launchCalendar,
0x0000019d: PhysicalKeyboardKey.mediaLast,
0x000001a2: PhysicalKeyboardKey.channelUp,
0x000001a3: PhysicalKeyboardKey.channelDown,
0x000001aa: PhysicalKeyboardKey.zoomIn,
0x000001ab: PhysicalKeyboardKey.zoomOut,
0x000001ad: PhysicalKeyboardKey.launchWordProcessor,
0x000001af: PhysicalKeyboardKey.launchSpreadsheet,
0x000001b5: PhysicalKeyboardKey.launchContacts,
0x000001b7: PhysicalKeyboardKey.brightnessToggle,
0x000001b8: PhysicalKeyboardKey.spellCheck,
0x000001b9: PhysicalKeyboardKey.logOff,
0x0000024b: PhysicalKeyboardKey.launchControlPanel,
0x0000024c: PhysicalKeyboardKey.selectTask,
0x0000024d: PhysicalKeyboardKey.launchScreenSaver,
0x0000024e: PhysicalKeyboardKey.speechInputToggle,
0x0000024f: PhysicalKeyboardKey.launchAssistant,
0x00000250: PhysicalKeyboardKey.keyboardLayoutSelect,
0x00000258: PhysicalKeyboardKey.brightnessMinimum,
0x00000259: PhysicalKeyboardKey.brightnessMaximum,
0x00000281: PhysicalKeyboardKey.privacyScreenToggle,
};
/// Maps Web KeyboardEvent codes to the matching [LogicalKeyboardKey].
const Map<String, LogicalKeyboardKey> kWebToLogicalKey = <String, LogicalKeyboardKey>{
'AVRInput': LogicalKeyboardKey.avrInput,
'AVRPower': LogicalKeyboardKey.avrPower,
'Accel': LogicalKeyboardKey.accel,
'Accept': LogicalKeyboardKey.accept,
'Again': LogicalKeyboardKey.again,
'AllCandidates': LogicalKeyboardKey.allCandidates,
'Alphanumeric': LogicalKeyboardKey.alphanumeric,
'AltGraph': LogicalKeyboardKey.altGraph,
'AppSwitch': LogicalKeyboardKey.appSwitch,
'ArrowDown': LogicalKeyboardKey.arrowDown,
'ArrowLeft': LogicalKeyboardKey.arrowLeft,
'ArrowRight': LogicalKeyboardKey.arrowRight,
'ArrowUp': LogicalKeyboardKey.arrowUp,
'Attn': LogicalKeyboardKey.attn,
'AudioBalanceLeft': LogicalKeyboardKey.audioBalanceLeft,
'AudioBalanceRight': LogicalKeyboardKey.audioBalanceRight,
'AudioBassBoostDown': LogicalKeyboardKey.audioBassBoostDown,
'AudioBassBoostToggle': LogicalKeyboardKey.audioBassBoostToggle,
'AudioBassBoostUp': LogicalKeyboardKey.audioBassBoostUp,
'AudioFaderFront': LogicalKeyboardKey.audioFaderFront,
'AudioFaderRear': LogicalKeyboardKey.audioFaderRear,
'AudioSurroundModeNext': LogicalKeyboardKey.audioSurroundModeNext,
'AudioTrebleDown': LogicalKeyboardKey.audioTrebleDown,
'AudioTrebleUp': LogicalKeyboardKey.audioTrebleUp,
'AudioVolumeDown': LogicalKeyboardKey.audioVolumeDown,
'AudioVolumeMute': LogicalKeyboardKey.audioVolumeMute,
'AudioVolumeUp': LogicalKeyboardKey.audioVolumeUp,
'Backspace': LogicalKeyboardKey.backspace,
'BrightnessDown': LogicalKeyboardKey.brightnessDown,
'BrightnessUp': LogicalKeyboardKey.brightnessUp,
'BrowserBack': LogicalKeyboardKey.browserBack,
'BrowserFavorites': LogicalKeyboardKey.browserFavorites,
'BrowserForward': LogicalKeyboardKey.browserForward,
'BrowserHome': LogicalKeyboardKey.browserHome,
'BrowserRefresh': LogicalKeyboardKey.browserRefresh,
'BrowserSearch': LogicalKeyboardKey.browserSearch,
'BrowserStop': LogicalKeyboardKey.browserStop,
'Call': LogicalKeyboardKey.call,
'Camera': LogicalKeyboardKey.camera,
'CameraFocus': LogicalKeyboardKey.cameraFocus,
'Cancel': LogicalKeyboardKey.cancel,
'CapsLock': LogicalKeyboardKey.capsLock,
'ChannelDown': LogicalKeyboardKey.channelDown,
'ChannelUp': LogicalKeyboardKey.channelUp,
'Clear': LogicalKeyboardKey.clear,
'Close': LogicalKeyboardKey.close,
'ClosedCaptionToggle': LogicalKeyboardKey.closedCaptionToggle,
'CodeInput': LogicalKeyboardKey.codeInput,
'ColorF0Red': LogicalKeyboardKey.colorF0Red,
'ColorF1Green': LogicalKeyboardKey.colorF1Green,
'ColorF2Yellow': LogicalKeyboardKey.colorF2Yellow,
'ColorF3Blue': LogicalKeyboardKey.colorF3Blue,
'ColorF4Grey': LogicalKeyboardKey.colorF4Grey,
'ColorF5Brown': LogicalKeyboardKey.colorF5Brown,
'Compose': LogicalKeyboardKey.compose,
'ContextMenu': LogicalKeyboardKey.contextMenu,
'Convert': LogicalKeyboardKey.convert,
'Copy': LogicalKeyboardKey.copy,
'CrSel': LogicalKeyboardKey.crSel,
'Cut': LogicalKeyboardKey.cut,
'DVR': LogicalKeyboardKey.dvr,
'Delete': LogicalKeyboardKey.delete,
'Dimmer': LogicalKeyboardKey.dimmer,
'DisplaySwap': LogicalKeyboardKey.displaySwap,
'Eisu': LogicalKeyboardKey.eisu,
'Eject': LogicalKeyboardKey.eject,
'End': LogicalKeyboardKey.end,
'EndCall': LogicalKeyboardKey.endCall,
'Enter': LogicalKeyboardKey.enter,
'EraseEof': LogicalKeyboardKey.eraseEof,
'Esc': LogicalKeyboardKey.escape,
'Escape': LogicalKeyboardKey.escape,
'ExSel': LogicalKeyboardKey.exSel,
'Execute': LogicalKeyboardKey.execute,
'Exit': LogicalKeyboardKey.exit,
'F1': LogicalKeyboardKey.f1,
'F10': LogicalKeyboardKey.f10,
'F11': LogicalKeyboardKey.f11,
'F12': LogicalKeyboardKey.f12,
'F13': LogicalKeyboardKey.f13,
'F14': LogicalKeyboardKey.f14,
'F15': LogicalKeyboardKey.f15,
'F16': LogicalKeyboardKey.f16,
'F17': LogicalKeyboardKey.f17,
'F18': LogicalKeyboardKey.f18,
'F19': LogicalKeyboardKey.f19,
'F2': LogicalKeyboardKey.f2,
'F20': LogicalKeyboardKey.f20,
'F21': LogicalKeyboardKey.f21,
'F22': LogicalKeyboardKey.f22,
'F23': LogicalKeyboardKey.f23,
'F24': LogicalKeyboardKey.f24,
'F3': LogicalKeyboardKey.f3,
'F4': LogicalKeyboardKey.f4,
'F5': LogicalKeyboardKey.f5,
'F6': LogicalKeyboardKey.f6,
'F7': LogicalKeyboardKey.f7,
'F8': LogicalKeyboardKey.f8,
'F9': LogicalKeyboardKey.f9,
'FavoriteClear0': LogicalKeyboardKey.favoriteClear0,
'FavoriteClear1': LogicalKeyboardKey.favoriteClear1,
'FavoriteClear2': LogicalKeyboardKey.favoriteClear2,
'FavoriteClear3': LogicalKeyboardKey.favoriteClear3,
'FavoriteRecall0': LogicalKeyboardKey.favoriteRecall0,
'FavoriteRecall1': LogicalKeyboardKey.favoriteRecall1,
'FavoriteRecall2': LogicalKeyboardKey.favoriteRecall2,
'FavoriteRecall3': LogicalKeyboardKey.favoriteRecall3,
'FavoriteStore0': LogicalKeyboardKey.favoriteStore0,
'FavoriteStore1': LogicalKeyboardKey.favoriteStore1,
'FavoriteStore2': LogicalKeyboardKey.favoriteStore2,
'FavoriteStore3': LogicalKeyboardKey.favoriteStore3,
'FinalMode': LogicalKeyboardKey.finalMode,
'Find': LogicalKeyboardKey.find,
'Fn': LogicalKeyboardKey.fn,
'FnLock': LogicalKeyboardKey.fnLock,
'GoBack': LogicalKeyboardKey.goBack,
'GoHome': LogicalKeyboardKey.goHome,
'GroupFirst': LogicalKeyboardKey.groupFirst,
'GroupLast': LogicalKeyboardKey.groupLast,
'GroupNext': LogicalKeyboardKey.groupNext,
'GroupPrevious': LogicalKeyboardKey.groupPrevious,
'Guide': LogicalKeyboardKey.guide,
'GuideNextDay': LogicalKeyboardKey.guideNextDay,
'GuidePreviousDay': LogicalKeyboardKey.guidePreviousDay,
'HangulMode': LogicalKeyboardKey.hangulMode,
'HanjaMode': LogicalKeyboardKey.hanjaMode,
'Hankaku': LogicalKeyboardKey.hankaku,
'HeadsetHook': LogicalKeyboardKey.headsetHook,
'Help': LogicalKeyboardKey.help,
'Hibernate': LogicalKeyboardKey.hibernate,
'Hiragana': LogicalKeyboardKey.hiragana,
'HiraganaKatakana': LogicalKeyboardKey.hiraganaKatakana,
'Home': LogicalKeyboardKey.home,
'Hyper': LogicalKeyboardKey.hyper,
'Info': LogicalKeyboardKey.info,
'Insert': LogicalKeyboardKey.insert,
'InstantReplay': LogicalKeyboardKey.instantReplay,
'JunjaMode': LogicalKeyboardKey.junjaMode,
'KanaMode': LogicalKeyboardKey.kanaMode,
'KanjiMode': LogicalKeyboardKey.kanjiMode,
'Katakana': LogicalKeyboardKey.katakana,
'Key11': LogicalKeyboardKey.key11,
'Key12': LogicalKeyboardKey.key12,
'LastNumberRedial': LogicalKeyboardKey.lastNumberRedial,
'LaunchApplication1': LogicalKeyboardKey.launchApplication1,
'LaunchApplication2': LogicalKeyboardKey.launchApplication2,
'LaunchAssistant': LogicalKeyboardKey.launchAssistant,
'LaunchCalendar': LogicalKeyboardKey.launchCalendar,
'LaunchContacts': LogicalKeyboardKey.launchContacts,
'LaunchControlPanel': LogicalKeyboardKey.launchControlPanel,
'LaunchMail': LogicalKeyboardKey.launchMail,
'LaunchMediaPlayer': LogicalKeyboardKey.launchMediaPlayer,
'LaunchMusicPlayer': LogicalKeyboardKey.launchMusicPlayer,
'LaunchPhone': LogicalKeyboardKey.launchPhone,
'LaunchScreenSaver': LogicalKeyboardKey.launchScreenSaver,
'LaunchSpreadsheet': LogicalKeyboardKey.launchSpreadsheet,
'LaunchWebBrowser': LogicalKeyboardKey.launchWebBrowser,
'LaunchWebCam': LogicalKeyboardKey.launchWebCam,
'LaunchWordProcessor': LogicalKeyboardKey.launchWordProcessor,
'Link': LogicalKeyboardKey.link,
'ListProgram': LogicalKeyboardKey.listProgram,
'LiveContent': LogicalKeyboardKey.liveContent,
'Lock': LogicalKeyboardKey.lock,
'LogOff': LogicalKeyboardKey.logOff,
'MailForward': LogicalKeyboardKey.mailForward,
'MailReply': LogicalKeyboardKey.mailReply,
'MailSend': LogicalKeyboardKey.mailSend,
'MannerMode': LogicalKeyboardKey.mannerMode,
'MediaApps': LogicalKeyboardKey.mediaApps,
'MediaAudioTrack': LogicalKeyboardKey.mediaAudioTrack,
'MediaClose': LogicalKeyboardKey.mediaClose,
'MediaFastForward': LogicalKeyboardKey.mediaFastForward,
'MediaLast': LogicalKeyboardKey.mediaLast,
'MediaPause': LogicalKeyboardKey.mediaPause,
'MediaPlay': LogicalKeyboardKey.mediaPlay,
'MediaPlayPause': LogicalKeyboardKey.mediaPlayPause,
'MediaRecord': LogicalKeyboardKey.mediaRecord,
'MediaRewind': LogicalKeyboardKey.mediaRewind,
'MediaSkip': LogicalKeyboardKey.mediaSkip,
'MediaSkipBackward': LogicalKeyboardKey.mediaSkipBackward,
'MediaSkipForward': LogicalKeyboardKey.mediaSkipForward,
'MediaStepBackward': LogicalKeyboardKey.mediaStepBackward,
'MediaStepForward': LogicalKeyboardKey.mediaStepForward,
'MediaStop': LogicalKeyboardKey.mediaStop,
'MediaTopMenu': LogicalKeyboardKey.mediaTopMenu,
'MediaTrackNext': LogicalKeyboardKey.mediaTrackNext,
'MediaTrackPrevious': LogicalKeyboardKey.mediaTrackPrevious,
'MicrophoneToggle': LogicalKeyboardKey.microphoneToggle,
'MicrophoneVolumeDown': LogicalKeyboardKey.microphoneVolumeDown,
'MicrophoneVolumeMute': LogicalKeyboardKey.microphoneVolumeMute,
'MicrophoneVolumeUp': LogicalKeyboardKey.microphoneVolumeUp,
'ModeChange': LogicalKeyboardKey.modeChange,
'NavigateIn': LogicalKeyboardKey.navigateIn,
'NavigateNext': LogicalKeyboardKey.navigateNext,
'NavigateOut': LogicalKeyboardKey.navigateOut,
'NavigatePrevious': LogicalKeyboardKey.navigatePrevious,
'New': LogicalKeyboardKey.newKey,
'NextCandidate': LogicalKeyboardKey.nextCandidate,
'NextFavoriteChannel': LogicalKeyboardKey.nextFavoriteChannel,
'NextUserProfile': LogicalKeyboardKey.nextUserProfile,
'NonConvert': LogicalKeyboardKey.nonConvert,
'Notification': LogicalKeyboardKey.notification,
'NumLock': LogicalKeyboardKey.numLock,
'OnDemand': LogicalKeyboardKey.onDemand,
'Open': LogicalKeyboardKey.open,
'PageDown': LogicalKeyboardKey.pageDown,
'PageUp': LogicalKeyboardKey.pageUp,
'Pairing': LogicalKeyboardKey.pairing,
'Paste': LogicalKeyboardKey.paste,
'Pause': LogicalKeyboardKey.pause,
'PinPDown': LogicalKeyboardKey.pInPDown,
'PinPMove': LogicalKeyboardKey.pInPMove,
'PinPToggle': LogicalKeyboardKey.pInPToggle,
'PinPUp': LogicalKeyboardKey.pInPUp,
'Play': LogicalKeyboardKey.play,
'PlaySpeedDown': LogicalKeyboardKey.playSpeedDown,
'PlaySpeedReset': LogicalKeyboardKey.playSpeedReset,
'PlaySpeedUp': LogicalKeyboardKey.playSpeedUp,
'Power': LogicalKeyboardKey.power,
'PowerOff': LogicalKeyboardKey.powerOff,
'PreviousCandidate': LogicalKeyboardKey.previousCandidate,
'Print': LogicalKeyboardKey.print,
'PrintScreen': LogicalKeyboardKey.printScreen,
'Process': LogicalKeyboardKey.process,
'Props': LogicalKeyboardKey.props,
'RandomToggle': LogicalKeyboardKey.randomToggle,
'RcLowBattery': LogicalKeyboardKey.rcLowBattery,
'RecordSpeedNext': LogicalKeyboardKey.recordSpeedNext,
'Redo': LogicalKeyboardKey.redo,
'RfBypass': LogicalKeyboardKey.rfBypass,
'Romaji': LogicalKeyboardKey.romaji,
'STBInput': LogicalKeyboardKey.stbInput,
'STBPower': LogicalKeyboardKey.stbPower,
'Save': LogicalKeyboardKey.save,
'ScanChannelsToggle': LogicalKeyboardKey.scanChannelsToggle,
'ScreenModeNext': LogicalKeyboardKey.screenModeNext,
'ScrollLock': LogicalKeyboardKey.scrollLock,
'Select': LogicalKeyboardKey.select,
'Settings': LogicalKeyboardKey.settings,
'ShiftLevel5': LogicalKeyboardKey.shiftLevel5,
'SingleCandidate': LogicalKeyboardKey.singleCandidate,
'Soft1': LogicalKeyboardKey.soft1,
'Soft2': LogicalKeyboardKey.soft2,
'Soft3': LogicalKeyboardKey.soft3,
'Soft4': LogicalKeyboardKey.soft4,
'Soft5': LogicalKeyboardKey.soft5,
'Soft6': LogicalKeyboardKey.soft6,
'Soft7': LogicalKeyboardKey.soft7,
'Soft8': LogicalKeyboardKey.soft8,
'SpeechCorrectionList': LogicalKeyboardKey.speechCorrectionList,
'SpeechInputToggle': LogicalKeyboardKey.speechInputToggle,
'SpellCheck': LogicalKeyboardKey.spellCheck,
'SplitScreenToggle': LogicalKeyboardKey.splitScreenToggle,
'Standby': LogicalKeyboardKey.standby,
'Subtitle': LogicalKeyboardKey.subtitle,
'Super': LogicalKeyboardKey.superKey,
'Symbol': LogicalKeyboardKey.symbol,
'SymbolLock': LogicalKeyboardKey.symbolLock,
'TV': LogicalKeyboardKey.tv,
'TV3DMode': LogicalKeyboardKey.tv3DMode,
'TVAntennaCable': LogicalKeyboardKey.tvAntennaCable,
'TVAudioDescription': LogicalKeyboardKey.tvAudioDescription,
'TVAudioDescriptionMixDown': LogicalKeyboardKey.tvAudioDescriptionMixDown,
'TVAudioDescriptionMixUp': LogicalKeyboardKey.tvAudioDescriptionMixUp,
'TVContentsMenu': LogicalKeyboardKey.tvContentsMenu,
'TVDataService': LogicalKeyboardKey.tvDataService,
'TVInput': LogicalKeyboardKey.tvInput,
'TVInputComponent1': LogicalKeyboardKey.tvInputComponent1,
'TVInputComponent2': LogicalKeyboardKey.tvInputComponent2,
'TVInputComposite1': LogicalKeyboardKey.tvInputComposite1,
'TVInputComposite2': LogicalKeyboardKey.tvInputComposite2,
'TVInputHDMI1': LogicalKeyboardKey.tvInputHDMI1,
'TVInputHDMI2': LogicalKeyboardKey.tvInputHDMI2,
'TVInputHDMI3': LogicalKeyboardKey.tvInputHDMI3,
'TVInputHDMI4': LogicalKeyboardKey.tvInputHDMI4,
'TVInputVGA1': LogicalKeyboardKey.tvInputVGA1,
'TVMediaContext': LogicalKeyboardKey.tvMediaContext,
'TVNetwork': LogicalKeyboardKey.tvNetwork,
'TVNumberEntry': LogicalKeyboardKey.tvNumberEntry,
'TVPower': LogicalKeyboardKey.tvPower,
'TVRadioService': LogicalKeyboardKey.tvRadioService,
'TVSatellite': LogicalKeyboardKey.tvSatellite,
'TVSatelliteBS': LogicalKeyboardKey.tvSatelliteBS,
'TVSatelliteCS': LogicalKeyboardKey.tvSatelliteCS,
'TVSatelliteToggle': LogicalKeyboardKey.tvSatelliteToggle,
'TVTerrestrialAnalog': LogicalKeyboardKey.tvTerrestrialAnalog,
'TVTerrestrialDigital': LogicalKeyboardKey.tvTerrestrialDigital,
'TVTimer': LogicalKeyboardKey.tvTimer,
'Tab': LogicalKeyboardKey.tab,
'Teletext': LogicalKeyboardKey.teletext,
'Undo': LogicalKeyboardKey.undo,
'Unidentified': LogicalKeyboardKey.unidentified,
'VideoModeNext': LogicalKeyboardKey.videoModeNext,
'VoiceDial': LogicalKeyboardKey.voiceDial,
'WakeUp': LogicalKeyboardKey.wakeUp,
'Wink': LogicalKeyboardKey.wink,
'Zenkaku': LogicalKeyboardKey.zenkaku,
'ZenkakuHankaku': LogicalKeyboardKey.zenkakuHankaku,
'ZoomIn': LogicalKeyboardKey.zoomIn,
'ZoomOut': LogicalKeyboardKey.zoomOut,
'ZoomToggle': LogicalKeyboardKey.zoomToggle,
};
/// Maps Web KeyboardEvent codes to the matching [PhysicalKeyboardKey].
const Map<String, PhysicalKeyboardKey> kWebToPhysicalKey = <String, PhysicalKeyboardKey>{
'Abort': PhysicalKeyboardKey.abort,
'Again': PhysicalKeyboardKey.again,
'AltLeft': PhysicalKeyboardKey.altLeft,
'AltRight': PhysicalKeyboardKey.altRight,
'ArrowDown': PhysicalKeyboardKey.arrowDown,
'ArrowLeft': PhysicalKeyboardKey.arrowLeft,
'ArrowRight': PhysicalKeyboardKey.arrowRight,
'ArrowUp': PhysicalKeyboardKey.arrowUp,
'AudioVolumeDown': PhysicalKeyboardKey.audioVolumeDown,
'AudioVolumeMute': PhysicalKeyboardKey.audioVolumeMute,
'AudioVolumeUp': PhysicalKeyboardKey.audioVolumeUp,
'Backquote': PhysicalKeyboardKey.backquote,
'Backslash': PhysicalKeyboardKey.backslash,
'Backspace': PhysicalKeyboardKey.backspace,
'BracketLeft': PhysicalKeyboardKey.bracketLeft,
'BracketRight': PhysicalKeyboardKey.bracketRight,
'BrightnessDown': PhysicalKeyboardKey.brightnessDown,
'BrightnessUp': PhysicalKeyboardKey.brightnessUp,
'BrowserBack': PhysicalKeyboardKey.browserBack,
'BrowserFavorites': PhysicalKeyboardKey.browserFavorites,
'BrowserForward': PhysicalKeyboardKey.browserForward,
'BrowserHome': PhysicalKeyboardKey.browserHome,
'BrowserRefresh': PhysicalKeyboardKey.browserRefresh,
'BrowserSearch': PhysicalKeyboardKey.browserSearch,
'BrowserStop': PhysicalKeyboardKey.browserStop,
'CapsLock': PhysicalKeyboardKey.capsLock,
'Comma': PhysicalKeyboardKey.comma,
'ContextMenu': PhysicalKeyboardKey.contextMenu,
'ControlLeft': PhysicalKeyboardKey.controlLeft,
'ControlRight': PhysicalKeyboardKey.controlRight,
'Convert': PhysicalKeyboardKey.convert,
'Copy': PhysicalKeyboardKey.copy,
'Cut': PhysicalKeyboardKey.cut,
'Delete': PhysicalKeyboardKey.delete,
'Digit0': PhysicalKeyboardKey.digit0,
'Digit1': PhysicalKeyboardKey.digit1,
'Digit2': PhysicalKeyboardKey.digit2,
'Digit3': PhysicalKeyboardKey.digit3,
'Digit4': PhysicalKeyboardKey.digit4,
'Digit5': PhysicalKeyboardKey.digit5,
'Digit6': PhysicalKeyboardKey.digit6,
'Digit7': PhysicalKeyboardKey.digit7,
'Digit8': PhysicalKeyboardKey.digit8,
'Digit9': PhysicalKeyboardKey.digit9,
'DisplayToggleIntExt': PhysicalKeyboardKey.displayToggleIntExt,
'Eject': PhysicalKeyboardKey.eject,
'End': PhysicalKeyboardKey.end,
'Enter': PhysicalKeyboardKey.enter,
'Equal': PhysicalKeyboardKey.equal,
'Escape': PhysicalKeyboardKey.escape,
'Esc': PhysicalKeyboardKey.escape,
'F1': PhysicalKeyboardKey.f1,
'F10': PhysicalKeyboardKey.f10,
'F11': PhysicalKeyboardKey.f11,
'F12': PhysicalKeyboardKey.f12,
'F13': PhysicalKeyboardKey.f13,
'F14': PhysicalKeyboardKey.f14,
'F15': PhysicalKeyboardKey.f15,
'F16': PhysicalKeyboardKey.f16,
'F17': PhysicalKeyboardKey.f17,
'F18': PhysicalKeyboardKey.f18,
'F19': PhysicalKeyboardKey.f19,
'F2': PhysicalKeyboardKey.f2,
'F20': PhysicalKeyboardKey.f20,
'F21': PhysicalKeyboardKey.f21,
'F22': PhysicalKeyboardKey.f22,
'F23': PhysicalKeyboardKey.f23,
'F24': PhysicalKeyboardKey.f24,
'F3': PhysicalKeyboardKey.f3,
'F4': PhysicalKeyboardKey.f4,
'F5': PhysicalKeyboardKey.f5,
'F6': PhysicalKeyboardKey.f6,
'F7': PhysicalKeyboardKey.f7,
'F8': PhysicalKeyboardKey.f8,
'F9': PhysicalKeyboardKey.f9,
'Find': PhysicalKeyboardKey.find,
'Fn': PhysicalKeyboardKey.fn,
'FnLock': PhysicalKeyboardKey.fnLock,
'GameButton1': PhysicalKeyboardKey.gameButton1,
'GameButton10': PhysicalKeyboardKey.gameButton10,
'GameButton11': PhysicalKeyboardKey.gameButton11,
'GameButton12': PhysicalKeyboardKey.gameButton12,
'GameButton13': PhysicalKeyboardKey.gameButton13,
'GameButton14': PhysicalKeyboardKey.gameButton14,
'GameButton15': PhysicalKeyboardKey.gameButton15,
'GameButton16': PhysicalKeyboardKey.gameButton16,
'GameButton2': PhysicalKeyboardKey.gameButton2,
'GameButton3': PhysicalKeyboardKey.gameButton3,
'GameButton4': PhysicalKeyboardKey.gameButton4,
'GameButton5': PhysicalKeyboardKey.gameButton5,
'GameButton6': PhysicalKeyboardKey.gameButton6,
'GameButton7': PhysicalKeyboardKey.gameButton7,
'GameButton8': PhysicalKeyboardKey.gameButton8,
'GameButton9': PhysicalKeyboardKey.gameButton9,
'GameButtonA': PhysicalKeyboardKey.gameButtonA,
'GameButtonB': PhysicalKeyboardKey.gameButtonB,
'GameButtonC': PhysicalKeyboardKey.gameButtonC,
'GameButtonLeft1': PhysicalKeyboardKey.gameButtonLeft1,
'GameButtonLeft2': PhysicalKeyboardKey.gameButtonLeft2,
'GameButtonMode': PhysicalKeyboardKey.gameButtonMode,
'GameButtonRight1': PhysicalKeyboardKey.gameButtonRight1,
'GameButtonRight2': PhysicalKeyboardKey.gameButtonRight2,
'GameButtonSelect': PhysicalKeyboardKey.gameButtonSelect,
'GameButtonStart': PhysicalKeyboardKey.gameButtonStart,
'GameButtonThumbLeft': PhysicalKeyboardKey.gameButtonThumbLeft,
'GameButtonThumbRight': PhysicalKeyboardKey.gameButtonThumbRight,
'GameButtonX': PhysicalKeyboardKey.gameButtonX,
'GameButtonY': PhysicalKeyboardKey.gameButtonY,
'GameButtonZ': PhysicalKeyboardKey.gameButtonZ,
'Help': PhysicalKeyboardKey.help,
'Home': PhysicalKeyboardKey.home,
'Hyper': PhysicalKeyboardKey.hyper,
'Insert': PhysicalKeyboardKey.insert,
'IntlBackslash': PhysicalKeyboardKey.intlBackslash,
'IntlRo': PhysicalKeyboardKey.intlRo,
'IntlYen': PhysicalKeyboardKey.intlYen,
'KanaMode': PhysicalKeyboardKey.kanaMode,
'KeyA': PhysicalKeyboardKey.keyA,
'KeyB': PhysicalKeyboardKey.keyB,
'KeyC': PhysicalKeyboardKey.keyC,
'KeyD': PhysicalKeyboardKey.keyD,
'KeyE': PhysicalKeyboardKey.keyE,
'KeyF': PhysicalKeyboardKey.keyF,
'KeyG': PhysicalKeyboardKey.keyG,
'KeyH': PhysicalKeyboardKey.keyH,
'KeyI': PhysicalKeyboardKey.keyI,
'KeyJ': PhysicalKeyboardKey.keyJ,
'KeyK': PhysicalKeyboardKey.keyK,
'KeyL': PhysicalKeyboardKey.keyL,
'KeyM': PhysicalKeyboardKey.keyM,
'KeyN': PhysicalKeyboardKey.keyN,
'KeyO': PhysicalKeyboardKey.keyO,
'KeyP': PhysicalKeyboardKey.keyP,
'KeyQ': PhysicalKeyboardKey.keyQ,
'KeyR': PhysicalKeyboardKey.keyR,
'KeyS': PhysicalKeyboardKey.keyS,
'KeyT': PhysicalKeyboardKey.keyT,
'KeyU': PhysicalKeyboardKey.keyU,
'KeyV': PhysicalKeyboardKey.keyV,
'KeyW': PhysicalKeyboardKey.keyW,
'KeyX': PhysicalKeyboardKey.keyX,
'KeyY': PhysicalKeyboardKey.keyY,
'KeyZ': PhysicalKeyboardKey.keyZ,
'KeyboardLayoutSelect': PhysicalKeyboardKey.keyboardLayoutSelect,
'Lang1': PhysicalKeyboardKey.lang1,
'Lang2': PhysicalKeyboardKey.lang2,
'Lang3': PhysicalKeyboardKey.lang3,
'Lang4': PhysicalKeyboardKey.lang4,
'Lang5': PhysicalKeyboardKey.lang5,
'LaunchApp1': PhysicalKeyboardKey.launchApp1,
'LaunchApp2': PhysicalKeyboardKey.launchApp2,
'LaunchAssistant': PhysicalKeyboardKey.launchAssistant,
'LaunchControlPanel': PhysicalKeyboardKey.launchControlPanel,
'LaunchMail': PhysicalKeyboardKey.launchMail,
'LaunchScreenSaver': PhysicalKeyboardKey.launchScreenSaver,
'MailForward': PhysicalKeyboardKey.mailForward,
'MailReply': PhysicalKeyboardKey.mailReply,
'MailSend': PhysicalKeyboardKey.mailSend,
'MediaFastForward': PhysicalKeyboardKey.mediaFastForward,
'MediaPause': PhysicalKeyboardKey.mediaPause,
'MediaPlay': PhysicalKeyboardKey.mediaPlay,
'MediaPlayPause': PhysicalKeyboardKey.mediaPlayPause,
'MediaRecord': PhysicalKeyboardKey.mediaRecord,
'MediaRewind': PhysicalKeyboardKey.mediaRewind,
'MediaSelect': PhysicalKeyboardKey.mediaSelect,
'MediaStop': PhysicalKeyboardKey.mediaStop,
'MediaTrackNext': PhysicalKeyboardKey.mediaTrackNext,
'MediaTrackPrevious': PhysicalKeyboardKey.mediaTrackPrevious,
'MetaLeft': PhysicalKeyboardKey.metaLeft,
'MetaRight': PhysicalKeyboardKey.metaRight,
'MicrophoneMuteToggle': PhysicalKeyboardKey.microphoneMuteToggle,
'Minus': PhysicalKeyboardKey.minus,
'NonConvert': PhysicalKeyboardKey.nonConvert,
'NumLock': PhysicalKeyboardKey.numLock,
'Numpad0': PhysicalKeyboardKey.numpad0,
'Numpad1': PhysicalKeyboardKey.numpad1,
'Numpad2': PhysicalKeyboardKey.numpad2,
'Numpad3': PhysicalKeyboardKey.numpad3,
'Numpad4': PhysicalKeyboardKey.numpad4,
'Numpad5': PhysicalKeyboardKey.numpad5,
'Numpad6': PhysicalKeyboardKey.numpad6,
'Numpad7': PhysicalKeyboardKey.numpad7,
'Numpad8': PhysicalKeyboardKey.numpad8,
'Numpad9': PhysicalKeyboardKey.numpad9,
'NumpadAdd': PhysicalKeyboardKey.numpadAdd,
'NumpadBackspace': PhysicalKeyboardKey.numpadBackspace,
'NumpadClear': PhysicalKeyboardKey.numpadClear,
'NumpadClearEntry': PhysicalKeyboardKey.numpadClearEntry,
'NumpadComma': PhysicalKeyboardKey.numpadComma,
'NumpadDecimal': PhysicalKeyboardKey.numpadDecimal,
'NumpadDivide': PhysicalKeyboardKey.numpadDivide,
'NumpadEnter': PhysicalKeyboardKey.numpadEnter,
'NumpadEqual': PhysicalKeyboardKey.numpadEqual,
'NumpadMemoryAdd': PhysicalKeyboardKey.numpadMemoryAdd,
'NumpadMemoryClear': PhysicalKeyboardKey.numpadMemoryClear,
'NumpadMemoryRecall': PhysicalKeyboardKey.numpadMemoryRecall,
'NumpadMemoryStore': PhysicalKeyboardKey.numpadMemoryStore,
'NumpadMemorySubtract': PhysicalKeyboardKey.numpadMemorySubtract,
'NumpadMultiply': PhysicalKeyboardKey.numpadMultiply,
'NumpadParenLeft': PhysicalKeyboardKey.numpadParenLeft,
'NumpadParenRight': PhysicalKeyboardKey.numpadParenRight,
'NumpadSubtract': PhysicalKeyboardKey.numpadSubtract,
'Open': PhysicalKeyboardKey.open,
'PageDown': PhysicalKeyboardKey.pageDown,
'PageUp': PhysicalKeyboardKey.pageUp,
'Paste': PhysicalKeyboardKey.paste,
'Pause': PhysicalKeyboardKey.pause,
'Period': PhysicalKeyboardKey.period,
'Power': PhysicalKeyboardKey.power,
'PrintScreen': PhysicalKeyboardKey.printScreen,
'PrivacyScreenToggle': PhysicalKeyboardKey.privacyScreenToggle,
'Props': PhysicalKeyboardKey.props,
'Quote': PhysicalKeyboardKey.quote,
'Resume': PhysicalKeyboardKey.resume,
'ScrollLock': PhysicalKeyboardKey.scrollLock,
'Select': PhysicalKeyboardKey.select,
'SelectTask': PhysicalKeyboardKey.selectTask,
'Semicolon': PhysicalKeyboardKey.semicolon,
'ShiftLeft': PhysicalKeyboardKey.shiftLeft,
'ShiftRight': PhysicalKeyboardKey.shiftRight,
'ShowAllWindows': PhysicalKeyboardKey.showAllWindows,
'Slash': PhysicalKeyboardKey.slash,
'Sleep': PhysicalKeyboardKey.sleep,
'Space': PhysicalKeyboardKey.space,
'Super': PhysicalKeyboardKey.superKey,
'Suspend': PhysicalKeyboardKey.suspend,
'Tab': PhysicalKeyboardKey.tab,
'Turbo': PhysicalKeyboardKey.turbo,
'Undo': PhysicalKeyboardKey.undo,
'WakeUp': PhysicalKeyboardKey.wakeUp,
'ZoomToggle': PhysicalKeyboardKey.zoomToggle,
};
/// A map of Web KeyboardEvent codes which have printable representations, but appear
/// on the number pad. Used to provide different key objects for keys like
/// KEY_EQUALS and NUMPAD_EQUALS.
const Map<String, LogicalKeyboardKey> kWebNumPadMap = <String, LogicalKeyboardKey>{
'Numpad0': LogicalKeyboardKey.numpad0,
'Numpad1': LogicalKeyboardKey.numpad1,
'Numpad2': LogicalKeyboardKey.numpad2,
'Numpad3': LogicalKeyboardKey.numpad3,
'Numpad4': LogicalKeyboardKey.numpad4,
'Numpad5': LogicalKeyboardKey.numpad5,
'Numpad6': LogicalKeyboardKey.numpad6,
'Numpad7': LogicalKeyboardKey.numpad7,
'Numpad8': LogicalKeyboardKey.numpad8,
'Numpad9': LogicalKeyboardKey.numpad9,
'NumpadAdd': LogicalKeyboardKey.numpadAdd,
'NumpadComma': LogicalKeyboardKey.numpadComma,
'NumpadDecimal': LogicalKeyboardKey.numpadDecimal,
'NumpadDivide': LogicalKeyboardKey.numpadDivide,
'NumpadEqual': LogicalKeyboardKey.numpadEqual,
'NumpadMultiply': LogicalKeyboardKey.numpadMultiply,
'NumpadParenLeft': LogicalKeyboardKey.numpadParenLeft,
'NumpadParenRight': LogicalKeyboardKey.numpadParenRight,
'NumpadSubtract': LogicalKeyboardKey.numpadSubtract,
};
/// A map of Web KeyboardEvent keys which needs to be decided based on location,
/// typically for numpad keys and modifier keys. Used to provide different key
/// objects for keys like KEY_EQUALS and NUMPAD_EQUALS.
const Map<String, List<LogicalKeyboardKey?>> kWebLocationMap = <String, List<LogicalKeyboardKey?>>{
'*': <LogicalKeyboardKey?>[LogicalKeyboardKey.asterisk, null, null, LogicalKeyboardKey.numpadMultiply],
'+': <LogicalKeyboardKey?>[LogicalKeyboardKey.add, null, null, LogicalKeyboardKey.numpadAdd],
'-': <LogicalKeyboardKey?>[LogicalKeyboardKey.minus, null, null, LogicalKeyboardKey.numpadSubtract],
'.': <LogicalKeyboardKey?>[LogicalKeyboardKey.period, null, null, LogicalKeyboardKey.numpadDecimal],
'/': <LogicalKeyboardKey?>[LogicalKeyboardKey.slash, null, null, LogicalKeyboardKey.numpadDivide],
'0': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit0, null, null, LogicalKeyboardKey.numpad0],
'1': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit1, null, null, LogicalKeyboardKey.numpad1],
'2': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit2, null, null, LogicalKeyboardKey.numpad2],
'3': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit3, null, null, LogicalKeyboardKey.numpad3],
'4': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit4, null, null, LogicalKeyboardKey.numpad4],
'5': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit5, null, null, LogicalKeyboardKey.numpad5],
'6': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit6, null, null, LogicalKeyboardKey.numpad6],
'7': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit7, null, null, LogicalKeyboardKey.numpad7],
'8': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit8, null, null, LogicalKeyboardKey.numpad8],
'9': <LogicalKeyboardKey?>[LogicalKeyboardKey.digit9, null, null, LogicalKeyboardKey.numpad9],
'Alt': <LogicalKeyboardKey?>[LogicalKeyboardKey.altLeft, LogicalKeyboardKey.altLeft, LogicalKeyboardKey.altRight, null],
'AltGraph': <LogicalKeyboardKey?>[LogicalKeyboardKey.altGraph, null, LogicalKeyboardKey.altGraph, null],
'ArrowDown': <LogicalKeyboardKey?>[LogicalKeyboardKey.arrowDown, null, null, LogicalKeyboardKey.numpad2],
'ArrowLeft': <LogicalKeyboardKey?>[LogicalKeyboardKey.arrowLeft, null, null, LogicalKeyboardKey.numpad4],
'ArrowRight': <LogicalKeyboardKey?>[LogicalKeyboardKey.arrowRight, null, null, LogicalKeyboardKey.numpad6],
'ArrowUp': <LogicalKeyboardKey?>[LogicalKeyboardKey.arrowUp, null, null, LogicalKeyboardKey.numpad8],
'Clear': <LogicalKeyboardKey?>[LogicalKeyboardKey.clear, null, null, LogicalKeyboardKey.numpad5],
'Control': <LogicalKeyboardKey?>[LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.controlRight, null],
'Delete': <LogicalKeyboardKey?>[LogicalKeyboardKey.delete, null, null, LogicalKeyboardKey.numpadDecimal],
'End': <LogicalKeyboardKey?>[LogicalKeyboardKey.end, null, null, LogicalKeyboardKey.numpad1],
'Enter': <LogicalKeyboardKey?>[LogicalKeyboardKey.enter, null, null, LogicalKeyboardKey.numpadEnter],
'Home': <LogicalKeyboardKey?>[LogicalKeyboardKey.home, null, null, LogicalKeyboardKey.numpad7],
'Insert': <LogicalKeyboardKey?>[LogicalKeyboardKey.insert, null, null, LogicalKeyboardKey.numpad0],
'Meta': <LogicalKeyboardKey?>[LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaRight, null],
'PageDown': <LogicalKeyboardKey?>[LogicalKeyboardKey.pageDown, null, null, LogicalKeyboardKey.numpad3],
'PageUp': <LogicalKeyboardKey?>[LogicalKeyboardKey.pageUp, null, null, LogicalKeyboardKey.numpad9],
'Shift': <LogicalKeyboardKey?>[LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight, null],
};
/// Maps Windows KeyboardEvent codes to the matching [LogicalKeyboardKey].
const Map<int, LogicalKeyboardKey> kWindowsToLogicalKey = <int, LogicalKeyboardKey>{
3: LogicalKeyboardKey.cancel,
8: LogicalKeyboardKey.backspace,
9: LogicalKeyboardKey.tab,
12: LogicalKeyboardKey.clear,
13: LogicalKeyboardKey.enter,
16: LogicalKeyboardKey.shiftLeft,
17: LogicalKeyboardKey.controlLeft,
19: LogicalKeyboardKey.pause,
20: LogicalKeyboardKey.capsLock,
21: LogicalKeyboardKey.lang1,
23: LogicalKeyboardKey.junjaMode,
24: LogicalKeyboardKey.finalMode,
25: LogicalKeyboardKey.kanjiMode,
27: LogicalKeyboardKey.escape,
28: LogicalKeyboardKey.convert,
30: LogicalKeyboardKey.accept,
31: LogicalKeyboardKey.modeChange,
32: LogicalKeyboardKey.space,
33: LogicalKeyboardKey.pageUp,
34: LogicalKeyboardKey.pageDown,
35: LogicalKeyboardKey.end,
36: LogicalKeyboardKey.home,
37: LogicalKeyboardKey.arrowLeft,
38: LogicalKeyboardKey.arrowUp,
39: LogicalKeyboardKey.arrowRight,
40: LogicalKeyboardKey.arrowDown,
41: LogicalKeyboardKey.select,
42: LogicalKeyboardKey.print,
43: LogicalKeyboardKey.execute,
44: LogicalKeyboardKey.printScreen,
45: LogicalKeyboardKey.insert,
46: LogicalKeyboardKey.delete,
47: LogicalKeyboardKey.help,
48: LogicalKeyboardKey.digit0,
49: LogicalKeyboardKey.digit1,
50: LogicalKeyboardKey.digit2,
51: LogicalKeyboardKey.digit3,
52: LogicalKeyboardKey.digit4,
53: LogicalKeyboardKey.digit5,
54: LogicalKeyboardKey.digit6,
55: LogicalKeyboardKey.digit7,
56: LogicalKeyboardKey.digit8,
57: LogicalKeyboardKey.digit9,
65: LogicalKeyboardKey.keyA,
66: LogicalKeyboardKey.keyB,
67: LogicalKeyboardKey.keyC,
68: LogicalKeyboardKey.keyD,
69: LogicalKeyboardKey.keyE,
70: LogicalKeyboardKey.keyF,
71: LogicalKeyboardKey.keyG,
72: LogicalKeyboardKey.keyH,
73: LogicalKeyboardKey.keyI,
74: LogicalKeyboardKey.keyJ,
75: LogicalKeyboardKey.keyK,
76: LogicalKeyboardKey.keyL,
77: LogicalKeyboardKey.keyM,
78: LogicalKeyboardKey.keyN,
79: LogicalKeyboardKey.keyO,
80: LogicalKeyboardKey.keyP,
81: LogicalKeyboardKey.keyQ,
82: LogicalKeyboardKey.keyR,
83: LogicalKeyboardKey.keyS,
84: LogicalKeyboardKey.keyT,
85: LogicalKeyboardKey.keyU,
86: LogicalKeyboardKey.keyV,
87: LogicalKeyboardKey.keyW,
88: LogicalKeyboardKey.keyX,
89: LogicalKeyboardKey.keyY,
90: LogicalKeyboardKey.keyZ,
91: LogicalKeyboardKey.metaLeft,
92: LogicalKeyboardKey.metaRight,
93: LogicalKeyboardKey.contextMenu,
95: LogicalKeyboardKey.sleep,
96: LogicalKeyboardKey.numpad0,
97: LogicalKeyboardKey.numpad1,
98: LogicalKeyboardKey.numpad2,
99: LogicalKeyboardKey.numpad3,
100: LogicalKeyboardKey.numpad4,
101: LogicalKeyboardKey.numpad5,
102: LogicalKeyboardKey.numpad6,
103: LogicalKeyboardKey.numpad7,
104: LogicalKeyboardKey.numpad8,
105: LogicalKeyboardKey.numpad9,
106: LogicalKeyboardKey.numpadMultiply,
107: LogicalKeyboardKey.numpadAdd,
108: LogicalKeyboardKey.numpadComma,
109: LogicalKeyboardKey.numpadSubtract,
110: LogicalKeyboardKey.numpadDecimal,
111: LogicalKeyboardKey.numpadDivide,
112: LogicalKeyboardKey.f1,
113: LogicalKeyboardKey.f2,
114: LogicalKeyboardKey.f3,
115: LogicalKeyboardKey.f4,
116: LogicalKeyboardKey.f5,
117: LogicalKeyboardKey.f6,
118: LogicalKeyboardKey.f7,
119: LogicalKeyboardKey.f8,
120: LogicalKeyboardKey.f9,
121: LogicalKeyboardKey.f10,
122: LogicalKeyboardKey.f11,
123: LogicalKeyboardKey.f12,
124: LogicalKeyboardKey.f13,
125: LogicalKeyboardKey.f14,
126: LogicalKeyboardKey.f15,
127: LogicalKeyboardKey.f16,
128: LogicalKeyboardKey.f17,
129: LogicalKeyboardKey.f18,
130: LogicalKeyboardKey.f19,
131: LogicalKeyboardKey.f20,
132: LogicalKeyboardKey.f21,
133: LogicalKeyboardKey.f22,
134: LogicalKeyboardKey.f23,
135: LogicalKeyboardKey.f24,
144: LogicalKeyboardKey.numLock,
145: LogicalKeyboardKey.scrollLock,
146: LogicalKeyboardKey.numpadEqual,
160: LogicalKeyboardKey.shiftLeft,
161: LogicalKeyboardKey.shiftRight,
162: LogicalKeyboardKey.controlLeft,
163: LogicalKeyboardKey.controlRight,
164: LogicalKeyboardKey.altLeft,
165: LogicalKeyboardKey.altRight,
166: LogicalKeyboardKey.browserBack,
167: LogicalKeyboardKey.browserForward,
168: LogicalKeyboardKey.browserRefresh,
169: LogicalKeyboardKey.browserStop,
170: LogicalKeyboardKey.browserSearch,
171: LogicalKeyboardKey.browserFavorites,
172: LogicalKeyboardKey.browserHome,
173: LogicalKeyboardKey.audioVolumeMute,
174: LogicalKeyboardKey.audioVolumeDown,
175: LogicalKeyboardKey.audioVolumeUp,
178: LogicalKeyboardKey.mediaStop,
179: LogicalKeyboardKey.mediaPlayPause,
180: LogicalKeyboardKey.launchMail,
186: LogicalKeyboardKey.semicolon,
187: LogicalKeyboardKey.equal,
188: LogicalKeyboardKey.comma,
189: LogicalKeyboardKey.minus,
190: LogicalKeyboardKey.period,
191: LogicalKeyboardKey.slash,
192: LogicalKeyboardKey.backquote,
195: LogicalKeyboardKey.gameButton8,
196: LogicalKeyboardKey.gameButton9,
197: LogicalKeyboardKey.gameButton10,
198: LogicalKeyboardKey.gameButton11,
199: LogicalKeyboardKey.gameButton12,
200: LogicalKeyboardKey.gameButton13,
201: LogicalKeyboardKey.gameButton14,
202: LogicalKeyboardKey.gameButton15,
203: LogicalKeyboardKey.gameButton16,
219: LogicalKeyboardKey.bracketLeft,
220: LogicalKeyboardKey.backslash,
221: LogicalKeyboardKey.bracketRight,
222: LogicalKeyboardKey.quote,
246: LogicalKeyboardKey.attn,
250: LogicalKeyboardKey.play,
};
/// Maps Windows KeyboardEvent codes to the matching [PhysicalKeyboardKey].
const Map<int, PhysicalKeyboardKey> kWindowsToPhysicalKey = <int, PhysicalKeyboardKey>{
1: PhysicalKeyboardKey.escape,
2: PhysicalKeyboardKey.digit1,
3: PhysicalKeyboardKey.digit2,
4: PhysicalKeyboardKey.digit3,
5: PhysicalKeyboardKey.digit4,
6: PhysicalKeyboardKey.digit5,
7: PhysicalKeyboardKey.digit6,
8: PhysicalKeyboardKey.digit7,
9: PhysicalKeyboardKey.digit8,
10: PhysicalKeyboardKey.digit9,
11: PhysicalKeyboardKey.digit0,
12: PhysicalKeyboardKey.minus,
13: PhysicalKeyboardKey.equal,
14: PhysicalKeyboardKey.backspace,
15: PhysicalKeyboardKey.tab,
16: PhysicalKeyboardKey.keyQ,
17: PhysicalKeyboardKey.keyW,
18: PhysicalKeyboardKey.keyE,
19: PhysicalKeyboardKey.keyR,
20: PhysicalKeyboardKey.keyT,
21: PhysicalKeyboardKey.keyY,
22: PhysicalKeyboardKey.keyU,
23: PhysicalKeyboardKey.keyI,
24: PhysicalKeyboardKey.keyO,
25: PhysicalKeyboardKey.keyP,
26: PhysicalKeyboardKey.bracketLeft,
27: PhysicalKeyboardKey.bracketRight,
28: PhysicalKeyboardKey.enter,
29: PhysicalKeyboardKey.controlLeft,
30: PhysicalKeyboardKey.keyA,
31: PhysicalKeyboardKey.keyS,
32: PhysicalKeyboardKey.keyD,
33: PhysicalKeyboardKey.keyF,
34: PhysicalKeyboardKey.keyG,
35: PhysicalKeyboardKey.keyH,
36: PhysicalKeyboardKey.keyJ,
37: PhysicalKeyboardKey.keyK,
38: PhysicalKeyboardKey.keyL,
39: PhysicalKeyboardKey.semicolon,
40: PhysicalKeyboardKey.quote,
41: PhysicalKeyboardKey.backquote,
42: PhysicalKeyboardKey.shiftLeft,
43: PhysicalKeyboardKey.backslash,
44: PhysicalKeyboardKey.keyZ,
45: PhysicalKeyboardKey.keyX,
46: PhysicalKeyboardKey.keyC,
47: PhysicalKeyboardKey.keyV,
48: PhysicalKeyboardKey.keyB,
49: PhysicalKeyboardKey.keyN,
50: PhysicalKeyboardKey.keyM,
51: PhysicalKeyboardKey.comma,
52: PhysicalKeyboardKey.period,
53: PhysicalKeyboardKey.slash,
54: PhysicalKeyboardKey.shiftRight,
55: PhysicalKeyboardKey.numpadMultiply,
56: PhysicalKeyboardKey.altLeft,
57: PhysicalKeyboardKey.space,
58: PhysicalKeyboardKey.capsLock,
59: PhysicalKeyboardKey.f1,
60: PhysicalKeyboardKey.f2,
61: PhysicalKeyboardKey.f3,
62: PhysicalKeyboardKey.f4,
63: PhysicalKeyboardKey.f5,
64: PhysicalKeyboardKey.f6,
65: PhysicalKeyboardKey.f7,
66: PhysicalKeyboardKey.f8,
67: PhysicalKeyboardKey.f9,
68: PhysicalKeyboardKey.f10,
69: PhysicalKeyboardKey.pause,
70: PhysicalKeyboardKey.scrollLock,
71: PhysicalKeyboardKey.numpad7,
72: PhysicalKeyboardKey.numpad8,
73: PhysicalKeyboardKey.numpad9,
74: PhysicalKeyboardKey.numpadSubtract,
75: PhysicalKeyboardKey.numpad4,
76: PhysicalKeyboardKey.numpad5,
77: PhysicalKeyboardKey.numpad6,
78: PhysicalKeyboardKey.numpadAdd,
79: PhysicalKeyboardKey.numpad1,
80: PhysicalKeyboardKey.numpad2,
81: PhysicalKeyboardKey.numpad3,
82: PhysicalKeyboardKey.numpad0,
83: PhysicalKeyboardKey.numpadDecimal,
86: PhysicalKeyboardKey.intlBackslash,
87: PhysicalKeyboardKey.f11,
88: PhysicalKeyboardKey.f12,
89: PhysicalKeyboardKey.numpadEqual,
100: PhysicalKeyboardKey.f13,
101: PhysicalKeyboardKey.f14,
102: PhysicalKeyboardKey.f15,
103: PhysicalKeyboardKey.f16,
104: PhysicalKeyboardKey.f17,
105: PhysicalKeyboardKey.f18,
106: PhysicalKeyboardKey.f19,
107: PhysicalKeyboardKey.f20,
108: PhysicalKeyboardKey.f21,
109: PhysicalKeyboardKey.f22,
110: PhysicalKeyboardKey.f23,
112: PhysicalKeyboardKey.kanaMode,
113: PhysicalKeyboardKey.lang2,
114: PhysicalKeyboardKey.lang1,
115: PhysicalKeyboardKey.intlRo,
118: PhysicalKeyboardKey.f24,
119: PhysicalKeyboardKey.lang4,
120: PhysicalKeyboardKey.lang3,
121: PhysicalKeyboardKey.convert,
123: PhysicalKeyboardKey.nonConvert,
125: PhysicalKeyboardKey.intlYen,
126: PhysicalKeyboardKey.numpadComma,
252: PhysicalKeyboardKey.usbPostFail,
255: PhysicalKeyboardKey.usbErrorRollOver,
57352: PhysicalKeyboardKey.undo,
57354: PhysicalKeyboardKey.paste,
57360: PhysicalKeyboardKey.mediaTrackPrevious,
57367: PhysicalKeyboardKey.cut,
57368: PhysicalKeyboardKey.copy,
57369: PhysicalKeyboardKey.mediaTrackNext,
57372: PhysicalKeyboardKey.numpadEnter,
57373: PhysicalKeyboardKey.controlRight,
57376: PhysicalKeyboardKey.audioVolumeMute,
57377: PhysicalKeyboardKey.launchApp2,
57378: PhysicalKeyboardKey.mediaPlayPause,
57380: PhysicalKeyboardKey.mediaStop,
57388: PhysicalKeyboardKey.eject,
57390: PhysicalKeyboardKey.audioVolumeDown,
57392: PhysicalKeyboardKey.audioVolumeUp,
57394: PhysicalKeyboardKey.browserHome,
57397: PhysicalKeyboardKey.numpadDivide,
57399: PhysicalKeyboardKey.printScreen,
57400: PhysicalKeyboardKey.altRight,
57403: PhysicalKeyboardKey.help,
57413: PhysicalKeyboardKey.numLock,
57415: PhysicalKeyboardKey.home,
57416: PhysicalKeyboardKey.arrowUp,
57417: PhysicalKeyboardKey.pageUp,
57419: PhysicalKeyboardKey.arrowLeft,
57421: PhysicalKeyboardKey.arrowRight,
57423: PhysicalKeyboardKey.end,
57424: PhysicalKeyboardKey.arrowDown,
57425: PhysicalKeyboardKey.pageDown,
57426: PhysicalKeyboardKey.insert,
57427: PhysicalKeyboardKey.delete,
57435: PhysicalKeyboardKey.metaLeft,
57436: PhysicalKeyboardKey.metaRight,
57437: PhysicalKeyboardKey.contextMenu,
57438: PhysicalKeyboardKey.power,
57439: PhysicalKeyboardKey.sleep,
57443: PhysicalKeyboardKey.wakeUp,
57445: PhysicalKeyboardKey.browserSearch,
57446: PhysicalKeyboardKey.browserFavorites,
57447: PhysicalKeyboardKey.browserRefresh,
57448: PhysicalKeyboardKey.browserStop,
57449: PhysicalKeyboardKey.browserForward,
57450: PhysicalKeyboardKey.browserBack,
57451: PhysicalKeyboardKey.launchApp1,
57452: PhysicalKeyboardKey.launchMail,
57453: PhysicalKeyboardKey.mediaSelect,
};
/// A map of Windows KeyboardEvent codes which have printable representations, but appear
/// on the number pad. Used to provide different key objects for keys like
/// KEY_EQUALS and NUMPAD_EQUALS.
const Map<int, LogicalKeyboardKey> kWindowsNumPadMap = <int, LogicalKeyboardKey>{
96: LogicalKeyboardKey.numpad0,
97: LogicalKeyboardKey.numpad1,
98: LogicalKeyboardKey.numpad2,
99: LogicalKeyboardKey.numpad3,
100: LogicalKeyboardKey.numpad4,
101: LogicalKeyboardKey.numpad5,
102: LogicalKeyboardKey.numpad6,
103: LogicalKeyboardKey.numpad7,
104: LogicalKeyboardKey.numpad8,
105: LogicalKeyboardKey.numpad9,
106: LogicalKeyboardKey.numpadMultiply,
107: LogicalKeyboardKey.numpadAdd,
108: LogicalKeyboardKey.numpadComma,
109: LogicalKeyboardKey.numpadSubtract,
110: LogicalKeyboardKey.numpadDecimal,
111: LogicalKeyboardKey.numpadDivide,
146: LogicalKeyboardKey.numpadEqual,
};
| flutter/packages/flutter/lib/src/services/keyboard_maps.g.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/keyboard_maps.g.dart",
"repo_id": "flutter",
"token_count": 48168
} | 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 '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;
// Virtual key VK_PROCESSKEY in Win32 API.
//
// Key down events related to IME operations use this as keyCode.
const int _vkProcessKey = 0xe5;
/// Platform-specific key event data for Windows.
///
/// This class is DEPRECATED. Platform specific key event data will no longer
/// available. See [KeyEvent] for what is available.
///
/// This object contains information about key events obtained from Windows's
/// win32 API.
///
/// 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 RawKeyEventDataWindows extends RawKeyEventData {
/// Creates a key event data structure specific for Windows.
@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 RawKeyEventDataWindows({
this.keyCode = 0,
this.scanCode = 0,
this.characterCodePoint = 0,
this.modifiers = 0,
});
/// The hardware key code corresponding to this key event.
///
/// This is the physical key that was pressed, not the Unicode character.
/// See [characterCodePoint] for the Unicode character.
final int keyCode;
/// The hardware scan code id corresponding to this key event.
///
/// These values are not reliable and vary from device to device, so this
/// information is mainly useful for debugging.
final int scanCode;
/// The Unicode code point represented by the key event, if any.
///
/// If there is no Unicode code point, this value is zero.
final int characterCodePoint;
/// A mask of the current modifiers. The modifier values must be in sync with
/// the Windows embedder. See:
/// https://github.com/flutter/engine/blob/7667c8a12ce6bc2d8dd538845add0a4e1a575bfd/shell/platform/windows/keyboard_key_channel_handler.cc#L44
final int modifiers;
@override
String get keyLabel => characterCodePoint == 0 ? '' : String.fromCharCode(characterCodePoint);
@override
PhysicalKeyboardKey get physicalKey => kWindowsToPhysicalKey[scanCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.windowsPlane + scanCode);
@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 = kWindowsNumPadMap[keyCode];
if (numPadKey != null) {
return numPadKey;
}
// If it has a non-control-character label, then either return the existing
// constant, or construct a new Unicode-based key from it. Don't mark it as
// autogenerated, since the label uniquely identifies an ID from the Unicode
// plane.
if (keyLabel.isNotEmpty && !LogicalKeyboardKey.isControlCharacter(keyLabel)) {
final int keyId = LogicalKeyboardKey.unicodePlane | (characterCodePoint & LogicalKeyboardKey.valueMask);
return LogicalKeyboardKey.findKeyByKeyId(keyId) ?? LogicalKeyboardKey(keyId);
}
// Look to see if the keyCode is one we know about and have a mapping for.
final LogicalKeyboardKey? newKey = kWindowsToLogicalKey[keyCode];
if (newKey != null) {
return newKey;
}
// This is a non-printable key that we don't know about, so we mint a new
// code.
return LogicalKeyboardKey(keyCode | LogicalKeyboardKey.windowsPlane);
}
bool _isLeftRightModifierPressed(KeyboardSide side, int anyMask, int leftMask, int rightMask) {
if (modifiers & (leftMask | rightMask | 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 Windows
// 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 bool result;
switch (key) {
case ModifierKey.controlModifier:
result = _isLeftRightModifierPressed(side, modifierControl, modifierLeftControl, modifierRightControl);
case ModifierKey.shiftModifier:
result = _isLeftRightModifierPressed(side, modifierShift, modifierLeftShift, modifierRightShift);
case ModifierKey.altModifier:
result = _isLeftRightModifierPressed(side, modifierAlt, modifierLeftAlt, modifierRightAlt);
case ModifierKey.metaModifier:
// Windows does not provide an "any" key for win key press.
result = _isLeftRightModifierPressed(side, modifierLeftMeta | modifierRightMeta , modifierLeftMeta, modifierRightMeta);
case ModifierKey.capsLockModifier:
result = modifiers & modifierCaps != 0;
case ModifierKey.scrollLockModifier:
result = modifiers & modifierScrollLock != 0;
case ModifierKey.numLockModifier:
result = modifiers & modifierNumLock != 0;
// The OS does not expose the Fn key to the drivers, it doesn't generate a key message.
case ModifierKey.functionModifier:
case ModifierKey.symbolModifier:
// These modifier masks are not used in Windows 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 leftMask, int rightMask, int anyMask) {
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 Windows supplies just the "either" modifier
// flag, but not the left/right flag. (e.g. modifierShift but not
// modifierLeftShift).
return KeyboardSide.all;
}
return null;
}
switch (key) {
case ModifierKey.controlModifier:
return findSide(modifierLeftControl, modifierRightControl, modifierControl);
case ModifierKey.shiftModifier:
return findSide(modifierLeftShift, modifierRightShift, modifierShift);
case ModifierKey.altModifier:
return findSide(modifierLeftAlt, modifierRightAlt, modifierAlt);
case ModifierKey.metaModifier:
return findSide(modifierLeftMeta, modifierRightMeta, 0);
case ModifierKey.capsLockModifier:
case ModifierKey.numLockModifier:
case ModifierKey.scrollLockModifier:
case ModifierKey.functionModifier:
case ModifierKey.symbolModifier:
return KeyboardSide.all;
}
}
@override
bool shouldDispatchEvent() {
// In Win32 API, down events related to IME operations use VK_PROCESSKEY as
// keyCode. This event, as well as the following key up event (which uses a
// normal keyCode), should be skipped, because the effect of IME operations
// will be handled by the text input API.
return keyCode != _vkProcessKey;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<int>('keyCode', keyCode));
properties.add(DiagnosticsProperty<int>('scanCode', scanCode));
properties.add(DiagnosticsProperty<int>('characterCodePoint', characterCodePoint));
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 RawKeyEventDataWindows
&& other.keyCode == keyCode
&& other.scanCode == scanCode
&& other.characterCodePoint == characterCodePoint
&& other.modifiers == modifiers;
}
@override
int get hashCode => Object.hash(
keyCode,
scanCode,
characterCodePoint,
modifiers,
);
// These are not the values defined by the Windows header for each modifier. Since they
// can't be packaged into a single int, we are re-defining them here to reduce the size
// of the message from the embedder. Embedders should map these values to the native key codes.
// Keep this in sync with https://github.com/flutter/engine/blob/master/shell/platform/windows/key_event_handler.cc
/// This mask is used to check the [modifiers] field to test whether one of the
/// SHIFT modifier keys is pressed.
///
/// {@template flutter.services.RawKeyEventDataWindows.modifierShift}
/// 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 modifierShift = 1 << 0;
/// This mask is used to check the [modifiers] field to test whether the left
/// SHIFT modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierLeftShift = 1 << 1;
/// This mask is used to check the [modifiers] field to test whether the right
/// SHIFT modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierRightShift = 1 << 2;
/// This mask is used to check the [modifiers] field to test whether one of the
/// CTRL modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierControl = 1 << 3;
/// This mask is used to check the [modifiers] field to test whether the left
/// CTRL modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierLeftControl = 1 << 4;
/// This mask is used to check the [modifiers] field to test whether the right
/// CTRL modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierRightControl = 1 << 5;
/// This mask is used to check the [modifiers] field to test whether one of the
/// ALT modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierAlt = 1 << 6;
/// This mask is used to check the [modifiers] field to test whether the left
/// ALT modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierLeftAlt = 1 << 7;
/// This mask is used to check the [modifiers] field to test whether the right
/// ALT modifier key is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierRightAlt = 1 << 8;
/// This mask is used to check the [modifiers] field to test whether the left
/// WIN modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierLeftMeta = 1 << 9;
/// This mask is used to check the [modifiers] field to test whether the right
/// WIN modifier keys is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierRightMeta = 1 << 10;
/// This mask is used to check the [modifiers] field to test whether the CAPS LOCK key
/// is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierCaps = 1 << 11;
/// This mask is used to check the [modifiers] field to test whether the NUM LOCK key
/// is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierNumLock = 1 << 12;
/// This mask is used to check the [modifiers] field to test whether the SCROLL LOCK key
/// is pressed.
///
/// {@macro flutter.services.RawKeyEventDataWindows.modifierShift}
static const int modifierScrollLock = 1 << 13;
}
| flutter/packages/flutter/lib/src/services/raw_keyboard_windows.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/raw_keyboard_windows.dart",
"repo_id": "flutter",
"token_count": 4103
} | 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 'framework.dart';
import 'platform_view.dart';
/// The platform-specific implementation of [HtmlElementView].
extension HtmlElementViewImpl on HtmlElementView {
/// Creates an [HtmlElementView] that renders a DOM element with the given
/// [tagName].
static HtmlElementView createFromTagName({
Key? key,
required String tagName,
bool isVisible = true,
ElementCreatedCallback? onElementCreated,
}) {
throw UnimplementedError('HtmlElementView is only available on Flutter Web');
}
/// Called from [HtmlElementView.build] to build the widget tree.
///
/// This is not expected to be invoked in non-web environments. It throws if
/// that happens.
///
/// The implementation on Flutter Web builds a platform view and handles its
/// lifecycle.
Widget buildImpl(BuildContext context) {
throw UnimplementedError('HtmlElementView is only available on Flutter Web');
}
}
| flutter/packages/flutter/lib/src/widgets/_html_element_view_io.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/_html_element_view_io.dart",
"repo_id": "flutter",
"token_count": 310
} | 649 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'framework.dart';
import 'notification_listener.dart';
import 'sliver.dart';
/// Allows subtrees to request to be kept alive in lazy lists.
///
/// This widget is like [KeepAlive] but instead of being explicitly configured,
/// it listens to [KeepAliveNotification] messages from the [child] and other
/// descendants.
///
/// The subtree is kept alive whenever there is one or more descendant that has
/// sent a [KeepAliveNotification] and not yet triggered its
/// [KeepAliveNotification.handle].
///
/// To send these notifications, consider using [AutomaticKeepAliveClientMixin].
class AutomaticKeepAlive extends StatefulWidget {
/// Creates a widget that listens to [KeepAliveNotification]s and maintains a
/// [KeepAlive] widget appropriately.
const AutomaticKeepAlive({
super.key,
required this.child,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
State<AutomaticKeepAlive> createState() => _AutomaticKeepAliveState();
}
class _AutomaticKeepAliveState extends State<AutomaticKeepAlive> {
Map<Listenable, VoidCallback>? _handles;
// In order to apply parent data out of turn, the child of the KeepAlive
// widget must be the same across frames.
late Widget _child;
bool _keepingAlive = false;
@override
void initState() {
super.initState();
_updateChild();
}
@override
void didUpdateWidget(AutomaticKeepAlive oldWidget) {
super.didUpdateWidget(oldWidget);
_updateChild();
}
void _updateChild() {
_child = NotificationListener<KeepAliveNotification>(
onNotification: _addClient,
child: widget.child,
);
}
@override
void dispose() {
if (_handles != null) {
for (final Listenable handle in _handles!.keys) {
handle.removeListener(_handles![handle]!);
}
}
super.dispose();
}
bool _addClient(KeepAliveNotification notification) {
final Listenable handle = notification.handle;
_handles ??= <Listenable, VoidCallback>{};
assert(!_handles!.containsKey(handle));
_handles![handle] = _createCallback(handle);
handle.addListener(_handles![handle]!);
if (!_keepingAlive) {
_keepingAlive = true;
final ParentDataElement<KeepAliveParentDataMixin>? childElement = _getChildElement();
if (childElement != null) {
// If the child already exists, update it synchronously.
_updateParentDataOfChild(childElement);
} else {
// If the child doesn't exist yet, we got called during the very first
// build of this subtree. Wait until the end of the frame to update
// the child when the child is guaranteed to be present.
SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
if (!mounted) {
return;
}
final ParentDataElement<KeepAliveParentDataMixin>? childElement = _getChildElement();
assert(childElement != null);
_updateParentDataOfChild(childElement!);
}, debugLabel: 'AutomaticKeepAlive.updateParentData');
}
}
return false;
}
/// Get the [Element] for the only [KeepAlive] child.
///
/// While this widget is guaranteed to have a child, this may return null if
/// the first build of that child has not completed yet.
ParentDataElement<KeepAliveParentDataMixin>? _getChildElement() {
assert(mounted);
final Element element = context as Element;
Element? childElement;
// We use Element.visitChildren rather than context.visitChildElements
// because we might be called during build, and context.visitChildElements
// verifies that it is not called during build. Element.visitChildren does
// not, instead it assumes that the caller will be careful. (See the
// documentation for these methods for more details.)
//
// Here we know it's safe (with the exception outlined below) because we
// just received a notification, which we wouldn't be able to do if we
// hadn't built our child and its child -- our build method always builds
// the same subtree and it always includes the node we're looking for
// (KeepAlive) as the parent of the node that reports the notifications
// (NotificationListener).
//
// If we are called during the first build of this subtree the links to the
// children will not be hooked up yet. In that case this method returns
// null despite the fact that we will have a child after the build
// completes. It's the caller's responsibility to deal with this case.
//
// (We're only going down one level, to get our direct child.)
element.visitChildren((Element child) {
childElement = child;
});
assert(childElement == null || childElement is ParentDataElement<KeepAliveParentDataMixin>);
return childElement as ParentDataElement<KeepAliveParentDataMixin>?;
}
void _updateParentDataOfChild(ParentDataElement<KeepAliveParentDataMixin> childElement) {
childElement.applyWidgetOutOfTurn(build(context) as ParentDataWidget<KeepAliveParentDataMixin>);
}
VoidCallback _createCallback(Listenable handle) {
late final VoidCallback callback;
return callback = () {
assert(() {
if (!mounted) {
throw FlutterError(
'AutomaticKeepAlive handle triggered after AutomaticKeepAlive was disposed.\n'
'Widgets should always trigger their KeepAliveNotification handle when they are '
'deactivated, so that they (or their handle) do not send spurious events later '
'when they are no longer in the tree.',
);
}
return true;
}());
_handles!.remove(handle);
handle.removeListener(callback);
if (_handles!.isEmpty) {
if (SchedulerBinding.instance.schedulerPhase.index < SchedulerPhase.persistentCallbacks.index) {
// Build/layout haven't started yet so let's just schedule this for
// the next frame.
setState(() { _keepingAlive = false; });
} else {
// We were probably notified by a descendant when they were yanked out
// of our subtree somehow. We're probably in the middle of build or
// layout, so there's really nothing we can do to clean up this mess
// short of just scheduling another build to do the cleanup. This is
// very unfortunate, and means (for instance) that garbage collection
// of these resources won't happen for another 16ms.
//
// The problem is there's really no way for us to distinguish these
// cases:
//
// * We haven't built yet (or missed out chance to build), but
// someone above us notified our descendant and our descendant is
// disconnecting from us. If we could mark ourselves dirty we would
// be able to clean everything this frame. (This is a pretty
// unlikely scenario in practice. Usually things change before
// build/layout, not during build/layout.)
//
// * Our child changed, and as our old child went away, it notified
// us. We can't setState, since we _just_ built. We can't apply the
// parent data information to our child because we don't _have_ a
// child at this instant. We really want to be able to change our
// mind about how we built, so we can give the KeepAlive widget a
// new value, but it's too late.
//
// * A deep descendant in another build scope just got yanked, and in
// the process notified us. We could apply new parent data
// information, but it may or may not get applied this frame,
// depending on whether said child is in the same layout scope.
//
// * A descendant is being moved from one position under us to
// another position under us. They just notified us of the removal,
// at some point in the future they will notify us of the addition.
// We don't want to do anything. (This is why we check that
// _handles is still empty below.)
//
// * We're being notified in the paint phase, or even in a post-frame
// callback. Either way it is far too late for us to make our
// parent lay out again this frame, so the garbage won't get
// collected this frame.
//
// * We are being torn out of the tree ourselves, as is our
// descendant, and it notified us while it was being deactivated.
// We don't need to do anything, but we don't know yet because we
// haven't been deactivated yet. (This is why we check mounted
// below before calling setState.)
//
// Long story short, we have to schedule a new frame and request a
// frame there, but this is generally a bad practice, and you should
// avoid it if possible.
_keepingAlive = false;
scheduleMicrotask(() {
if (mounted && _handles!.isEmpty) {
// If mounted is false, we went away as well, so there's nothing to do.
// If _handles is no longer empty, then another client (or the same
// client in a new place) registered itself before we had a chance to
// turn off keepalive, so again there's nothing to do.
setState(() {
assert(!_keepingAlive);
});
}
});
}
}
};
}
@override
Widget build(BuildContext context) {
return KeepAlive(
keepAlive: _keepingAlive,
child: _child,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder description) {
super.debugFillProperties(description);
description.add(FlagProperty('_keepingAlive', value: _keepingAlive, ifTrue: 'keeping subtree alive'));
description.add(DiagnosticsProperty<Map<Listenable, VoidCallback>>(
'handles',
_handles,
description: _handles != null ?
'${_handles!.length} active client${ _handles!.length == 1 ? "" : "s" }' :
null,
ifNull: 'no notifications ever received',
));
}
}
/// Indicates that the subtree through which this notification bubbles must be
/// kept alive even if it would normally be discarded as an optimization.
///
/// For example, a focused text field might fire this notification to indicate
/// that it should not be disposed even if the user scrolls the field off
/// screen.
///
/// Each [KeepAliveNotification] is configured with a [handle] that consists of
/// a [Listenable] that is triggered when the subtree no longer needs to be kept
/// alive.
///
/// The [handle] should be triggered any time the sending widget is removed from
/// the tree (in [State.deactivate]). If the widget is then rebuilt and still
/// needs to be kept alive, it should immediately send a new notification
/// (possible with the very same [Listenable]) during build.
///
/// This notification is listened to by the [AutomaticKeepAlive] widget, which
/// is added to the tree automatically by [SliverList] (and [ListView]) and
/// [SliverGrid] (and [GridView]) widgets.
///
/// Failure to trigger the [handle] in the manner described above will likely
/// cause the [AutomaticKeepAlive] to lose track of whether the widget should be
/// kept alive or not, leading to memory leaks or lost data. For example, if the
/// widget that requested keepalive is removed from the subtree but doesn't
/// trigger its [Listenable] on the way out, then the subtree will continue to
/// be kept alive until the list itself is disposed. Similarly, if the
/// [Listenable] is triggered while the widget needs to be kept alive, but a new
/// [KeepAliveNotification] is not immediately sent, then the widget risks being
/// garbage collected while it wants to be kept alive.
///
/// It is an error to use the same [handle] in two [KeepAliveNotification]s
/// within the same [AutomaticKeepAlive] without triggering that [handle] before
/// the second notification is sent.
///
/// For a more convenient way to interact with [AutomaticKeepAlive] widgets,
/// consider using [AutomaticKeepAliveClientMixin], which uses
/// [KeepAliveNotification] internally.
class KeepAliveNotification extends Notification {
/// Creates a notification to indicate that a subtree must be kept alive.
const KeepAliveNotification(this.handle);
/// A [Listenable] that will inform its clients when the widget that fired the
/// notification no longer needs to be kept alive.
///
/// The [Listenable] should be triggered any time the sending widget is
/// removed from the tree (in [State.deactivate]). If the widget is then
/// rebuilt and still needs to be kept alive, it should immediately send a new
/// notification (possible with the very same [Listenable]) during build.
///
/// See also:
///
/// * [KeepAliveHandle], a convenience class for use with this property.
final Listenable handle;
}
/// A [Listenable] which can be manually triggered.
///
/// Used with [KeepAliveNotification] objects as their
/// [KeepAliveNotification.handle].
///
/// For a more convenient way to interact with [AutomaticKeepAlive] widgets,
/// consider using [AutomaticKeepAliveClientMixin], which uses a
/// [KeepAliveHandle] internally.
class KeepAliveHandle extends ChangeNotifier {
@override
void dispose() {
notifyListeners();
super.dispose();
}
}
/// A mixin with convenience methods for clients of [AutomaticKeepAlive]. Used
/// with [State] subclasses.
///
/// Subclasses must implement [wantKeepAlive], and their [build] methods must
/// call `super.build` (though the return value should be ignored).
///
/// Then, whenever [wantKeepAlive]'s value changes (or might change), the
/// subclass should call [updateKeepAlive].
///
/// The type argument `T` is the type of the [StatefulWidget] subclass of the
/// [State] into which this class is being mixed.
///
/// See also:
///
/// * [AutomaticKeepAlive], which listens to messages from this mixin.
/// * [KeepAliveNotification], the notifications sent by this mixin.
@optionalTypeArgs
mixin AutomaticKeepAliveClientMixin<T extends StatefulWidget> on State<T> {
KeepAliveHandle? _keepAliveHandle;
void _ensureKeepAlive() {
assert(_keepAliveHandle == null);
_keepAliveHandle = KeepAliveHandle();
KeepAliveNotification(_keepAliveHandle!).dispatch(context);
}
void _releaseKeepAlive() {
_keepAliveHandle!.dispose();
_keepAliveHandle = null;
}
/// Whether the current instance should be kept alive.
///
/// Call [updateKeepAlive] whenever this getter's value changes.
@protected
bool get wantKeepAlive;
/// Ensures that any [AutomaticKeepAlive] ancestors are in a good state, by
/// firing a [KeepAliveNotification] or triggering the [KeepAliveHandle] as
/// appropriate.
@protected
void updateKeepAlive() {
if (wantKeepAlive) {
if (_keepAliveHandle == null) {
_ensureKeepAlive();
}
} else {
if (_keepAliveHandle != null) {
_releaseKeepAlive();
}
}
}
@override
void initState() {
super.initState();
if (wantKeepAlive) {
_ensureKeepAlive();
}
}
@override
void deactivate() {
if (_keepAliveHandle != null) {
_releaseKeepAlive();
}
super.deactivate();
}
@mustCallSuper
@override
Widget build(BuildContext context) {
if (wantKeepAlive && _keepAliveHandle == null) {
_ensureKeepAlive();
}
return const _NullWidget();
}
}
class _NullWidget extends StatelessWidget {
const _NullWidget();
@override
Widget build(BuildContext context) {
throw FlutterError(
'Widgets that mix AutomaticKeepAliveClientMixin into their State must '
'call super.build() but must ignore the return value of the superclass.',
);
}
}
| flutter/packages/flutter/lib/src/widgets/automatic_keep_alive.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/automatic_keep_alive.dart",
"repo_id": "flutter",
"token_count": 5407
} | 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 'dart:ui' show DisplayFeature, DisplayFeatureState;
import 'basic.dart';
import 'debug.dart';
import 'framework.dart';
import 'media_query.dart';
/// Positions [child] such that it avoids overlapping any [DisplayFeature] that
/// splits the screen into sub-screens.
///
/// A [DisplayFeature] splits the screen into sub-screens when both these
/// conditions are met:
///
/// * it obstructs the screen, meaning the area it occupies is not 0 or the
/// `state` is [DisplayFeatureState.postureHalfOpened].
/// * it is at least as tall as the screen, producing a left and right
/// sub-screen or it is at least as wide as the screen, producing a top and
/// bottom sub-screen
///
/// After determining the 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.
///
/// Similarly to [SafeArea], this widget assumes there is no added padding
/// between it and the first [MediaQuery] ancestor. The [child] is wrapped in a
/// new [MediaQuery] instance containing the [DisplayFeature]s that exist in the
/// selected sub-screen, with coordinates relative to the sub-screen. Padding is
/// also adjusted to zero out any sides that were avoided by this widget.
///
/// See also:
///
/// * [showDialog], which is a way to display a [DialogRoute].
/// * [showCupertinoDialog], which displays an iOS-style dialog.
class DisplayFeatureSubScreen extends StatelessWidget {
/// Creates a widget that positions its child so that it avoids display
/// features.
const DisplayFeatureSubScreen({
super.key,
this.anchorPoint,
required this.child,
});
/// {@template flutter.widgets.DisplayFeatureSubScreen.anchorPoint}
/// The anchor point used to pick the closest sub-screen.
///
/// If the anchor point sits inside one of these sub-screens, then that
/// sub-screen is picked. If not, then the sub-screen with the closest edge to
/// the point is used.
///
/// [Offset.zero] is the top-left corner of the available screen space. For a
/// vertically split dual-screen device, this is the top-left corner of the
/// left screen.
///
/// When this is null, [Directionality] is used:
///
/// * for [TextDirection.ltr], [anchorPoint] is [Offset.zero], which will
/// cause the top-left sub-screen to be picked.
/// * for [TextDirection.rtl], [anchorPoint] is
/// `Offset(double.maxFinite, 0)`, which will cause the top-right
/// sub-screen to be picked.
/// {@endtemplate}
final Offset? anchorPoint;
/// The widget below this widget in the tree.
///
/// The padding on the [MediaQuery] for the [child] will be suitably adjusted
/// to zero out any sides that were avoided by this widget. The [MediaQuery]
/// for the [child] will no longer contain any display features that split the
/// screen into sub-screens.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
Widget build(BuildContext context) {
assert(anchorPoint != null || debugCheckHasDirectionality(
context,
why: 'to determine which sub-screen DisplayFeatureSubScreen uses',
alternative: "Alternatively, consider specifying the 'anchorPoint' argument on the DisplayFeatureSubScreen.",
));
final MediaQueryData mediaQuery = MediaQuery.of(context);
final Size parentSize = mediaQuery.size;
final Rect wantedBounds = Offset.zero & parentSize;
final Offset resolvedAnchorPoint = _capOffset(anchorPoint ?? _fallbackAnchorPoint(context), parentSize);
final Iterable<Rect> subScreens = subScreensInBounds(wantedBounds, avoidBounds(mediaQuery));
final Rect closestSubScreen = _closestToAnchorPoint(subScreens, resolvedAnchorPoint);
return Padding(
padding: EdgeInsets.only(
left: closestSubScreen.left,
top: closestSubScreen.top,
right: parentSize.width - closestSubScreen.right,
bottom: parentSize.height - closestSubScreen.bottom,
),
child: MediaQuery(
data: mediaQuery.removeDisplayFeatures(closestSubScreen),
child: child,
),
);
}
static Offset _fallbackAnchorPoint(BuildContext context) {
return switch (Directionality.of(context)) {
TextDirection.rtl => const Offset(double.maxFinite, 0),
TextDirection.ltr => Offset.zero,
};
}
/// Returns the areas of the screen that are obstructed by display features.
///
/// A [DisplayFeature] obstructs the screen when the area it occupies is
/// not 0 or the `state` is [DisplayFeatureState.postureHalfOpened].
static Iterable<Rect> avoidBounds(MediaQueryData mediaQuery) {
return mediaQuery.displayFeatures
.where((DisplayFeature d) => d.bounds.shortestSide > 0 ||
d.state == DisplayFeatureState.postureHalfOpened)
.map((DisplayFeature d) => d.bounds);
}
/// Returns the closest sub-screen to the [anchorPoint].
static Rect _closestToAnchorPoint(Iterable<Rect> subScreens, Offset anchorPoint) {
Rect closestScreen = subScreens.first;
double closestDistance = _distanceFromPointToRect(anchorPoint, closestScreen);
for (final Rect screen in subScreens) {
final double subScreenDistance = _distanceFromPointToRect(anchorPoint, screen);
if (subScreenDistance < closestDistance) {
closestScreen = screen;
closestDistance = subScreenDistance;
}
}
return closestScreen;
}
static double _distanceFromPointToRect(Offset point, Rect rect) {
// Cases for point position relative to rect:
// 1 2 3
// 4 [R] 5
// 6 7 8
if (point.dx < rect.left) {
if (point.dy < rect.top) {
// Case 1
return (point - rect.topLeft).distance;
} else if (point.dy > rect.bottom) {
// Case 6
return (point - rect.bottomLeft).distance;
} else {
// Case 4
return rect.left - point.dx;
}
} else if (point.dx > rect.right) {
if (point.dy < rect.top) {
// Case 3
return (point - rect.topRight).distance;
} else if (point.dy > rect.bottom) {
// Case 8
return (point - rect.bottomRight).distance;
} else {
// Case 5
return point.dx - rect.right;
}
} else {
if (point.dy < rect.top) {
// Case 2
return rect.top - point.dy;
} else if (point.dy > rect.bottom) {
// Case 7
return point.dy - rect.bottom;
} else {
// Case R
return 0;
}
}
}
/// Returns sub-screens resulted by dividing [wantedBounds] along items of
/// [avoidBounds] that are at least as tall or as wide.
static Iterable<Rect> subScreensInBounds(Rect wantedBounds, Iterable<Rect> avoidBounds) {
Iterable<Rect> subScreens = <Rect>[wantedBounds];
for (final Rect bounds in avoidBounds) {
final List<Rect> newSubScreens = <Rect>[];
for (final Rect screen in subScreens) {
if (screen.top >= bounds.top && screen.bottom <= bounds.bottom) {
// Display feature splits the screen vertically
if (screen.left < bounds.left) {
// There is a smaller sub-screen, left of the display feature
newSubScreens.add(Rect.fromLTWH(
screen.left,
screen.top,
bounds.left - screen.left,
screen.height,
));
}
if (screen.right > bounds.right) {
// There is a smaller sub-screen, right of the display feature
newSubScreens.add(Rect.fromLTWH(
bounds.right,
screen.top,
screen.right - bounds.right,
screen.height,
));
}
} else if (screen.left >= bounds.left && screen.right <= bounds.right) {
// Display feature splits the sub-screen horizontally
if (screen.top < bounds.top) {
// There is a smaller sub-screen, above the display feature
newSubScreens.add(Rect.fromLTWH(
screen.left,
screen.top,
screen.width,
bounds.top - screen.top,
));
}
if (screen.bottom > bounds.bottom) {
// There is a smaller sub-screen, below the display feature
newSubScreens.add(Rect.fromLTWH(
screen.left,
bounds.bottom,
screen.width,
screen.bottom - bounds.bottom,
));
}
} else {
newSubScreens.add(screen);
}
}
subScreens = newSubScreens;
}
return subScreens;
}
static Offset _capOffset(Offset offset, Size maximum) {
if (offset.dx >= 0 && offset.dx <= maximum.width
&& offset.dy >=0 && offset.dy <= maximum.height) {
return offset;
} else {
return Offset(
math.min(math.max(0, offset.dx), maximum.width),
math.min(math.max(0, offset.dy), maximum.height),
);
}
}
}
| flutter/packages/flutter/lib/src/widgets/display_feature_sub_screen.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/display_feature_sub_screen.dart",
"repo_id": "flutter",
"token_count": 3583
} | 651 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
/// A description of an icon fulfilled by a font glyph.
///
/// See [Icons] for a number of predefined icons available for material
/// design applications.
///
/// In release builds, the Flutter tool will tree shake out of bundled fonts
/// the code points (or instances of [IconData]) which are not referenced from
/// Dart app code. See the [staticIconProvider] annotation for more details.
@immutable
class IconData {
/// Creates icon data.
///
/// Rarely used directly. Instead, consider using one of the predefined icons
/// like the [Icons] collection.
///
/// The [fontPackage] argument must be non-null when using a font family that
/// is included in a package. This is used when selecting the font.
///
/// Instantiating non-const instances of this class in your app will
/// mean the app cannot be built in release mode with icon tree-shaking (it
/// need to be explicitly opted out at build time). See [staticIconProvider]
/// for more context.
const IconData(
this.codePoint, {
this.fontFamily,
this.fontPackage,
this.matchTextDirection = false,
this.fontFamilyFallback,
});
/// The Unicode code point at which this icon is stored in the icon font.
final int codePoint;
/// The font family from which the glyph for the [codePoint] will be selected.
final String? fontFamily;
/// The name of the package from which the font family is included.
///
/// The name is used by the [Icon] widget when configuring the [TextStyle] so
/// that the given [fontFamily] is obtained from the appropriate asset.
///
/// See also:
///
/// * [TextStyle], which describes how to use fonts from other packages.
final String? fontPackage;
/// Whether this icon should be automatically mirrored in right-to-left
/// environments.
///
/// The [Icon] widget respects this value by mirroring the icon when the
/// [Directionality] is [TextDirection.rtl].
final bool matchTextDirection;
/// The ordered list of font families to fall back on when a glyph cannot be found in a higher priority font family.
///
/// For more details, refer to the documentation of [TextStyle]
final List<String>? fontFamilyFallback;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is IconData
&& other.codePoint == codePoint
&& other.fontFamily == fontFamily
&& other.fontPackage == fontPackage
&& other.matchTextDirection == matchTextDirection
&& listEquals(other.fontFamilyFallback, fontFamilyFallback);
}
@override
int get hashCode {
return Object.hash(
codePoint,
fontFamily,
fontPackage,
matchTextDirection,
Object.hashAll(fontFamilyFallback ?? const <String?>[]),
);
}
@override
String toString() => 'IconData(U+${codePoint.toRadixString(16).toUpperCase().padLeft(5, '0')})';
}
/// [DiagnosticsProperty] that has an [IconData] as value.
class IconDataProperty extends DiagnosticsProperty<IconData> {
/// Create a diagnostics property for [IconData].
IconDataProperty(
String super.name,
super.value, {
super.ifNull,
super.showName,
super.style,
super.level,
});
@override
Map<String, Object?> toJsonMap(DiagnosticsSerializationDelegate delegate) {
final Map<String, Object?> json = super.toJsonMap(delegate);
if (value != null) {
json['valueProperties'] = <String, Object>{
'codePoint': value!.codePoint,
};
}
return json;
}
}
class _StaticIconProvider {
const _StaticIconProvider();
}
/// Annotation for classes that only provide static const [IconData] instances.
///
/// This is a hint to the font tree shaker to ignore the constant instances
/// of [IconData] appearing in the declaration of this class when tree-shaking
/// unused code points from the bundled font.
///
/// Classes with this annotation must have only "static const" members. The
/// presence of any non-const [IconData] instances will preclude apps
/// importing the declaration into their application from being able to use
/// icon tree-shaking during release builds, resulting in larger font assets.
///
/// ```dart
/// @staticIconProvider
/// abstract final class MyCustomIcons {
/// static const String fontFamily = 'MyCustomIcons';
/// static const IconData happyFace = IconData(1, fontFamily: fontFamily);
/// static const IconData sadFace = IconData(2, fontFamily: fontFamily);
/// }
/// ```
const Object staticIconProvider = _StaticIconProvider();
| flutter/packages/flutter/lib/src/widgets/icon_data.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/icon_data.dart",
"repo_id": "flutter",
"token_count": 1407
} | 652 |
// Copyright 2014 The Flutter Authors. 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 'dart:ui';
import 'package:flutter/rendering.dart';
import 'basic.dart';
import 'container.dart';
import 'framework.dart';
import 'inherited_theme.dart';
import 'navigator.dart';
import 'overlay.dart';
/// Signature for a builder that builds a [Widget] with a [MagnifierController].
///
/// The builder is called exactly once per magnifier.
///
/// If the `controller` parameter's [MagnifierController.animationController]
/// field is set (by the builder) to an [AnimationController], the
/// [MagnifierController] will drive the animation during entry and exit.
///
/// The `magnifierInfo` parameter is updated with new [MagnifierInfo] instances
/// during the lifetime of the built magnifier, e.g. as the user moves their
/// finger around the text field.
typedef MagnifierBuilder = Widget? Function(
BuildContext context,
MagnifierController controller,
ValueNotifier<MagnifierInfo> magnifierInfo,
);
/// A data class that contains the geometry information of text layouts
/// and selection gestures, used to position magnifiers.
@immutable
class MagnifierInfo {
/// Constructs a [MagnifierInfo] from provided geometry values.
const MagnifierInfo({
required this.globalGesturePosition,
required this.caretRect,
required this.fieldBounds,
required this.currentLineBoundaries,
});
/// Const [MagnifierInfo] with all values set to 0.
static const MagnifierInfo empty = MagnifierInfo(
globalGesturePosition: Offset.zero,
caretRect: Rect.zero,
currentLineBoundaries: Rect.zero,
fieldBounds: Rect.zero,
);
/// The offset of the gesture position that the magnifier should be shown at.
final Offset globalGesturePosition;
/// The rect of the current line the magnifier should be shown at, without
/// taking into account any padding of the field; only the position of the
/// first and last character.
final Rect currentLineBoundaries;
/// The rect of the handle that the magnifier should follow.
final Rect caretRect;
/// The bounds of the entire text field that the magnifier is bound to.
final Rect fieldBounds;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is MagnifierInfo
&& other.globalGesturePosition == globalGesturePosition
&& other.caretRect == caretRect
&& other.currentLineBoundaries == currentLineBoundaries
&& other.fieldBounds == fieldBounds;
}
@override
int get hashCode => Object.hash(
globalGesturePosition,
caretRect,
fieldBounds,
currentLineBoundaries,
);
}
/// A configuration object for a magnifier (e.g. in a text field).
///
/// In general, most features of the magnifier can be configured by controlling
/// the widgets built by the [magnifierBuilder].
class TextMagnifierConfiguration {
/// Constructs a [TextMagnifierConfiguration] from parts.
///
/// If [magnifierBuilder] is null, a default [MagnifierBuilder] will be used
/// that does not build a magnifier.
const TextMagnifierConfiguration({
MagnifierBuilder? magnifierBuilder,
this.shouldDisplayHandlesInMagnifier = true,
}) : _magnifierBuilder = magnifierBuilder;
/// The builder callback that creates the widget that renders the magnifier.
MagnifierBuilder get magnifierBuilder => _magnifierBuilder ?? _none;
final MagnifierBuilder? _magnifierBuilder;
static Widget? _none(
BuildContext context,
MagnifierController controller,
ValueNotifier<MagnifierInfo> magnifierInfo,
) => null;
/// Whether a magnifier should show the text editing handles or not.
///
/// This flag is used by [SelectionOverlay.showMagnifier] to control the order
/// of layers in the rendering; specifically, whether to place the layer
/// containing the handles above or below the layer containing the magnifier
/// in the [Overlay].
final bool shouldDisplayHandlesInMagnifier;
/// A constant for a [TextMagnifierConfiguration] that is disabled, meaning it
/// never builds anything, regardless of platform.
static const TextMagnifierConfiguration disabled = TextMagnifierConfiguration();
}
/// A controller for a magnifier.
///
/// [MagnifierController]'s main benefit over holding a raw [OverlayEntry] is that
/// [MagnifierController] will handle logic around waiting for a magnifier to animate in or out.
///
/// If a magnifier chooses to have an entry / exit animation, it should provide the animation
/// controller to [MagnifierController.animationController]. [MagnifierController] will then drive
/// the [AnimationController] and wait for it to be complete before removing it from the
/// [Overlay].
///
/// To check the status of the magnifier, see [MagnifierController.shown].
// TODO(antholeole): This whole paradigm can be removed once portals
// lands - then the magnifier can be controlled though a widget in the tree.
// https://github.com/flutter/flutter/pull/105335
class MagnifierController {
/// If there is no in / out animation for the magnifier, [animationController] should be left
/// null.
MagnifierController({this.animationController}) {
animationController?.value = 0;
}
/// The controller that will be driven in / out when show / hide is triggered,
/// respectively.
AnimationController? animationController;
/// The magnifier's [OverlayEntry], if currently in the overlay.
///
/// This is exposed so that other overlay entries can be positioned above or
/// below this [overlayEntry]. Anything in the paint order after the
/// [RawMagnifier] in this [OverlayEntry] will not be displayed in the
/// magnifier; if it is desired for an overlay entry to be displayed in the
/// magnifier, it _must_ be positioned below the magnifier.
///
/// {@tool snippet}
/// ```dart
/// void magnifierShowExample(BuildContext context) {
/// final MagnifierController myMagnifierController = MagnifierController();
///
/// // Placed below the magnifier, so it will show.
/// Overlay.of(context).insert(OverlayEntry(
/// builder: (BuildContext context) => const Text('I WILL display in the magnifier')));
///
/// // Will display in the magnifier, since this entry was passed to show.
/// final OverlayEntry displayInMagnifier = OverlayEntry(
/// builder: (BuildContext context) =>
/// const Text('I WILL display in the magnifier'));
///
/// Overlay.of(context)
/// .insert(displayInMagnifier);
/// myMagnifierController.show(
/// context: context,
/// below: displayInMagnifier,
/// builder: (BuildContext context) => const RawMagnifier(
/// size: Size(100, 100),
/// ));
///
/// // By default, new entries will be placed over the top entry.
/// Overlay.of(context).insert(OverlayEntry(
/// builder: (BuildContext context) => const Text('I WILL NOT display in the magnifier')));
///
/// Overlay.of(context).insert(
/// below:
/// myMagnifierController.overlayEntry, // Explicitly placed below the magnifier.
/// OverlayEntry(
/// builder: (BuildContext context) => const Text('I WILL display in the magnifier')));
/// }
/// ```
/// {@end-tool}
///
/// To check if a magnifier is in the overlay, use [shown]. The [overlayEntry]
/// field may be non-null even when the magnifier is not visible.
OverlayEntry? get overlayEntry => _overlayEntry;
OverlayEntry? _overlayEntry;
/// Whether the magnifier is currently being shown.
///
/// This is false when nothing is in the overlay, when the
/// [animationController] is in the [AnimationStatus.dismissed] state, or when
/// the [animationController] is animating out (i.e. in the
/// [AnimationStatus.reverse] state).
///
/// It is true in the opposite cases, i.e. when the overlay is not empty, and
/// either the [animationController] is null, in the
/// [AnimationStatus.completed] state, or in the [AnimationStatus.forward]
/// state.
bool get shown {
if (overlayEntry == null) {
return false;
}
if (animationController != null) {
return animationController!.status == AnimationStatus.completed ||
animationController!.status == AnimationStatus.forward;
}
return true;
}
/// Displays the magnifier.
///
/// Returns a future that completes when the magnifier is fully shown, i.e. done
/// with its entry animation.
///
/// To control what overlays are shown in the magnifier, use `below`. See
/// [overlayEntry] for more details on how to utilize `below`.
///
/// If the magnifier already exists (i.e. [overlayEntry] != null), then [show]
/// will replace the old overlay without playing an exit animation. Consider
/// awaiting [hide] first, to animate from the old magnifier to the new one.
Future<void> show({
required BuildContext context,
required WidgetBuilder builder,
Widget? debugRequiredFor,
OverlayEntry? below,
}) async {
_overlayEntry?.remove();
_overlayEntry?.dispose();
final OverlayState overlayState = Overlay.of(
context,
rootOverlay: true,
debugRequiredFor: debugRequiredFor,
);
final CapturedThemes capturedThemes = InheritedTheme.capture(
from: context,
to: Navigator.maybeOf(context)?.context,
);
_overlayEntry = OverlayEntry(
builder: (BuildContext context) => capturedThemes.wrap(builder(context)),
);
overlayState.insert(overlayEntry!, below: below);
if (animationController != null) {
await animationController?.forward();
}
}
/// Schedules a hide of the magnifier.
///
/// If this [MagnifierController] has an [AnimationController],
/// then [hide] reverses the animation controller and waits
/// for the animation to complete. Then, if [removeFromOverlay]
/// is true, remove the magnifier from the overlay.
///
/// In general, `removeFromOverlay` should be true, unless
/// the magnifier needs to preserve states between shows / hides.
///
/// See also:
///
/// * [removeFromOverlay] which removes the [OverlayEntry] from the [Overlay]
/// synchronously.
Future<void> hide({bool removeFromOverlay = true}) async {
if (overlayEntry == null) {
return;
}
if (animationController != null) {
await animationController?.reverse();
}
if (removeFromOverlay) {
this.removeFromOverlay();
}
}
/// Remove the [OverlayEntry] from the [Overlay].
///
/// This method removes the [OverlayEntry] synchronously,
/// regardless of exit animation: this leads to abrupt removals
/// of [OverlayEntry]s with animations.
///
/// To allow the [OverlayEntry] to play its exit animation, consider calling
/// [hide] instead, with `removeFromOverlay` set to true, and optionally await
/// the returned Future.
@visibleForTesting
void removeFromOverlay() {
_overlayEntry?.remove();
_overlayEntry?.dispose();
_overlayEntry = null;
}
/// A utility for calculating a new [Rect] from [rect] such that
/// [rect] is fully constrained within [bounds].
///
/// Any point in the output rect is guaranteed to also be a point contained in [bounds].
///
/// It is a runtime error for [rect].width to be greater than [bounds].width,
/// and it is also an error for [rect].height to be greater than [bounds].height.
///
/// This algorithm translates [rect] the shortest distance such that it is entirely within
/// [bounds].
///
/// If [rect] is already within [bounds], no shift will be applied to [rect] and
/// [rect] will be returned as-is.
///
/// It is perfectly valid for the output rect to have a point along the edge of the
/// [bounds]. If the desired output rect requires that no edges are parallel to edges
/// of [bounds], see [Rect.deflate] by 1 on [bounds] to achieve this effect.
static Rect shiftWithinBounds({
required Rect rect,
required Rect bounds,
}) {
assert(rect.width <= bounds.width,
'attempted to shift $rect within $bounds, but the rect has a greater width.');
assert(rect.height <= bounds.height,
'attempted to shift $rect within $bounds, but the rect has a greater height.');
Offset rectShift = Offset.zero;
if (rect.left < bounds.left) {
rectShift += Offset(bounds.left - rect.left, 0);
} else if (rect.right > bounds.right) {
rectShift += Offset(bounds.right - rect.right, 0);
}
if (rect.top < bounds.top) {
rectShift += Offset(0, bounds.top - rect.top);
} else if (rect.bottom > bounds.bottom) {
rectShift += Offset(0, bounds.bottom - rect.bottom);
}
return rect.shift(rectShift);
}
}
/// A decoration for a [RawMagnifier].
///
/// [MagnifierDecoration] does not expose [ShapeDecoration.color], [ShapeDecoration.image],
/// or [ShapeDecoration.gradient], since they will be covered by the [RawMagnifier]'s lens.
///
/// Also takes an [opacity] (see https://github.com/flutter/engine/pull/34435).
class MagnifierDecoration extends ShapeDecoration {
/// Constructs a [MagnifierDecoration].
///
/// By default, [MagnifierDecoration] is a rectangular magnifier with no shadows, and
/// fully opaque.
const MagnifierDecoration({
this.opacity = 1,
super.shadows,
super.shape = const RoundedRectangleBorder(),
});
/// The magnifier's opacity.
final double opacity;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return super == other && other is MagnifierDecoration && other.opacity == opacity;
}
@override
int get hashCode => Object.hash(super.hashCode, opacity);
}
/// A common base class for magnifiers.
///
/// {@tool dartpad}
/// This sample demonstrates what a magnifier is, and how it can be used.
///
/// ** See code in examples/api/lib/widgets/magnifier/magnifier.0.dart **
/// {@end-tool}
///
/// {@template flutter.widgets.magnifier.intro}
/// This magnifying glass is useful for scenarios on mobile devices where
/// the user's finger may be covering part of the screen where a granular
/// action is being performed, such as navigating a small cursor with a drag
/// gesture, on an image or text.
/// {@endtemplate}
///
/// A magnifier can be conveniently managed by [MagnifierController], which handles
/// showing and hiding the magnifier, with an optional entry / exit animation.
///
/// See:
/// * [MagnifierController], a controller to handle magnifiers in an overlay.
class RawMagnifier extends StatelessWidget {
/// Constructs a [RawMagnifier].
///
/// {@template flutter.widgets.magnifier.RawMagnifier.invisibility_warning}
/// By default, this magnifier uses the default [MagnifierDecoration],
/// the focal point is directly under the magnifier, and there is no magnification:
/// This means that a default magnifier will be entirely invisible to the naked eye,
/// since it is painting exactly what is under it, exactly where it was painted
/// originally.
/// {@endtemplate}
const RawMagnifier({
super.key,
this.child,
this.decoration = const MagnifierDecoration(),
this.focalPointOffset = Offset.zero,
this.magnificationScale = 1,
required this.size,
}) : assert(magnificationScale != 0,
'Magnification scale of 0 results in undefined behavior.');
/// An optional widget to position inside the len of the [RawMagnifier].
///
/// This is positioned over the [RawMagnifier] - it may be useful for tinting the
/// [RawMagnifier], or drawing a crosshair like UI.
final Widget? child;
/// This magnifier's decoration.
///
/// {@macro flutter.widgets.magnifier.RawMagnifier.invisibility_warning}
final MagnifierDecoration decoration;
/// The offset of the magnifier from [RawMagnifier]'s center.
///
/// {@template flutter.widgets.magnifier.offset}
/// For example, if [RawMagnifier] is globally positioned at Offset(100, 100),
/// and [focalPointOffset] is Offset(-20, -20), then [RawMagnifier] will see
/// the content at global offset (80, 80).
///
/// If left as [Offset.zero], the [RawMagnifier] will show the content that
/// is directly below it.
/// {@endtemplate}
final Offset focalPointOffset;
/// How "zoomed in" the magnification subject is in the lens.
final double magnificationScale;
/// The size of the magnifier.
///
/// This does not include added border; it only includes
/// the size of the magnifier.
final Size size;
@override
Widget build(BuildContext context) {
return Stack(
clipBehavior: Clip.none,
alignment: Alignment.center,
children: <Widget>[
ClipPath.shape(
shape: decoration.shape,
child: Opacity(
opacity: decoration.opacity,
child: _Magnifier(
shape: decoration.shape,
focalPointOffset: focalPointOffset,
magnificationScale: magnificationScale,
child: SizedBox.fromSize(
size: size,
child: child,
),
),
),
),
// Because `BackdropFilter` will filter any widgets before it, we should
// apply the style after (i.e. in a younger sibling) to avoid the magnifier
// from seeing its own styling.
Opacity(
opacity: decoration.opacity,
child: _MagnifierStyle(
decoration,
size: size,
),
)
],
);
}
}
class _MagnifierStyle extends StatelessWidget {
const _MagnifierStyle(this.decoration, {required this.size});
final MagnifierDecoration decoration;
final Size size;
@override
Widget build(BuildContext context) {
double largestShadow = 0;
for (final BoxShadow shadow in decoration.shadows ?? <BoxShadow>[]) {
largestShadow = math.max(
largestShadow,
(shadow.blurRadius + shadow.spreadRadius) +
math.max(shadow.offset.dy.abs(), shadow.offset.dx.abs()));
}
return ClipPath(
clipBehavior: Clip.hardEdge,
clipper: _DonutClip(
shape: decoration.shape,
spreadRadius: largestShadow,
),
child: DecoratedBox(
decoration: decoration,
child: SizedBox.fromSize(
size: size,
),
),
);
}
}
/// A `clipPath` that looks like a donut if you were to fill its area.
///
/// This is necessary because the shadow must be added after the magnifier is drawn,
/// so that the shadow does not end up in the magnifier. Without this clip, the magnifier would be
/// entirely covered by the shadow.
///
/// The negative space of the donut is clipped out (the donut hole, outside the donut).
/// The donut hole is cut out exactly like the shape of the magnifier.
class _DonutClip extends CustomClipper<Path> {
_DonutClip({required this.shape, required this.spreadRadius});
final double spreadRadius;
final ShapeBorder shape;
@override
Path getClip(Size size) {
final Path path = Path();
final Rect rect = Offset.zero & size;
path.fillType = PathFillType.evenOdd;
path.addPath(shape.getOuterPath(rect.inflate(spreadRadius)), Offset.zero);
path.addPath(shape.getInnerPath(rect), Offset.zero);
return path;
}
@override
bool shouldReclip(_DonutClip oldClipper) => oldClipper.shape != shape;
}
class _Magnifier extends SingleChildRenderObjectWidget {
const _Magnifier({
super.child,
required this.shape,
this.magnificationScale = 1,
this.focalPointOffset = Offset.zero,
});
// The Offset that the center of the _Magnifier points to, relative
// to the center of the magnifier.
final Offset focalPointOffset;
// The enlarge multiplier of the magnification.
//
// If equal to 1.0, the content in the magnifier is true to its real size.
// If greater than 1.0, the content appears bigger in the magnifier.
final double magnificationScale;
// Shape of the magnifier.
final ShapeBorder shape;
@override
RenderObject createRenderObject(BuildContext context) {
return _RenderMagnification(focalPointOffset, magnificationScale, shape);
}
@override
void updateRenderObject(
BuildContext context, _RenderMagnification renderObject) {
renderObject
..focalPointOffset = focalPointOffset
..shape = shape
..magnificationScale = magnificationScale;
}
}
class _RenderMagnification extends RenderProxyBox {
_RenderMagnification(
this._focalPointOffset,
this._magnificationScale,
this._shape, {
RenderBox? child,
}) : super(child);
Offset get focalPointOffset => _focalPointOffset;
Offset _focalPointOffset;
set focalPointOffset(Offset value) {
if (_focalPointOffset == value) {
return;
}
_focalPointOffset = value;
markNeedsPaint();
}
double get magnificationScale => _magnificationScale;
double _magnificationScale;
set magnificationScale(double value) {
if (_magnificationScale == value) {
return;
}
_magnificationScale = value;
markNeedsPaint();
}
ShapeBorder get shape => _shape;
ShapeBorder _shape;
set shape(ShapeBorder value) {
if (_shape == value) {
return;
}
_shape = value;
markNeedsPaint();
}
@override
bool get alwaysNeedsCompositing => true;
@override
BackdropFilterLayer? get layer => super.layer as BackdropFilterLayer?;
@override
void paint(PaintingContext context, Offset offset) {
final Offset thisCenter = Alignment.center.alongSize(size) + offset;
final Matrix4 matrix = Matrix4.identity()
..translate(
magnificationScale * ((focalPointOffset.dx * -1) - thisCenter.dx) + thisCenter.dx,
magnificationScale * ((focalPointOffset.dy * -1) - thisCenter.dy) + thisCenter.dy)
..scale(magnificationScale);
final ImageFilter filter = ImageFilter.matrix(matrix.storage, filterQuality: FilterQuality.high);
if (layer == null) {
layer = BackdropFilterLayer(
filter: filter,
);
} else {
layer!.filter = filter;
}
context.pushLayer(layer!, super.paint, offset);
}
}
| flutter/packages/flutter/lib/src/widgets/magnifier.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/magnifier.dart",
"repo_id": "flutter",
"token_count": 7120
} | 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/foundation.dart';
import 'basic.dart';
import 'framework.dart';
class _PlaceholderPainter extends CustomPainter {
const _PlaceholderPainter({
required this.color,
required this.strokeWidth,
});
final Color color;
final double strokeWidth;
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = strokeWidth;
final Rect rect = Offset.zero & size;
final Path path = Path()
..addRect(rect)
..addPolygon(<Offset>[rect.topRight, rect.bottomLeft], false)
..addPolygon(<Offset>[rect.topLeft, rect.bottomRight], false);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(_PlaceholderPainter oldPainter) {
return oldPainter.color != color
|| oldPainter.strokeWidth != strokeWidth;
}
@override
bool hitTest(Offset position) => false;
}
/// A widget that draws a box that represents where other widgets will one day
/// be added.
///
/// This widget is useful during development to indicate that the interface is
/// not yet complete.
///
/// By default, the placeholder is sized to fit its container. If the
/// placeholder is in an unbounded space, it will size itself according to the
/// given [fallbackWidth] and [fallbackHeight].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=LPe56fezmoo}
class Placeholder extends StatelessWidget {
/// Creates a widget which draws a box.
const Placeholder({
super.key,
this.color = const Color(0xFF455A64), // Blue Grey 700
this.strokeWidth = 2.0,
this.fallbackWidth = 400.0,
this.fallbackHeight = 400.0,
this.child
});
/// The color to draw the placeholder box.
final Color color;
/// The width of the lines in the placeholder box.
final double strokeWidth;
/// The width to use when the placeholder is in a situation with an unbounded
/// width.
///
/// See also:
///
/// * [fallbackHeight], the same but vertically.
final double fallbackWidth;
/// The height to use when the placeholder is in a situation with an unbounded
/// height.
///
/// See also:
///
/// * [fallbackWidth], the same but horizontally.
final double fallbackHeight;
/// The [child] contained by the placeholder box.
///
/// Defaults to null.
final Widget? child;
@override
Widget build(BuildContext context) {
return LimitedBox(
maxWidth: fallbackWidth,
maxHeight: fallbackHeight,
child: CustomPaint(
size: Size.infinite,
painter: _PlaceholderPainter(
color: color,
strokeWidth: strokeWidth,
),
child: child,
),
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(ColorProperty('color', color, defaultValue: const Color(0xFF455A64)));
properties.add(DoubleProperty('strokeWidth', strokeWidth, defaultValue: 2.0));
properties.add(DoubleProperty('fallbackWidth', fallbackWidth, defaultValue: 400.0));
properties.add(DoubleProperty('fallbackHeight', fallbackHeight, defaultValue: 400.0));
}
}
| flutter/packages/flutter/lib/src/widgets/placeholder.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/placeholder.dart",
"repo_id": "flutter",
"token_count": 1091
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart' show LogicalKeyboardKey;
import 'framework.dart';
import 'overscroll_indicator.dart';
import 'scroll_physics.dart';
import 'scrollable.dart';
import 'scrollable_helpers.dart';
import 'scrollbar.dart';
const Color _kDefaultGlowColor = Color(0xFFFFFFFF);
/// Device types that scrollables should accept drag gestures from by default.
const Set<PointerDeviceKind> _kTouchLikeDeviceTypes = <PointerDeviceKind>{
PointerDeviceKind.touch,
PointerDeviceKind.stylus,
PointerDeviceKind.invertedStylus,
PointerDeviceKind.trackpad,
// The VoiceAccess sends pointer events with unknown type when scrolling
// scrollables.
PointerDeviceKind.unknown,
};
/// Types of overscroll indicators supported by [TargetPlatform.android].
enum AndroidOverscrollIndicator {
/// Utilizes a [StretchingOverscrollIndicator], which transforms the contents
/// of a [ScrollView] when overscrolled.
stretch,
/// Utilizes a [GlowingOverscrollIndicator], painting a glowing semi circle on
/// top of the [ScrollView] in response to overscrolling.
glow,
}
/// Describes how [Scrollable] widgets should behave.
///
/// {@template flutter.widgets.scrollBehavior}
/// Used by [ScrollConfiguration] to configure the [Scrollable] widgets in a
/// subtree.
///
/// This class can be extended to further customize a [ScrollBehavior] for a
/// subtree. For example, overriding [ScrollBehavior.getScrollPhysics] sets the
/// default [ScrollPhysics] for [Scrollable]s that inherit this [ScrollConfiguration].
/// Overriding [ScrollBehavior.buildOverscrollIndicator] can be used to add or change
/// the default [GlowingOverscrollIndicator] decoration, while
/// [ScrollBehavior.buildScrollbar] can be changed to modify the default [Scrollbar].
///
/// When looking to easily toggle the default decorations, you can use
/// [ScrollBehavior.copyWith] instead of creating your own [ScrollBehavior] class.
/// The `scrollbar` and `overscrollIndicator` flags can turn these decorations off.
/// {@endtemplate}
///
/// See also:
///
/// * [ScrollConfiguration], the inherited widget that controls how
/// [Scrollable] widgets behave in a subtree.
@immutable
class ScrollBehavior {
/// Creates a description of how [Scrollable] widgets should behave.
const ScrollBehavior();
/// Creates a copy of this ScrollBehavior, making it possible to
/// easily toggle `scrollbar` and `overscrollIndicator` effects.
///
/// This is used by widgets like [PageView] and [ListWheelScrollView] to
/// override the current [ScrollBehavior] and manage how they are decorated.
/// Widgets such as these have the option to provide a [ScrollBehavior] on
/// the widget level, like [PageView.scrollBehavior], in order to change the
/// default.
ScrollBehavior copyWith({
bool? scrollbars,
bool? overscroll,
Set<PointerDeviceKind>? dragDevices,
MultitouchDragStrategy? multitouchDragStrategy,
Set<LogicalKeyboardKey>? pointerAxisModifiers,
ScrollPhysics? physics,
TargetPlatform? platform,
}) {
return _WrappedScrollBehavior(
delegate: this,
scrollbars: scrollbars ?? true,
overscroll: overscroll ?? true,
dragDevices: dragDevices,
multitouchDragStrategy: multitouchDragStrategy,
pointerAxisModifiers: pointerAxisModifiers,
physics: physics,
platform: platform,
);
}
/// The platform whose scroll physics should be implemented.
///
/// Defaults to the current platform.
TargetPlatform getPlatform(BuildContext context) => defaultTargetPlatform;
/// The device kinds that the scrollable will accept drag gestures from.
///
/// By default only [PointerDeviceKind.touch], [PointerDeviceKind.stylus], and
/// [PointerDeviceKind.invertedStylus] are configured to create drag gestures.
/// Enabling this for [PointerDeviceKind.mouse] will make it difficult or
/// impossible to select text in scrollable containers and is not recommended.
Set<PointerDeviceKind> get dragDevices => _kTouchLikeDeviceTypes;
/// {@macro flutter.gestures.monodrag.DragGestureRecognizer.multitouchDragStrategy}
///
/// By default, [MultitouchDragStrategy.latestPointer] is configured to
/// create drag gestures for non-Apple platforms, and
/// [MultitouchDragStrategy.averageBoundaryPointers] for Apple platforms.
MultitouchDragStrategy getMultitouchDragStrategy(BuildContext context) {
switch (getPlatform(context)) {
case TargetPlatform.macOS:
case TargetPlatform.iOS:
return MultitouchDragStrategy.averageBoundaryPointers;
case TargetPlatform.linux:
case TargetPlatform.windows:
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return MultitouchDragStrategy.latestPointer;
}
}
/// A set of [LogicalKeyboardKey]s that, when any or all are pressed in
/// combination with a [PointerDeviceKind.mouse] pointer scroll event, will
/// flip the axes of the scroll input.
///
/// This will for example, result in the input of a vertical mouse wheel, to
/// move the [ScrollPosition] of a [ScrollView] with an [Axis.horizontal]
/// scroll direction.
///
/// If other keys exclusive of this set are pressed during a scroll event, in
/// conjunction with keys from this set, the scroll input will still be
/// flipped.
///
/// Defaults to [LogicalKeyboardKey.shiftLeft],
/// [LogicalKeyboardKey.shiftRight].
Set<LogicalKeyboardKey> get pointerAxisModifiers => <LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.shiftRight,
};
/// Applies a [RawScrollbar] to the child widget on desktop platforms.
Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) {
// When modifying this function, consider modifying the implementation in
// the Material and Cupertino subclasses as well.
switch (getPlatform(context)) {
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
assert(details.controller != null);
return RawScrollbar(
controller: details.controller,
child: child,
);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.iOS:
return child;
}
}
/// Applies a [GlowingOverscrollIndicator] to the child widget on
/// [TargetPlatform.android] and [TargetPlatform.fuchsia].
Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
// When modifying this function, consider modifying the implementation in
// the Material and Cupertino subclasses as well.
switch (getPlatform(context)) {
case TargetPlatform.iOS:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
return child;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return GlowingOverscrollIndicator(
axisDirection: details.direction,
color: _kDefaultGlowColor,
child: child,
);
}
}
/// Specifies the type of velocity tracker to use in the descendant
/// [Scrollable]s' drag gesture recognizers, for estimating the velocity of a
/// drag gesture.
///
/// This can be used to, for example, apply different fling velocity
/// estimation methods on different platforms, in order to match the
/// platform's native behavior.
///
/// Typically, the provided [GestureVelocityTrackerBuilder] should return a
/// fresh velocity tracker. If null is returned, [Scrollable] creates a new
/// [VelocityTracker] to track the newly added pointer that may develop into
/// a drag gesture.
///
/// The default implementation provides a new
/// [IOSScrollViewFlingVelocityTracker] on iOS and macOS for each new pointer,
/// and a new [VelocityTracker] on other platforms for each new pointer.
GestureVelocityTrackerBuilder velocityTrackerBuilder(BuildContext context) {
switch (getPlatform(context)) {
case TargetPlatform.iOS:
return (PointerEvent event) => IOSScrollViewFlingVelocityTracker(event.kind);
case TargetPlatform.macOS:
return (PointerEvent event) => MacOSScrollViewFlingVelocityTracker(event.kind);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return (PointerEvent event) => VelocityTracker.withKind(event.kind);
}
}
static const ScrollPhysics _bouncingPhysics = BouncingScrollPhysics(parent: RangeMaintainingScrollPhysics());
static const ScrollPhysics _bouncingDesktopPhysics = BouncingScrollPhysics(
decelerationRate: ScrollDecelerationRate.fast,
parent: RangeMaintainingScrollPhysics()
);
static const ScrollPhysics _clampingPhysics = ClampingScrollPhysics(parent: RangeMaintainingScrollPhysics());
/// The scroll physics to use for the platform given by [getPlatform].
///
/// Defaults to [RangeMaintainingScrollPhysics] mixed with
/// [BouncingScrollPhysics] on iOS and [ClampingScrollPhysics] on
/// Android.
ScrollPhysics getScrollPhysics(BuildContext context) {
// When modifying this function, consider modifying the implementation in
// the Material and Cupertino subclasses as well.
switch (getPlatform(context)) {
case TargetPlatform.iOS:
return _bouncingPhysics;
case TargetPlatform.macOS:
return _bouncingDesktopPhysics;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return _clampingPhysics;
}
}
/// Called whenever a [ScrollConfiguration] is rebuilt with a new
/// [ScrollBehavior] of the same [runtimeType].
///
/// If the new instance represents different information than the old
/// instance, then the method should return true, otherwise it should return
/// false.
///
/// If this method returns true, all the widgets that inherit from the
/// [ScrollConfiguration] will rebuild using the new [ScrollBehavior]. If this
/// method returns false, the rebuilds might be optimized away.
bool shouldNotify(covariant ScrollBehavior oldDelegate) => false;
@override
String toString() => objectRuntimeType(this, 'ScrollBehavior');
}
class _WrappedScrollBehavior implements ScrollBehavior {
const _WrappedScrollBehavior({
required this.delegate,
this.scrollbars = true,
this.overscroll = true,
Set<PointerDeviceKind>? dragDevices,
this.multitouchDragStrategy,
Set<LogicalKeyboardKey>? pointerAxisModifiers,
this.physics,
this.platform,
}) : _dragDevices = dragDevices,
_pointerAxisModifiers = pointerAxisModifiers;
final ScrollBehavior delegate;
final bool scrollbars;
final bool overscroll;
final ScrollPhysics? physics;
final TargetPlatform? platform;
final Set<PointerDeviceKind>? _dragDevices;
final MultitouchDragStrategy? multitouchDragStrategy;
final Set<LogicalKeyboardKey>? _pointerAxisModifiers;
@override
Set<PointerDeviceKind> get dragDevices => _dragDevices ?? delegate.dragDevices;
@override
Set<LogicalKeyboardKey> get pointerAxisModifiers => _pointerAxisModifiers ?? delegate.pointerAxisModifiers;
@override
MultitouchDragStrategy getMultitouchDragStrategy(BuildContext context) {
return multitouchDragStrategy ?? delegate.getMultitouchDragStrategy(context);
}
@override
Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
if (overscroll) {
return delegate.buildOverscrollIndicator(context, child, details);
}
return child;
}
@override
Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) {
if (scrollbars) {
return delegate.buildScrollbar(context, child, details);
}
return child;
}
@override
ScrollBehavior copyWith({
bool? scrollbars,
bool? overscroll,
Set<PointerDeviceKind>? dragDevices,
MultitouchDragStrategy? multitouchDragStrategy,
Set<LogicalKeyboardKey>? pointerAxisModifiers,
ScrollPhysics? physics,
TargetPlatform? platform,
}) {
return delegate.copyWith(
scrollbars: scrollbars ?? this.scrollbars,
overscroll: overscroll ?? this.overscroll,
dragDevices: dragDevices ?? this.dragDevices,
multitouchDragStrategy: multitouchDragStrategy ?? this.multitouchDragStrategy,
pointerAxisModifiers: pointerAxisModifiers ?? this.pointerAxisModifiers,
physics: physics ?? this.physics,
platform: platform ?? this.platform,
);
}
@override
TargetPlatform getPlatform(BuildContext context) {
return platform ?? delegate.getPlatform(context);
}
@override
ScrollPhysics getScrollPhysics(BuildContext context) {
return physics ?? delegate.getScrollPhysics(context);
}
@override
bool shouldNotify(_WrappedScrollBehavior oldDelegate) {
return oldDelegate.delegate.runtimeType != delegate.runtimeType
|| oldDelegate.scrollbars != scrollbars
|| oldDelegate.overscroll != overscroll
|| !setEquals<PointerDeviceKind>(oldDelegate.dragDevices, dragDevices)
|| oldDelegate.multitouchDragStrategy != multitouchDragStrategy
|| !setEquals<LogicalKeyboardKey>(oldDelegate.pointerAxisModifiers, pointerAxisModifiers)
|| oldDelegate.physics != physics
|| oldDelegate.platform != platform
|| delegate.shouldNotify(oldDelegate.delegate);
}
@override
GestureVelocityTrackerBuilder velocityTrackerBuilder(BuildContext context) {
return delegate.velocityTrackerBuilder(context);
}
@override
String toString() => objectRuntimeType(this, '_WrappedScrollBehavior');
}
/// Controls how [Scrollable] widgets behave in a subtree.
///
/// The scroll configuration determines the [ScrollPhysics] and viewport
/// decorations used by descendants of [child].
class ScrollConfiguration extends InheritedWidget {
/// Creates a widget that controls how [Scrollable] widgets behave in a subtree.
const ScrollConfiguration({
super.key,
required this.behavior,
required super.child,
});
/// How [Scrollable] widgets that are descendants of [child] should behave.
final ScrollBehavior behavior;
/// The [ScrollBehavior] for [Scrollable] widgets in the given [BuildContext].
///
/// If no [ScrollConfiguration] widget is in scope of the given `context`,
/// a default [ScrollBehavior] instance is returned.
static ScrollBehavior of(BuildContext context) {
final ScrollConfiguration? configuration = context.dependOnInheritedWidgetOfExactType<ScrollConfiguration>();
return configuration?.behavior ?? const ScrollBehavior();
}
@override
bool updateShouldNotify(ScrollConfiguration oldWidget) {
return behavior.runtimeType != oldWidget.behavior.runtimeType
|| (behavior != oldWidget.behavior && behavior.shouldNotify(oldWidget.behavior));
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ScrollBehavior>('behavior', behavior));
}
}
| flutter/packages/flutter/lib/src/widgets/scroll_configuration.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/scroll_configuration.dart",
"repo_id": "flutter",
"token_count": 4712
} | 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/rendering.dart';
import 'framework.dart';
/// A container that handles [SelectionEvent]s for the [Selectable]s in
/// the subtree.
///
/// This widget is useful when one wants to customize selection behaviors for
/// a group of [Selectable]s
///
/// The state of this container is a single selectable and will register
/// itself to the [registrar] if provided. Otherwise, it will register to the
/// [SelectionRegistrar] from the context. Consider using a [SelectionArea]
/// widget to provide a root registrar.
///
/// The containers handle the [SelectionEvent]s from the registered
/// [SelectionRegistrar] and delegate the events to the [delegate].
///
/// This widget uses [SelectionRegistrarScope] to host the [delegate] as the
/// [SelectionRegistrar] for the subtree to collect the [Selectable]s, and
/// [SelectionEvent]s received by this container are sent to the [delegate] using
/// the [SelectionHandler] API of the delegate.
///
/// {@tool dartpad}
/// This sample demonstrates how to create a [SelectionContainer] that only
/// allows selecting everything or nothing with no partial selection.
///
/// ** See code in examples/api/lib/material/selection_container/selection_container.0.dart **
/// {@end-tool}
///
/// See also:
/// * [SelectableRegion], which provides an overview of the selection system.
/// * [SelectionContainer.disabled], which disable selection for a
/// subtree.
class SelectionContainer extends StatefulWidget {
/// Creates a selection container to collect the [Selectable]s in the subtree.
///
/// If [registrar] is not provided, this selection container gets the
/// [SelectionRegistrar] from the context instead.
const SelectionContainer({
super.key,
this.registrar,
required SelectionContainerDelegate this.delegate,
required this.child,
});
/// Creates a selection container that disables selection for the
/// subtree.
///
/// {@tool dartpad}
/// This sample demonstrates how to disable selection for a Text under a
/// SelectionArea.
///
/// ** See code in examples/api/lib/material/selection_container/selection_container_disabled.0.dart **
/// {@end-tool}
const SelectionContainer.disabled({
super.key,
required this.child,
}) : registrar = null,
delegate = null;
/// The [SelectionRegistrar] this container is registered to.
///
/// If null, this widget gets the [SelectionRegistrar] from the current
/// context.
final SelectionRegistrar? registrar;
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// The delegate for [SelectionEvent]s sent to this selection container.
///
/// The [Selectable]s in the subtree are added or removed from this delegate
/// using [SelectionRegistrar] API.
///
/// This delegate is responsible for updating the selections for the selectables
/// under this widget.
final SelectionContainerDelegate? delegate;
/// Gets the immediate ancestor [SelectionRegistrar] of the [BuildContext].
///
/// If this returns null, either there is no [SelectionContainer] above
/// the [BuildContext] or the immediate [SelectionContainer] is not
/// enabled.
static SelectionRegistrar? maybeOf(BuildContext context) {
final SelectionRegistrarScope? scope = context.dependOnInheritedWidgetOfExactType<SelectionRegistrarScope>();
return scope?.registrar;
}
bool get _disabled => delegate == null;
@override
State<SelectionContainer> createState() => _SelectionContainerState();
}
class _SelectionContainerState extends State<SelectionContainer> with Selectable, SelectionRegistrant {
final Set<VoidCallback> _listeners = <VoidCallback>{};
static const SelectionGeometry _disabledGeometry = SelectionGeometry(
status: SelectionStatus.none,
hasContent: true,
);
@override
void initState() {
super.initState();
if (!widget._disabled) {
widget.delegate!._selectionContainerContext = context;
if (widget.registrar != null) {
registrar = widget.registrar;
}
}
}
@override
void didUpdateWidget(SelectionContainer oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.delegate != widget.delegate) {
if (!oldWidget._disabled) {
oldWidget.delegate!._selectionContainerContext = null;
_listeners.forEach(oldWidget.delegate!.removeListener);
}
if (!widget._disabled) {
widget.delegate!._selectionContainerContext = context;
_listeners.forEach(widget.delegate!.addListener);
}
if (oldWidget.delegate?.value != widget.delegate?.value) {
// Avoid concurrent modification.
for (final VoidCallback listener in _listeners.toList(growable: false)) {
listener();
}
}
}
if (widget._disabled) {
registrar = null;
} else if (widget.registrar != null) {
registrar = widget.registrar;
}
assert(!widget._disabled || registrar == null);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (widget.registrar == null && !widget._disabled) {
registrar = SelectionContainer.maybeOf(context);
}
assert(!widget._disabled || registrar == null);
}
@override
void addListener(VoidCallback listener) {
assert(!widget._disabled);
widget.delegate!.addListener(listener);
_listeners.add(listener);
}
@override
void removeListener(VoidCallback listener) {
widget.delegate?.removeListener(listener);
_listeners.remove(listener);
}
@override
void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) {
assert(!widget._disabled);
widget.delegate!.pushHandleLayers(startHandle, endHandle);
}
@override
SelectedContent? getSelectedContent() {
assert(!widget._disabled);
return widget.delegate!.getSelectedContent();
}
@override
SelectionResult dispatchSelectionEvent(SelectionEvent event) {
assert(!widget._disabled);
return widget.delegate!.dispatchSelectionEvent(event);
}
@override
SelectionGeometry get value {
if (widget._disabled) {
return _disabledGeometry;
}
return widget.delegate!.value;
}
@override
Matrix4 getTransformTo(RenderObject? ancestor) {
assert(!widget._disabled);
return context.findRenderObject()!.getTransformTo(ancestor);
}
@override
Size get size => (context.findRenderObject()! as RenderBox).size;
@override
List<Rect> get boundingBoxes => <Rect>[(context.findRenderObject()! as RenderBox).paintBounds];
@override
void dispose() {
if (!widget._disabled) {
widget.delegate!._selectionContainerContext = null;
_listeners.forEach(widget.delegate!.removeListener);
}
super.dispose();
}
@override
Widget build(BuildContext context) {
if (widget._disabled) {
return SelectionRegistrarScope._disabled(child: widget.child);
}
return SelectionRegistrarScope(
registrar: widget.delegate!,
child: widget.child,
);
}
}
/// An inherited widget to host a [SelectionRegistrar] for the subtree.
///
/// Use [SelectionContainer.maybeOf] to get the SelectionRegistrar from
/// a context.
///
/// This widget is automatically created as part of [SelectionContainer] and
/// is generally not used directly, except for disabling selection for a part
/// of subtree. In that case, one can wrap the subtree with
/// [SelectionContainer.disabled].
class SelectionRegistrarScope extends InheritedWidget {
/// Creates a selection registrar scope that host the [registrar].
const SelectionRegistrarScope({
super.key,
required SelectionRegistrar this.registrar,
required super.child,
});
/// Creates a selection registrar scope that disables selection for the
/// subtree.
const SelectionRegistrarScope._disabled({
required super.child,
}) : registrar = null;
/// The [SelectionRegistrar] hosted by this widget.
final SelectionRegistrar? registrar;
@override
bool updateShouldNotify(SelectionRegistrarScope oldWidget) {
return oldWidget.registrar != registrar;
}
}
/// A delegate to handle [SelectionEvent]s for a [SelectionContainer].
///
/// This delegate needs to implement [SelectionRegistrar] to register
/// [Selectable]s in the [SelectionContainer] subtree.
abstract class SelectionContainerDelegate implements SelectionHandler, SelectionRegistrar {
BuildContext? _selectionContainerContext;
/// Gets the paint transform from the [Selectable] child to
/// [SelectionContainer] of this delegate.
///
/// Returns a matrix that maps the [Selectable] paint coordinate system to the
/// coordinate system of [SelectionContainer].
///
/// Can only be called after [SelectionContainer] is laid out.
Matrix4 getTransformFrom(Selectable child) {
assert(
_selectionContainerContext?.findRenderObject() != null,
'getTransformFrom cannot be called before SelectionContainer is laid out.',
);
return child.getTransformTo(_selectionContainerContext!.findRenderObject()! as RenderBox);
}
/// Gets the paint transform from the [SelectionContainer] of this delegate to
/// the `ancestor`.
///
/// Returns a matrix that maps the [SelectionContainer] paint coordinate
/// system to the coordinate system of `ancestor`.
///
/// If `ancestor` is null, this method returns a matrix that maps from the
/// local paint coordinate system to the coordinate system of the
/// [PipelineOwner.rootNode].
///
/// Can only be called after [SelectionContainer] is laid out.
Matrix4 getTransformTo(RenderObject? ancestor) {
assert(
_selectionContainerContext?.findRenderObject() != null,
'getTransformTo cannot be called before SelectionContainer is laid out.',
);
final RenderBox box = _selectionContainerContext!.findRenderObject()! as RenderBox;
return box.getTransformTo(ancestor);
}
/// Whether the [SelectionContainer] has undergone layout and has a size.
///
/// See also:
///
/// * [RenderBox.hasSize], which is used internally by this method.
bool get hasSize {
assert(
_selectionContainerContext?.findRenderObject() != null,
'The _selectionContainerContext must have a renderObject, such as after the first build has completed.',
);
final RenderBox box = _selectionContainerContext!.findRenderObject()! as RenderBox;
return box.hasSize;
}
/// Gets the size of the [SelectionContainer] of this delegate.
///
/// Can only be called after [SelectionContainer] is laid out.
Size get containerSize {
assert(
hasSize,
'containerSize cannot be called before SelectionContainer is laid out.',
);
final RenderBox box = _selectionContainerContext!.findRenderObject()! as RenderBox;
return box.size;
}
}
| flutter/packages/flutter/lib/src/widgets/selection_container.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/selection_container.dart",
"repo_id": "flutter",
"token_count": 3315
} | 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/painting.dart';
import 'package:flutter/services.dart'
show SpellCheckResults, SpellCheckService, SuggestionSpan, TextEditingValue;
import 'editable_text.dart' show EditableTextContextMenuBuilder;
/// Controls how spell check is performed for text input.
///
/// This configuration determines the [SpellCheckService] used to fetch the
/// [List<SuggestionSpan>] spell check results and the [TextStyle] used to
/// mark misspelled words within text input.
@immutable
class SpellCheckConfiguration {
/// Creates a configuration that specifies the service and suggestions handler
/// for spell check.
const SpellCheckConfiguration({
this.spellCheckService,
this.misspelledSelectionColor,
this.misspelledTextStyle,
this.spellCheckSuggestionsToolbarBuilder,
}) : _spellCheckEnabled = true;
/// Creates a configuration that disables spell check.
const SpellCheckConfiguration.disabled()
: _spellCheckEnabled = false,
spellCheckService = null,
spellCheckSuggestionsToolbarBuilder = null,
misspelledTextStyle = null,
misspelledSelectionColor = null;
/// The service used to fetch spell check results for text input.
final SpellCheckService? spellCheckService;
/// The color the paint the selection highlight when spell check is showing
/// suggestions for a misspelled word.
///
/// For example, on iOS, the selection appears red while the spell check menu
/// is showing.
final Color? misspelledSelectionColor;
/// Style used to indicate misspelled words.
///
/// This is nullable to allow style-specific wrappers of [EditableText]
/// to infer this, but this must be specified if this configuration is
/// provided directly to [EditableText] or its construction will fail with an
/// assertion error.
final TextStyle? misspelledTextStyle;
/// Builds the toolbar used to display spell check suggestions for misspelled
/// words.
final EditableTextContextMenuBuilder? spellCheckSuggestionsToolbarBuilder;
final bool _spellCheckEnabled;
/// Whether or not the configuration should enable or disable spell check.
bool get spellCheckEnabled => _spellCheckEnabled;
/// Returns a copy of the current [SpellCheckConfiguration] instance with
/// specified overrides.
SpellCheckConfiguration copyWith({
SpellCheckService? spellCheckService,
Color? misspelledSelectionColor,
TextStyle? misspelledTextStyle,
EditableTextContextMenuBuilder? spellCheckSuggestionsToolbarBuilder}) {
if (!_spellCheckEnabled) {
// A new configuration should be constructed to enable spell check.
return const SpellCheckConfiguration.disabled();
}
return SpellCheckConfiguration(
spellCheckService: spellCheckService ?? this.spellCheckService,
misspelledSelectionColor: misspelledSelectionColor ?? this.misspelledSelectionColor,
misspelledTextStyle: misspelledTextStyle ?? this.misspelledTextStyle,
spellCheckSuggestionsToolbarBuilder : spellCheckSuggestionsToolbarBuilder ?? this.spellCheckSuggestionsToolbarBuilder,
);
}
@override
String toString() {
return '${objectRuntimeType(this, 'SpellCheckConfiguration')}('
'${_spellCheckEnabled ? 'enabled' : 'disabled'}, '
'service: $spellCheckService, '
'text style: $misspelledTextStyle, '
'toolbar builder: $spellCheckSuggestionsToolbarBuilder'
')';
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is SpellCheckConfiguration
&& other.spellCheckService == spellCheckService
&& other.misspelledTextStyle == misspelledTextStyle
&& other.spellCheckSuggestionsToolbarBuilder == spellCheckSuggestionsToolbarBuilder
&& other._spellCheckEnabled == _spellCheckEnabled;
}
@override
int get hashCode => Object.hash(spellCheckService, misspelledTextStyle, spellCheckSuggestionsToolbarBuilder, _spellCheckEnabled);
}
// Methods for displaying spell check results:
/// Adjusts spell check results to correspond to [newText] if the only results
/// that the handler has access to are the [results] corresponding to
/// [resultsText].
///
/// Used in the case where the request for the spell check results of the
/// [newText] is lagging in order to avoid display of incorrect results.
List<SuggestionSpan> _correctSpellCheckResults(
String newText, String resultsText, List<SuggestionSpan> results) {
final List<SuggestionSpan> correctedSpellCheckResults = <SuggestionSpan>[];
int spanPointer = 0;
int offset = 0;
// Assumes that the order of spans has not been jumbled for optimization
// purposes, and will only search since the previously found span.
int searchStart = 0;
while (spanPointer < results.length) {
final SuggestionSpan currentSpan = results[spanPointer];
final String currentSpanText =
resultsText.substring(currentSpan.range.start, currentSpan.range.end);
final int spanLength = currentSpan.range.end - currentSpan.range.start;
// Try finding SuggestionSpan from resultsText in new text.
final String escapedText = RegExp.escape(currentSpanText);
final RegExp currentSpanTextRegexp = RegExp('\\b$escapedText\\b');
final int foundIndex = newText.substring(searchStart).indexOf(currentSpanTextRegexp);
// Check whether word was found exactly where expected or elsewhere in the newText.
final bool currentSpanFoundExactly = currentSpan.range.start == foundIndex + searchStart;
final bool currentSpanFoundExactlyWithOffset = currentSpan.range.start + offset == foundIndex + searchStart;
final bool currentSpanFoundElsewhere = foundIndex >= 0;
if (currentSpanFoundExactly || currentSpanFoundExactlyWithOffset) {
// currentSpan was found at the same index in newText and resultsText
// or at the same index with the previously calculated adjustment by
// the offset value, so apply it to new text by adding it to the list of
// corrected results.
final SuggestionSpan adjustedSpan = SuggestionSpan(
TextRange(
start: currentSpan.range.start + offset,
end: currentSpan.range.end + offset,
),
currentSpan.suggestions,
);
// Start search for the next misspelled word at the end of currentSpan.
searchStart = currentSpan.range.end + 1 + offset;
correctedSpellCheckResults.add(adjustedSpan);
} else if (currentSpanFoundElsewhere) {
// Word was pushed forward but not modified.
final int adjustedSpanStart = searchStart + foundIndex;
final int adjustedSpanEnd = adjustedSpanStart + spanLength;
final SuggestionSpan adjustedSpan = SuggestionSpan(
TextRange(start: adjustedSpanStart, end: adjustedSpanEnd),
currentSpan.suggestions,
);
// Start search for the next misspelled word at the end of the
// adjusted currentSpan.
searchStart = adjustedSpanEnd + 1;
// Adjust offset to reflect the difference between where currentSpan
// was positioned in resultsText versus in newText.
offset = adjustedSpanStart - currentSpan.range.start;
correctedSpellCheckResults.add(adjustedSpan);
}
spanPointer++;
}
return correctedSpellCheckResults;
}
/// Builds the [TextSpan] tree given the current state of the text input and
/// spell check results.
///
/// The [value] is the current [TextEditingValue] requested to be rendered
/// by a text input widget. The [composingWithinCurrentTextRange] value
/// represents whether or not there is a valid composing region in the
/// [value]. The [style] is the [TextStyle] to render the [value]'s text with,
/// and the [misspelledTextStyle] is the [TextStyle] to render misspelled
/// words within the [value]'s text with. The [spellCheckResults] are the
/// results of spell checking the [value]'s text.
TextSpan buildTextSpanWithSpellCheckSuggestions(
TextEditingValue value,
bool composingWithinCurrentTextRange,
TextStyle? style,
TextStyle misspelledTextStyle,
SpellCheckResults spellCheckResults) {
List<SuggestionSpan> spellCheckResultsSpans =
spellCheckResults.suggestionSpans;
final String spellCheckResultsText = spellCheckResults.spellCheckedText;
if (spellCheckResultsText != value.text) {
spellCheckResultsSpans = _correctSpellCheckResults(
value.text, spellCheckResultsText, spellCheckResultsSpans);
}
// We will draw the TextSpan tree based on the composing region, if it is
// available.
// TODO(camsim99): The two separate strategies for building TextSpan trees
// based on the availability of a composing region should be merged:
// https://github.com/flutter/flutter/issues/124142.
final bool shouldConsiderComposingRegion = defaultTargetPlatform == TargetPlatform.android;
if (shouldConsiderComposingRegion) {
return TextSpan(
style: style,
children: _buildSubtreesWithComposingRegion(
spellCheckResultsSpans,
value,
style,
misspelledTextStyle,
composingWithinCurrentTextRange,
),
);
}
return TextSpan(
style: style,
children: _buildSubtreesWithoutComposingRegion(
spellCheckResultsSpans,
value,
style,
misspelledTextStyle,
value.selection.baseOffset,
),
);
}
/// Builds the [TextSpan] tree for spell check without considering the composing
/// region. Instead, uses the cursor to identify the word that's actively being
/// edited and shouldn't be spell checked. This is useful for platforms and IMEs
/// that don't use the composing region for the active word.
List<TextSpan> _buildSubtreesWithoutComposingRegion(
List<SuggestionSpan>? spellCheckSuggestions,
TextEditingValue value,
TextStyle? style,
TextStyle misspelledStyle,
int cursorIndex,
) {
final List<TextSpan> textSpanTreeChildren = <TextSpan>[];
int textPointer = 0;
int currentSpanPointer = 0;
int endIndex;
final String text = value.text;
final TextStyle misspelledJointStyle =
style?.merge(misspelledStyle) ?? misspelledStyle;
bool cursorInCurrentSpan = false;
// Add text interwoven with any misspelled words to the tree.
if (spellCheckSuggestions != null) {
while (textPointer < text.length &&
currentSpanPointer < spellCheckSuggestions.length) {
final SuggestionSpan currentSpan = spellCheckSuggestions[currentSpanPointer];
if (currentSpan.range.start > textPointer) {
endIndex = currentSpan.range.start < text.length
? currentSpan.range.start
: text.length;
textSpanTreeChildren.add(
TextSpan(
style: style,
text: text.substring(textPointer, endIndex),
)
);
textPointer = endIndex;
} else {
endIndex =
currentSpan.range.end < text.length ? currentSpan.range.end : text.length;
cursorInCurrentSpan = currentSpan.range.start <= cursorIndex && currentSpan.range.end >= cursorIndex;
textSpanTreeChildren.add(
TextSpan(
style: cursorInCurrentSpan
? style
: misspelledJointStyle,
text: text.substring(currentSpan.range.start, endIndex),
)
);
textPointer = endIndex;
currentSpanPointer++;
}
}
}
// Add any remaining text to the tree if applicable.
if (textPointer < text.length) {
textSpanTreeChildren.add(
TextSpan(
style: style,
text: text.substring(textPointer, text.length),
)
);
}
return textSpanTreeChildren;
}
/// Builds [TextSpan] subtree for text with misspelled words with logic based on
/// a valid composing region.
List<TextSpan> _buildSubtreesWithComposingRegion(
List<SuggestionSpan>? spellCheckSuggestions,
TextEditingValue value,
TextStyle? style,
TextStyle misspelledStyle,
bool composingWithinCurrentTextRange) {
final List<TextSpan> textSpanTreeChildren = <TextSpan>[];
int textPointer = 0;
int currentSpanPointer = 0;
int endIndex;
SuggestionSpan currentSpan;
final String text = value.text;
final TextRange composingRegion = value.composing;
final TextStyle composingTextStyle =
style?.merge(const TextStyle(decoration: TextDecoration.underline)) ??
const TextStyle(decoration: TextDecoration.underline);
final TextStyle misspelledJointStyle =
style?.merge(misspelledStyle) ?? misspelledStyle;
bool textPointerWithinComposingRegion = false;
bool currentSpanIsComposingRegion = false;
// Add text interwoven with any misspelled words to the tree.
if (spellCheckSuggestions != null) {
while (textPointer < text.length &&
currentSpanPointer < spellCheckSuggestions.length) {
currentSpan = spellCheckSuggestions[currentSpanPointer];
if (currentSpan.range.start > textPointer) {
endIndex = currentSpan.range.start < text.length
? currentSpan.range.start
: text.length;
textPointerWithinComposingRegion =
composingRegion.start >= textPointer &&
composingRegion.end <= endIndex &&
!composingWithinCurrentTextRange;
if (textPointerWithinComposingRegion) {
_addComposingRegionTextSpans(textSpanTreeChildren, text, textPointer,
composingRegion, style, composingTextStyle);
textSpanTreeChildren.add(
TextSpan(
style: style,
text: text.substring(composingRegion.end, endIndex),
)
);
} else {
textSpanTreeChildren.add(
TextSpan(
style: style,
text: text.substring(textPointer, endIndex),
)
);
}
textPointer = endIndex;
} else {
endIndex =
currentSpan.range.end < text.length ? currentSpan.range.end : text.length;
currentSpanIsComposingRegion = textPointer >= composingRegion.start &&
endIndex <= composingRegion.end &&
!composingWithinCurrentTextRange;
textSpanTreeChildren.add(
TextSpan(
style: currentSpanIsComposingRegion
? composingTextStyle
: misspelledJointStyle,
text: text.substring(currentSpan.range.start, endIndex),
)
);
textPointer = endIndex;
currentSpanPointer++;
}
}
}
// Add any remaining text to the tree if applicable.
if (textPointer < text.length) {
if (textPointer < composingRegion.start &&
!composingWithinCurrentTextRange) {
_addComposingRegionTextSpans(textSpanTreeChildren, text, textPointer,
composingRegion, style, composingTextStyle);
if (composingRegion.end != text.length) {
textSpanTreeChildren.add(
TextSpan(
style: style,
text: text.substring(composingRegion.end, text.length),
)
);
}
} else {
textSpanTreeChildren.add(
TextSpan(
style: style, text: text.substring(textPointer, text.length),
)
);
}
}
return textSpanTreeChildren;
}
/// Helper method to create [TextSpan] tree children for specified range of
/// text up to and including the composing region.
void _addComposingRegionTextSpans(
List<TextSpan> treeChildren,
String text,
int start,
TextRange composingRegion,
TextStyle? style,
TextStyle composingTextStyle) {
treeChildren.add(
TextSpan(
style: style,
text: text.substring(start, composingRegion.start),
)
);
treeChildren.add(
TextSpan(
style: composingTextStyle,
text: text.substring(composingRegion.start, composingRegion.end),
)
);
}
| flutter/packages/flutter/lib/src/widgets/spell_check.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/spell_check.dart",
"repo_id": "flutter",
"token_count": 5512
} | 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:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'actions.dart';
import 'focus_manager.dart';
import 'framework.dart';
import 'text_editing_intents.dart';
/// Provides undo/redo capabilities for a [ValueNotifier].
///
/// Listens to [value] and saves relevant values for undoing/redoing. The
/// cadence at which values are saved is a best approximation of the native
/// behaviors of a number of hardware keyboard on Flutter's desktop
/// platforms, as there are subtle differences between each of the platforms.
///
/// Listens to keyboard undo/redo shortcuts and calls [onTriggered] when a
/// shortcut is triggered that would affect the state of the [value].
///
/// The [child] must manage focus on the [focusNode]. For example, using a
/// [TextField] or [Focus] widget.
class UndoHistory<T> extends StatefulWidget {
/// Creates an instance of [UndoHistory].
const UndoHistory({
super.key,
this.shouldChangeUndoStack,
required this.value,
required this.onTriggered,
required this.focusNode,
this.undoStackModifier,
this.controller,
required this.child,
});
/// The value to track over time.
final ValueNotifier<T> value;
/// Called when checking whether a value change should be pushed onto
/// the undo stack.
final bool Function(T? oldValue, T newValue)? shouldChangeUndoStack;
/// Called right before a new entry is pushed to the undo stack.
///
/// The value returned from this method will be pushed to the stack instead
/// of the original value.
///
/// If null then the original value will always be pushed to the stack.
final T Function(T value)? undoStackModifier;
/// Called when an undo or redo causes a state change.
///
/// If the state would still be the same before and after the undo/redo, this
/// will not be called. For example, receiving a redo when there is nothing
/// to redo will not call this method.
///
/// Changes to the [value] while this method is running will not be recorded
/// on the undo stack. For example, a [TextInputFormatter] may change the value
/// from what was on the undo stack, but this new value will not be recorded,
/// as that would wipe out the redo history.
final void Function(T value) onTriggered;
/// The [FocusNode] that will be used to listen for focus to set the initial
/// undo state for the element.
final FocusNode focusNode;
/// {@template flutter.widgets.undoHistory.controller}
/// Controls the undo state.
///
/// If null, this widget will create its own [UndoHistoryController].
/// {@endtemplate}
final UndoHistoryController? controller;
/// The child widget of [UndoHistory].
final Widget child;
@override
State<UndoHistory<T>> createState() => UndoHistoryState<T>();
}
/// State for a [UndoHistory].
///
/// Provides [undo], [redo], [canUndo], and [canRedo] for programmatic access
/// to the undo state for custom undo and redo UI implementations.
@visibleForTesting
class UndoHistoryState<T> extends State<UndoHistory<T>> with UndoManagerClient {
final _UndoStack<T> _stack = _UndoStack<T>();
late final _Throttled<T> _throttledPush;
Timer? _throttleTimer;
bool _duringTrigger = false;
// This duration was chosen as a best fit for the behavior of Mac, Linux,
// and Windows undo/redo state save durations, but it is not perfect for any
// of them.
static const Duration _kThrottleDuration = Duration(milliseconds: 500);
// Record the last value to prevent pushing multiple
// of the same value in a row onto the undo stack. For example, _push gets
// called both in initState and when the EditableText receives focus.
T? _lastValue;
UndoHistoryController? _controller;
UndoHistoryController get _effectiveController => widget.controller ?? (_controller ??= UndoHistoryController());
@override
void undo() {
if (_stack.currentValue == null) {
// Returns early if there is not a first value registered in the history.
// This is important because, if an undo is received while the initial
// value is being pushed (a.k.a when the field gets the focus but the
// throttling delay is pending), the initial push should not be canceled.
return;
}
if (_throttleTimer?.isActive ?? false) {
_throttleTimer?.cancel(); // Cancel ongoing push, if any.
_update(_stack.currentValue);
} else {
_update(_stack.undo());
}
_updateState();
}
@override
void redo() {
_update(_stack.redo());
_updateState();
}
@override
bool get canUndo => _stack.canUndo;
@override
bool get canRedo => _stack.canRedo;
void _updateState() {
_effectiveController.value = UndoHistoryValue(canUndo: canUndo, canRedo: canRedo);
if (defaultTargetPlatform != TargetPlatform.iOS) {
return;
}
if (UndoManager.client == this) {
UndoManager.setUndoState(canUndo: canUndo, canRedo: canRedo);
}
}
void _undoFromIntent(UndoTextIntent intent) {
undo();
}
void _redoFromIntent(RedoTextIntent intent) {
redo();
}
void _update(T? nextValue) {
if (nextValue == null) {
return;
}
if (nextValue == _lastValue) {
return;
}
_lastValue = nextValue;
_duringTrigger = true;
try {
widget.onTriggered(nextValue);
assert(widget.value.value == nextValue);
} finally {
_duringTrigger = false;
}
}
void _push() {
if (widget.value.value == _lastValue) {
return;
}
if (_duringTrigger) {
return;
}
if (!(widget.shouldChangeUndoStack?.call(_lastValue, widget.value.value) ?? true)) {
return;
}
final T nextValue = widget.undoStackModifier?.call(widget.value.value) ?? widget.value.value;
if (nextValue == _lastValue) {
return;
}
_lastValue = nextValue;
_throttleTimer = _throttledPush(nextValue);
}
void _handleFocus() {
if (!widget.focusNode.hasFocus) {
return;
}
UndoManager.client = this;
_updateState();
}
@override
void handlePlatformUndo(UndoDirection direction) {
switch (direction) {
case UndoDirection.undo:
undo();
case UndoDirection.redo:
redo();
}
}
@override
void initState() {
super.initState();
_throttledPush = _throttle<T>(
duration: _kThrottleDuration,
function: (T currentValue) {
_stack.push(currentValue);
_updateState();
},
);
_push();
widget.value.addListener(_push);
_handleFocus();
widget.focusNode.addListener(_handleFocus);
_effectiveController.onUndo.addListener(undo);
_effectiveController.onRedo.addListener(redo);
}
@override
void didUpdateWidget(UndoHistory<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.value != oldWidget.value) {
_stack.clear();
oldWidget.value.removeListener(_push);
widget.value.addListener(_push);
}
if (widget.focusNode != oldWidget.focusNode) {
oldWidget.focusNode.removeListener(_handleFocus);
widget.focusNode.addListener(_handleFocus);
}
if (widget.controller != oldWidget.controller) {
_effectiveController.onUndo.removeListener(undo);
_effectiveController.onRedo.removeListener(redo);
_controller?.dispose();
_controller = null;
_effectiveController.onUndo.addListener(undo);
_effectiveController.onRedo.addListener(redo);
}
}
@override
void dispose() {
widget.value.removeListener(_push);
widget.focusNode.removeListener(_handleFocus);
_effectiveController.onUndo.removeListener(undo);
_effectiveController.onRedo.removeListener(redo);
_controller?.dispose();
_throttleTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Actions(
actions: <Type, Action<Intent>>{
UndoTextIntent: Action<UndoTextIntent>.overridable(context: context, defaultAction: CallbackAction<UndoTextIntent>(onInvoke: _undoFromIntent)),
RedoTextIntent: Action<RedoTextIntent>.overridable(context: context, defaultAction: CallbackAction<RedoTextIntent>(onInvoke: _redoFromIntent)),
},
child: widget.child,
);
}
}
/// Represents whether the current undo stack can undo or redo.
@immutable
class UndoHistoryValue {
/// Creates a value for whether the current undo stack can undo or redo.
///
/// The [canUndo] and [canRedo] arguments must have a value, but default to
/// false.
const UndoHistoryValue({this.canUndo = false, this.canRedo = false});
/// A value corresponding to an undo stack that can neither undo nor redo.
static const UndoHistoryValue empty = UndoHistoryValue();
/// Whether the current undo stack can perform an undo operation.
final bool canUndo;
/// Whether the current undo stack can perform a redo operation.
final bool canRedo;
@override
String toString() => '${objectRuntimeType(this, 'UndoHistoryValue')}(canUndo: $canUndo, canRedo: $canRedo)';
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is UndoHistoryValue && other.canUndo == canUndo && other.canRedo == canRedo;
}
@override
int get hashCode => Object.hash(
canUndo.hashCode,
canRedo.hashCode,
);
}
/// A controller for the undo history, for example for an editable text field.
///
/// Whenever a change happens to the underlying value that the [UndoHistory]
/// widget tracks, that widget updates the [value] and the controller notifies
/// it's listeners. Listeners can then read the canUndo and canRedo
/// properties of the value to discover whether [undo] or [redo] are possible.
///
/// The controller also has [undo] and [redo] methods to modify the undo
/// history.
///
/// {@tool dartpad}
/// This example creates a [TextField] with an [UndoHistoryController]
/// which provides undo and redo buttons.
///
/// ** See code in examples/api/lib/widgets/undo_history/undo_history_controller.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [EditableText], which uses the [UndoHistory] widget and allows
/// control of the underlying history using an [UndoHistoryController].
class UndoHistoryController extends ValueNotifier<UndoHistoryValue> {
/// Creates a controller for an [UndoHistory] widget.
UndoHistoryController({UndoHistoryValue? value}) : super(value ?? UndoHistoryValue.empty);
/// Notifies listeners that [undo] has been called.
final ChangeNotifier onUndo = ChangeNotifier();
/// Notifies listeners that [redo] has been called.
final ChangeNotifier onRedo = ChangeNotifier();
/// Reverts the value on the stack to the previous value.
void undo() {
if (!value.canUndo) {
return;
}
onUndo.notifyListeners();
}
/// Updates the value on the stack to the next value.
void redo() {
if (!value.canRedo) {
return;
}
onRedo.notifyListeners();
}
@override
void dispose() {
onUndo.dispose();
onRedo.dispose();
super.dispose();
}
}
/// A data structure representing a chronological list of states that can be
/// undone and redone.
class _UndoStack<T> {
/// Creates an instance of [_UndoStack].
_UndoStack();
final List<T> _list = <T>[];
// The index of the current value, or -1 if the list is empty.
int _index = -1;
/// Returns the current value of the stack.
T? get currentValue => _list.isEmpty ? null : _list[_index];
bool get canUndo => _list.isNotEmpty && _index > 0;
bool get canRedo => _list.isNotEmpty && _index < _list.length - 1;
/// Add a new state change to the stack.
///
/// Pushing identical objects will not create multiple entries.
void push(T value) {
if (_list.isEmpty) {
_index = 0;
_list.add(value);
return;
}
assert(_index < _list.length && _index >= 0);
if (value == currentValue) {
return;
}
// If anything has been undone in this stack, remove those irrelevant states
// before adding the new one.
if (_index != _list.length - 1) {
_list.removeRange(_index + 1, _list.length);
}
_list.add(value);
_index = _list.length - 1;
}
/// Returns the current value after an undo operation.
///
/// An undo operation moves the current value to the previously pushed value,
/// if any.
///
/// Iff the stack is completely empty, then returns null.
T? undo() {
if (_list.isEmpty) {
return null;
}
assert(_index < _list.length && _index >= 0);
if (_index != 0) {
_index = _index - 1;
}
return currentValue;
}
/// Returns the current value after a redo operation.
///
/// A redo operation moves the current value to the value that was last
/// undone, if any.
///
/// Iff the stack is completely empty, then returns null.
T? redo() {
if (_list.isEmpty) {
return null;
}
assert(_index < _list.length && _index >= 0);
if (_index < _list.length - 1) {
_index = _index + 1;
}
return currentValue;
}
/// Remove everything from the stack.
void clear() {
_list.clear();
_index = -1;
}
@override
String toString() {
return '_UndoStack $_list';
}
}
/// A function that can be throttled with the throttle function.
typedef _Throttleable<T> = void Function(T currentArg);
/// A function that has been throttled by [_throttle].
typedef _Throttled<T> = Timer Function(T currentArg);
/// Returns a _Throttled that will call through to the given function only a
/// maximum of once per duration.
///
/// Only works for functions that take exactly one argument and return void.
_Throttled<T> _throttle<T>({
required Duration duration,
required _Throttleable<T> function,
}) {
Timer? timer;
late T arg;
return (T currentArg) {
arg = currentArg;
if (timer != null && timer!.isActive) {
return timer!;
}
timer = Timer(duration, () {
function(arg);
timer = null;
});
return timer!;
};
}
| flutter/packages/flutter/lib/src/widgets/undo_history.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/undo_history.dart",
"repo_id": "flutter",
"token_count": 4751
} | 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/animation.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Disposing controller removes listeners to avoid memory leaks', () {
final _TestAnimationController controller = _TestAnimationController(
duration: const Duration(milliseconds: 100),
vsync: const TestVSync(),
);
int statusListener = 0;
int listener = 0;
controller.addListener(() {
listener++;
});
controller.addStatusListener((AnimationStatus _) {
statusListener++;
});
expect(statusListener, 0);
expect(listener, 0);
controller.publicNotifyListeners();
controller.publicNotifyStatusListeners(AnimationStatus.completed);
expect(statusListener, 1);
expect(listener, 1);
controller.dispose();
controller.publicNotifyListeners();
controller.publicNotifyStatusListeners(AnimationStatus.completed);
expect(statusListener, 1);
expect(listener, 1);
});
}
class _TestAnimationController extends AnimationController {
_TestAnimationController({
super.duration,
required super.vsync,
});
void publicNotifyListeners() {
super.notifyListeners();
}
void publicNotifyStatusListeners(AnimationStatus status) {
super.notifyStatusListeners(status);
}
}
| flutter/packages/flutter/test/animation/animation_controller_listener_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/animation/animation_controller_listener_test.dart",
"repo_id": "flutter",
"token_count": 459
} | 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/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Heroes work', (WidgetTester tester) async {
await tester.pumpWidget(CupertinoApp(
home: ListView(children: <Widget>[
const Hero(tag: 'a', child: Text('foo')),
Builder(builder: (BuildContext context) {
return CupertinoButton(
child: const Text('next'),
onPressed: () {
Navigator.push(
context,
CupertinoPageRoute<void>(builder: (BuildContext context) {
return const Hero(tag: 'a', child: Text('foo'));
}),
);
},
);
}),
]),
));
await tester.tap(find.text('next'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
// During the hero transition, the hero widget is lifted off of both
// page routes and exists as its own overlay on top of both routes.
expect(find.widgetWithText(CupertinoPageRoute, 'foo'), findsNothing);
expect(find.widgetWithText(Navigator, 'foo'), findsOneWidget);
});
testWidgets('Has default cupertino localizations', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: Builder(
builder: (BuildContext context) {
return Column(
children: <Widget>[
Text(CupertinoLocalizations.of(context).selectAllButtonLabel),
Text(CupertinoLocalizations.of(context).datePickerMediumDate(
DateTime(2018, 10, 4),
)),
],
);
},
),
),
);
expect(find.text('Select All'), findsOneWidget);
expect(find.text('Thu Oct 4 '), findsOneWidget);
});
testWidgets('Can use dynamic color', (WidgetTester tester) async {
const CupertinoDynamicColor dynamicColor = CupertinoDynamicColor.withBrightness(
color: Color(0xFF000000),
darkColor: Color(0xFF000001),
);
await tester.pumpWidget(const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
color: dynamicColor,
home: Placeholder(),
));
expect(tester.widget<Title>(find.byType(Title)).color.value, 0xFF000000);
await tester.pumpWidget(const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.dark),
color: dynamicColor,
home: Placeholder(),
));
expect(tester.widget<Title>(find.byType(Title)).color.value, 0xFF000001);
});
testWidgets('Can customize initial routes', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(
CupertinoApp(
navigatorKey: navigatorKey,
onGenerateInitialRoutes: (String initialRoute) {
expect(initialRoute, '/abc');
return <Route<void>>[
PageRouteBuilder<void>(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return const Text('non-regular page one');
},
),
PageRouteBuilder<void>(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return const Text('non-regular page two');
},
),
];
},
initialRoute: '/abc',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => const Text('regular page one'),
'/abc': (BuildContext context) => const Text('regular page two'),
},
),
);
expect(find.text('non-regular page two'), findsOneWidget);
expect(find.text('non-regular page one'), findsNothing);
expect(find.text('regular page one'), findsNothing);
expect(find.text('regular page two'), findsNothing);
navigatorKey.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('non-regular page two'), findsNothing);
expect(find.text('non-regular page one'), findsOneWidget);
expect(find.text('regular page one'), findsNothing);
expect(find.text('regular page two'), findsNothing);
});
testWidgets('CupertinoApp.navigatorKey can be updated', (WidgetTester tester) async {
final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>();
await tester.pumpWidget(CupertinoApp(
navigatorKey: key1,
home: const Placeholder(),
));
expect(key1.currentState, isA<NavigatorState>());
final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>();
await tester.pumpWidget(CupertinoApp(
navigatorKey: key2,
home: const Placeholder(),
));
expect(key2.currentState, isA<NavigatorState>());
expect(key1.currentState, isNull);
});
testWidgets('CupertinoApp.router works', (WidgetTester tester) async {
final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(
uri: Uri.parse('initial'),
),
);
addTearDown(provider.dispose);
final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
builder: (BuildContext context, RouteInformation information) {
return Text(information.uri.toString());
},
onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
delegate.routeInformation = RouteInformation(
uri: Uri.parse('popped'),
);
return route.didPop(result);
},
);
addTearDown(delegate.dispose);
await tester.pumpWidget(CupertinoApp.router(
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
));
expect(find.text('initial'), findsOneWidget);
// Simulate android back button intent.
final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
await tester.pumpAndSettle();
expect(find.text('popped'), findsOneWidget);
});
testWidgets('CupertinoApp.router works with onNavigationNotification', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/139903.
final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(
uri: Uri.parse('initial'),
),
);
addTearDown(provider.dispose);
final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
builder: (BuildContext context, RouteInformation information) {
return Text(information.uri.toString());
},
onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
delegate.routeInformation = RouteInformation(
uri: Uri.parse('popped'),
);
return route.didPop(result);
},
);
addTearDown(delegate.dispose);
int navigationCount = 0;
await tester.pumpWidget(CupertinoApp.router(
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
onNavigationNotification: (NavigationNotification? notification) {
navigationCount += 1;
return true;
},
));
expect(find.text('initial'), findsOneWidget);
expect(navigationCount, greaterThan(0));
final int navigationCountAfterBuild = navigationCount;
// Simulate android back button intent.
final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
await tester.pumpAndSettle();
expect(find.text('popped'), findsOneWidget);
expect(navigationCount, greaterThan(navigationCountAfterBuild));
});
testWidgets('CupertinoApp.router route information parser is optional', (WidgetTester tester) async {
final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
builder: (BuildContext context, RouteInformation information) {
return Text(information.uri.toString());
},
onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
delegate.routeInformation = RouteInformation(
uri: Uri.parse('popped'),
);
return route.didPop(result);
},
);
addTearDown(delegate.dispose);
delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
await tester.pumpWidget(CupertinoApp.router(
routerDelegate: delegate,
));
expect(find.text('initial'), findsOneWidget);
// Simulate android back button intent.
final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
await tester.pumpAndSettle();
expect(find.text('popped'), findsOneWidget);
});
testWidgets('CupertinoApp.router throw if route information provider is provided but no route information parser', (WidgetTester tester) async {
final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
builder: (BuildContext context, RouteInformation information) {
return Text(information.uri.toString());
},
onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
delegate.routeInformation = RouteInformation(
uri: Uri.parse('popped'),
);
return route.didPop(result);
},
);
addTearDown(delegate.dispose);
delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(
uri: Uri.parse('initial'),
),
);
addTearDown(provider.dispose);
await tester.pumpWidget(CupertinoApp.router(
routeInformationProvider: provider,
routerDelegate: delegate,
));
expect(tester.takeException(), isAssertionError);
});
testWidgets('CupertinoApp.router throw if route configuration is provided along with other delegate', (WidgetTester tester) async {
final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
builder: (BuildContext context, RouteInformation information) {
return Text(information.uri.toString());
},
onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
delegate.routeInformation = RouteInformation(
uri: Uri.parse('popped'),
);
return route.didPop(result);
},
);
addTearDown(delegate.dispose);
delegate.routeInformation = RouteInformation(uri: Uri.parse('initial'));
final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(routerDelegate: delegate);
await tester.pumpWidget(CupertinoApp.router(
routerDelegate: delegate,
routerConfig: routerConfig,
));
expect(tester.takeException(), isAssertionError);
});
testWidgets('CupertinoApp.router router config works', (WidgetTester tester) async {
late SimpleNavigatorRouterDelegate delegate;
addTearDown(() => delegate.dispose());
final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(
uri: Uri.parse('initial'),
),
);
addTearDown(provider.dispose);
final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate = SimpleNavigatorRouterDelegate(
builder: (BuildContext context, RouteInformation information) {
return Text(information.uri.toString());
},
onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) {
delegate.routeInformation = RouteInformation(
uri: Uri.parse('popped'),
);
return route.didPop(result);
},
),
backButtonDispatcher: RootBackButtonDispatcher()
);
await tester.pumpWidget(CupertinoApp.router(
routerConfig: routerConfig,
));
expect(find.text('initial'), findsOneWidget);
// Simulate android back button intent.
final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
await tester.pumpAndSettle();
expect(find.text('popped'), findsOneWidget);
});
testWidgets('CupertinoApp has correct default ScrollBehavior', (WidgetTester tester) async {
late BuildContext capturedContext;
await tester.pumpWidget(
CupertinoApp(
home: Builder(
builder: (BuildContext context) {
capturedContext = context;
return const Placeholder();
},
),
),
);
expect(ScrollConfiguration.of(capturedContext).runtimeType, CupertinoScrollBehavior);
});
testWidgets('CupertinoApp has correct default multitouchDragStrategy', (WidgetTester tester) async {
late BuildContext capturedContext;
await tester.pumpWidget(
CupertinoApp(
home: Builder(
builder: (BuildContext context) {
capturedContext = context;
return const Placeholder();
},
),
),
);
final ScrollBehavior scrollBehavior = ScrollConfiguration.of(capturedContext);
expect(scrollBehavior.runtimeType, CupertinoScrollBehavior);
expect(scrollBehavior.getMultitouchDragStrategy(capturedContext), MultitouchDragStrategy.averageBoundaryPointers);
});
testWidgets('A ScrollBehavior can be set for CupertinoApp', (WidgetTester tester) async {
late BuildContext capturedContext;
await tester.pumpWidget(
CupertinoApp(
scrollBehavior: const MockScrollBehavior(),
home: Builder(
builder: (BuildContext context) {
capturedContext = context;
return const Placeholder();
},
),
),
);
final ScrollBehavior scrollBehavior = ScrollConfiguration.of(capturedContext);
expect(scrollBehavior.runtimeType, MockScrollBehavior);
expect(scrollBehavior.getScrollPhysics(capturedContext).runtimeType, NeverScrollableScrollPhysics);
});
testWidgets('When `useInheritedMediaQuery` is true an existing MediaQuery is used if one is available', (WidgetTester tester) async {
late BuildContext capturedContext;
final UniqueKey uniqueKey = UniqueKey();
await tester.pumpWidget(
MediaQuery(
key: uniqueKey,
data: const MediaQueryData(),
child: CupertinoApp(
useInheritedMediaQuery: true,
builder: (BuildContext context, Widget? child) {
capturedContext = context;
return const Placeholder();
},
color: const Color(0xFF123456),
),
),
);
expect(capturedContext.dependOnInheritedWidgetOfExactType<MediaQuery>()?.key, uniqueKey);
});
testWidgets('Text color is correctly resolved when CupertinoThemeData.brightness is null', (WidgetTester tester) async {
debugBrightnessOverride = Brightness.dark;
await tester.pumpWidget(
const CupertinoApp(
home: CupertinoPageScaffold(
child: Text('Hello'),
),
),
);
final RenderParagraph paragraph = tester.renderObject(find.text('Hello'));
final CupertinoDynamicColor textColor = paragraph.text.style!.color! as CupertinoDynamicColor;
// App with non-null brightness, so resolving color
// doesn't depend on the MediaQuery.platformBrightness.
late BuildContext capturedContext;
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(
brightness: Brightness.dark,
),
home: Builder(
builder: (BuildContext context) {
capturedContext = context;
return const Placeholder();
},
),
),
);
// We expect the string representations of the colors to have darkColor indicated (*) as effective color.
// (color = Color(0xff000000), *darkColor = Color(0xffffffff)*, resolved by: Builder)
expect(textColor.toString(), CupertinoColors.label.resolveFrom(capturedContext).toString());
debugBrightnessOverride = null;
});
testWidgets('Cursor color is resolved when CupertinoThemeData.brightness is null', (WidgetTester tester) async {
debugBrightnessOverride = Brightness.dark;
RenderEditable findRenderEditable(WidgetTester tester) {
final RenderObject root = tester.renderObject(find.byType(EditableText));
expect(root, isNotNull);
RenderEditable? renderEditable;
void recursiveFinder(RenderObject child) {
if (child is RenderEditable) {
renderEditable = child;
return;
}
child.visitChildren(recursiveFinder);
}
root.visitChildren(recursiveFinder);
expect(renderEditable, isNotNull);
return renderEditable!;
}
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
final TextEditingController controller = TextEditingController();
addTearDown(controller.dispose);
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(
primaryColor: CupertinoColors.activeOrange,
),
home: CupertinoPageScaffold(
child: Builder(
builder: (BuildContext context) {
return EditableText(
backgroundCursorColor: DefaultSelectionStyle.of(context).selectionColor!,
cursorColor: DefaultSelectionStyle.of(context).cursorColor!,
controller: controller,
focusNode: focusNode,
style: const TextStyle(),
);
},
),
),
),
);
final RenderEditable editableText = findRenderEditable(tester);
final Color cursorColor = editableText.cursorColor!;
// Cursor color should be equal to the dark variant of the primary color.
// Alpha value needs to be 0, because cursor is not visible by default.
expect(cursorColor, CupertinoColors.activeOrange.darkColor.withAlpha(0));
debugBrightnessOverride = null;
});
testWidgets('Assert in buildScrollbar that controller != null when using it', (WidgetTester tester) async {
const ScrollBehavior defaultBehavior = CupertinoScrollBehavior();
late BuildContext capturedContext;
await tester.pumpWidget(ScrollConfiguration(
// Avoid the default ones here.
behavior: const CupertinoScrollBehavior().copyWith(scrollbars: false),
child: SingleChildScrollView(
child: Builder(
builder: (BuildContext context) {
capturedContext = context;
return Container(height: 1000.0);
},
),
),
));
const ScrollableDetails details = ScrollableDetails(direction: AxisDirection.down);
final Widget child = Container();
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.iOS:
// Does not throw if we aren't using it.
defaultBehavior.buildScrollbar(capturedContext, child, details);
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
expect(
() {
defaultBehavior.buildScrollbar(capturedContext, child, details);
},
throwsA(
isA<AssertionError>().having((AssertionError error) => error.toString(),
'description', contains('details.controller != null')),
),
);
}
}, variant: TargetPlatformVariant.all());
}
class MockScrollBehavior extends ScrollBehavior {
const MockScrollBehavior();
@override
ScrollPhysics getScrollPhysics(BuildContext context) => const NeverScrollableScrollPhysics();
}
typedef SimpleRouterDelegateBuilder = Widget Function(BuildContext context, RouteInformation information);
typedef SimpleNavigatorRouterDelegatePopPage<T> = bool Function(Route<T> route, T result, SimpleNavigatorRouterDelegate delegate);
class SimpleRouteInformationParser extends RouteInformationParser<RouteInformation> {
SimpleRouteInformationParser();
@override
Future<RouteInformation> parseRouteInformation(RouteInformation information) {
return SynchronousFuture<RouteInformation>(information);
}
@override
RouteInformation restoreRouteInformation(RouteInformation configuration) {
return configuration;
}
}
class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> with PopNavigatorRouterDelegateMixin<RouteInformation>, ChangeNotifier {
SimpleNavigatorRouterDelegate({
required this.builder,
this.onPopPage,
});
@override
GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
RouteInformation get routeInformation => _routeInformation;
late RouteInformation _routeInformation;
set routeInformation(RouteInformation newValue) {
_routeInformation = newValue;
notifyListeners();
}
SimpleRouterDelegateBuilder builder;
SimpleNavigatorRouterDelegatePopPage<void>? onPopPage;
@override
Future<void> setNewRoutePath(RouteInformation configuration) {
_routeInformation = configuration;
return SynchronousFuture<void>(null);
}
bool _handlePopPage(Route<void> route, void data) {
return onPopPage!(route, data, this);
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
onPopPage: _handlePopPage,
pages: <Page<void>>[
// We need at least two pages for the pop to propagate through.
// Otherwise, the navigator will bubble the pop to the system navigator.
const CupertinoPage<void>(
child: Text('base'),
),
CupertinoPage<void>(
key: ValueKey<String?>(routeInformation.uri.toString()),
child: builder(context, routeInformation),
),
],
);
}
}
| flutter/packages/flutter/test/cupertino/app_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/app_test.dart",
"repo_id": "flutter",
"token_count": 8453
} | 660 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('shows title', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoListTile(
title: title,
),
),
),
);
expect(tester.widget<Text>(find.byType(Text)), title);
expect(find.text('CupertinoListTile'), findsOneWidget);
});
testWidgets('shows subtitle', (WidgetTester tester) async {
const Widget subtitle = Text('CupertinoListTile subtitle');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoListTile(
title: Icon(CupertinoIcons.add),
subtitle: subtitle,
),
),
),
);
expect(tester.widget<Text>(find.byType(Text)), subtitle);
expect(find.text('CupertinoListTile subtitle'), findsOneWidget);
});
testWidgets('shows additionalInfo', (WidgetTester tester) async {
const Widget additionalInfo = Text('Not Connected');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoListTile(
title: Icon(CupertinoIcons.add),
additionalInfo: additionalInfo,
),
),
),
);
expect(tester.widget<Text>(find.byType(Text)), additionalInfo);
expect(find.text('Not Connected'), findsOneWidget);
});
testWidgets('shows trailing', (WidgetTester tester) async {
const Widget trailing = CupertinoListTileChevron();
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoListTile(
title: Icon(CupertinoIcons.add),
trailing: trailing,
),
),
),
);
expect(tester.widget<CupertinoListTileChevron>(find.byType(CupertinoListTileChevron)), trailing);
});
testWidgets('shows leading', (WidgetTester tester) async {
const Widget leading = Icon(CupertinoIcons.add);
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoListTile(
leading: leading,
title: Text('CupertinoListTile'),
),
),
),
);
expect(tester.widget<Icon>(find.byType(Icon)), leading);
});
testWidgets('sets backgroundColor', (WidgetTester tester) async {
const Color backgroundColor = CupertinoColors.systemRed;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: CupertinoListSection(
children: const <Widget>[
CupertinoListTile(
title: Text('CupertinoListTile'),
backgroundColor: backgroundColor,
),
],
),
),
),
);
// Container inside CupertinoListTile is the second one in row.
final Container container = tester.widgetList<Container>(find.byType(Container)).elementAt(1);
expect(container.color, backgroundColor);
});
testWidgets('does not change backgroundColor when tapped if onTap is not provided', (WidgetTester tester) async {
const Color backgroundColor = CupertinoColors.systemBlue;
const Color backgroundColorActivated = CupertinoColors.systemRed;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: CupertinoListSection(
children: const <Widget>[
CupertinoListTile(
title: Text('CupertinoListTile'),
backgroundColor: backgroundColor,
backgroundColorActivated: backgroundColorActivated,
),
],
),
),
),
);
await tester.tap(find.byType(CupertinoListTile));
await tester.pump();
// Container inside CupertinoListTile is the second one in row.
final Container container = tester.widgetList<Container>(find.byType(Container)).elementAt(1);
expect(container.color, backgroundColor);
});
testWidgets('changes backgroundColor when tapped if onTap is provided', (WidgetTester tester) async {
const Color backgroundColor = CupertinoColors.systemBlue;
const Color backgroundColorActivated = CupertinoColors.systemRed;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: CupertinoListSection(
children: <Widget>[
CupertinoListTile(
title: const Text('CupertinoListTile'),
backgroundColor: backgroundColor,
backgroundColorActivated: backgroundColorActivated,
onTap: () async { await Future<void>.delayed(const Duration(milliseconds: 1), () {}); },
),
],
),
),
),
);
// Container inside CupertinoListTile is the second one in row.
Container container = tester.widgetList<Container>(find.byType(Container)).elementAt(1);
expect(container.color, backgroundColor);
// Pump only one frame so the color change persists.
await tester.tap(find.byType(CupertinoListTile));
await tester.pump();
// Container inside CupertinoListTile is the second one in row.
container = tester.widgetList<Container>(find.byType(Container)).elementAt(1);
expect(container.color, backgroundColorActivated);
// Pump the rest of the frames to complete the test.
await tester.pumpAndSettle();
});
testWidgets('does not contain GestureDetector if onTap is not provided', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: CupertinoListSection(
children: const <Widget>[
CupertinoListTile(
title: Text('CupertinoListTile'),
),
],
),
),
),
);
// Container inside CupertinoListTile is the second one in row.
expect(find.byType(GestureDetector), findsNothing);
});
testWidgets('contains GestureDetector if onTap is provided', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: CupertinoListSection(
children: <Widget>[
CupertinoListTile(
title: const Text('CupertinoListTile'),
onTap: () async {},
),
],
),
),
),
);
// Container inside CupertinoListTile is the second one in row.
expect(find.byType(GestureDetector), findsOneWidget);
});
testWidgets('resets the background color when navigated back', (WidgetTester tester) async {
const Color backgroundColor = CupertinoColors.systemBlue;
const Color backgroundColorActivated = CupertinoColors.systemRed;
await tester.pumpWidget(
CupertinoApp(
home: Builder(
builder: (BuildContext context) {
final Widget secondPage = Center(
child: CupertinoButton(
child: const Text('Go back'),
onPressed: () => Navigator.of(context).pop<void>(),
),
);
return Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child:CupertinoListTile(
title: const Text('CupertinoListTile'),
backgroundColor: backgroundColor,
backgroundColorActivated: backgroundColorActivated,
onTap: () => Navigator.of(context).push(CupertinoPageRoute<Widget>(
builder: (BuildContext context) => secondPage,
)),
),
),
),
);
},
),
),
);
// Navigate to second page.
await tester.tap(find.byType(CupertinoListTile));
await tester.pumpAndSettle();
// Go back to first page.
await tester.tap(find.byType(CupertinoButton));
await tester.pumpAndSettle();
// Container inside CupertinoListTile is the second one in row.
final Container container = tester.widget<Container>(find.byType(Container));
expect(container.color, backgroundColor);
});
group('alignment of widgets for left-to-right', () {
testWidgets('leading is on the left of title', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile');
const Widget leading = Icon(CupertinoIcons.add);
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: CupertinoListTile(
title: title,
leading: leading,
),
),
),
),
);
final Offset foundTitle = tester.getTopLeft(find.byType(Text));
final Offset foundLeading = tester.getTopRight(find.byType(Icon));
expect(foundTitle.dx > foundLeading.dx, true);
});
testWidgets('subtitle is placed below title and aligned on left', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile title');
const Widget subtitle = Text('CupertinoListTile subtitle');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: CupertinoListTile(
title: title,
subtitle: subtitle,
),
),
),
),
);
final Offset foundTitle = tester.getBottomLeft(find.text('CupertinoListTile title'));
final Offset foundSubtitle = tester.getTopLeft(find.text('CupertinoListTile subtitle'));
expect(foundTitle.dx, equals(foundSubtitle.dx));
expect(foundTitle.dy < foundSubtitle.dy, isTrue);
});
testWidgets('additionalInfo is on the right of title', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile');
const Widget additionalInfo = Text('Not Connected');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: CupertinoListTile(
title: title,
additionalInfo: additionalInfo,
),
),
),
),
);
final Offset foundTitle = tester.getTopRight(find.text('CupertinoListTile'));
final Offset foundInfo = tester.getTopLeft(find.text('Not Connected'));
expect(foundTitle.dx < foundInfo.dx, isTrue);
});
testWidgets('trailing is on the right of additionalInfo', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile');
const Widget additionalInfo = Text('Not Connected');
const Widget trailing = CupertinoListTileChevron();
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: CupertinoListTile(
title: title,
additionalInfo: additionalInfo,
trailing: trailing,
),
),
),
),
);
final Offset foundInfo = tester.getTopRight(find.text('Not Connected'));
final Offset foundTrailing = tester.getTopLeft(find.byType(CupertinoListTileChevron));
expect(foundInfo.dx < foundTrailing.dx, isTrue);
});
});
group('alignment of widgets for right-to-left', () {
testWidgets('leading is on the right of title', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile');
const Widget leading = Icon(CupertinoIcons.add);
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.rtl,
child: CupertinoListTile(
title: title,
leading: leading,
),
),
),
),
);
final Offset foundTitle = tester.getTopRight(find.byType(Text));
final Offset foundLeading = tester.getTopLeft(find.byType(Icon));
expect(foundTitle.dx < foundLeading.dx, true);
});
testWidgets('subtitle is placed below title and aligned on right', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile title');
const Widget subtitle = Text('CupertinoListTile subtitle');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.rtl,
child: CupertinoListTile(
title: title,
subtitle: subtitle,
),
),
),
),
);
final Offset foundTitle = tester.getBottomRight(find.text('CupertinoListTile title'));
final Offset foundSubtitle = tester.getTopRight(find.text('CupertinoListTile subtitle'));
expect(foundTitle.dx, equals(foundSubtitle.dx));
expect(foundTitle.dy < foundSubtitle.dy, isTrue);
});
testWidgets('additionalInfo is on the left of title', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile');
const Widget additionalInfo = Text('Not Connected');
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.rtl,
child: CupertinoListTile(
title: title,
additionalInfo: additionalInfo,
),
),
),
),
);
final Offset foundTitle = tester.getTopLeft(find.text('CupertinoListTile'));
final Offset foundInfo = tester.getTopRight(find.text('Not Connected'));
expect(foundTitle.dx > foundInfo.dx, isTrue);
});
testWidgets('trailing is on the left of additionalInfo', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile');
const Widget additionalInfo = Text('Not Connected');
const Widget trailing = CupertinoListTileChevron();
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: Directionality(
textDirection: TextDirection.rtl,
child: CupertinoListTile(
title: title,
additionalInfo: additionalInfo,
trailing: trailing,
),
),
),
),
);
final Offset foundInfo = tester.getTopLeft(find.text('Not Connected'));
final Offset foundTrailing = tester.getTopRight(find.byType(CupertinoListTileChevron));
expect(foundInfo.dx > foundTrailing.dx, isTrue);
});
});
testWidgets('onTap with delay does not throw an exception', (WidgetTester tester) async {
const Widget title = Text('CupertinoListTile');
bool showTile = true;
Future<void> onTap() async {
showTile = false;
await Future<void>.delayed(
const Duration(seconds: 1),
() => showTile = true,
);
}
Widget buildCupertinoListTile() {
return CupertinoApp(
home: CupertinoPageScaffold(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (showTile)
CupertinoListTile(
onTap: onTap,
title: title,
),
],
),
),
),
);
}
await tester.pumpWidget(buildCupertinoListTile());
expect(showTile, isTrue);
await tester.tap(find.byType(CupertinoListTile));
expect(showTile, isFalse);
await tester.pumpWidget(buildCupertinoListTile());
await tester.pumpAndSettle(const Duration(seconds: 5));
expect(tester.takeException(), null);
});
testWidgets('title does not overflow', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: CupertinoPageScaffold(
child: CupertinoListTile(
title: Text('CupertinoListTile' * 10),
),
),
),
);
expect(tester.takeException(), null);
});
testWidgets('subtitle does not overflow', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: CupertinoPageScaffold(
child: CupertinoListTile(
title: const Text(''),
subtitle: Text('CupertinoListTile' * 10),
),
),
),
);
expect(tester.takeException(), null);
});
}
| flutter/packages/flutter/test/cupertino/list_tile_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/list_tile_test.dart",
"repo_id": "flutter",
"token_count": 7663
} | 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.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
RenderBox getRenderSegmentedControl(WidgetTester tester) {
return tester.allRenderObjects.firstWhere(
(RenderObject currentObject) {
return currentObject.toStringShort().contains('_RenderSegmentedControl');
},
) as RenderBox;
}
StatefulBuilder setupSimpleSegmentedControl() {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
int sharedValue = 0;
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
);
}
Widget boilerplate({ required Widget child }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(child: child),
);
}
int getChildCount(WidgetTester tester) {
return (getRenderSegmentedControl(tester) as RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>>)
.getChildrenAsList().length;
}
ui.RRect getSurroundingRect(WidgetTester tester, {int child = 0}) {
return ((getRenderSegmentedControl(tester) as RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>>)
.getChildrenAsList()[child].parentData! as dynamic).surroundingRect as ui.RRect;
}
Size getChildSize(WidgetTester tester, {int child = 0}) {
return (getRenderSegmentedControl(tester) as RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>>)
.getChildrenAsList()[child].size;
}
Color getBorderColor(WidgetTester tester) {
return (getRenderSegmentedControl(tester) as dynamic).borderColor as Color;
}
int? getSelectedIndex(WidgetTester tester) {
return (getRenderSegmentedControl(tester) as dynamic).selectedIndex as int?;
}
Color getBackgroundColor(WidgetTester tester, int childIndex) {
// Using dynamic so the test can access a private class.
// ignore: avoid_dynamic_calls
return (getRenderSegmentedControl(tester) as dynamic).backgroundColors[childIndex] as Color;
}
void main() {
testWidgets('Tap changes toggle state', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
children[2] = const Text('Child 3');
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
expect(sharedValue, 0);
await tester.tap(find.byKey(const ValueKey<String>('Segmented Control')));
expect(sharedValue, 1);
});
testWidgets('Need at least 2 children', (WidgetTester tester) async {
await expectLater(
() => tester.pumpWidget(
boilerplate(
child: CupertinoSegmentedControl<int>(
children: const <int, Widget>{},
onValueChanged: (int newValue) { },
),
),
),
throwsA(isAssertionError.having(
(AssertionError error) => error.toString(),
'.toString()',
contains('children.length'),
)),
);
await expectLater(
() => tester.pumpWidget(
boilerplate(
child: CupertinoSegmentedControl<int>(
children: const <int, Widget>{0: Text('Child 1')},
onValueChanged: (int newValue) { },
),
),
),
throwsA(isAssertionError.having(
(AssertionError error) => error.toString(),
'.toString()',
contains('children.length'),
)),
);
});
testWidgets('Padding works', (WidgetTester tester) async {
const Key key = Key('Container');
final Map<int, Widget> children = <int, Widget>{};
children[0] = const SizedBox(
height: double.infinity,
child: Text('Child 1'),
) ;
children[1] = const SizedBox(
height: double.infinity,
child: Text('Child 2'),
) ;
Future<void> verifyPadding({ EdgeInsets? padding }) async {
final EdgeInsets effectivePadding = padding ?? const EdgeInsets.symmetric(horizontal: 16);
final Rect segmentedControlRect = tester.getRect(find.byKey(key));
expect(
tester.getTopLeft(find.byWidget(children[0]!)),
segmentedControlRect.topLeft.translate(
effectivePadding.topLeft.dx,
effectivePadding.topLeft.dy,
),
);
expect(
tester.getBottomLeft(find.byWidget(children[0]!)),
segmentedControlRect.bottomLeft.translate(
effectivePadding.bottomLeft.dx,
effectivePadding.bottomLeft.dy,
),
);
expect(
tester.getTopRight(find.byWidget(children[1]!)),
segmentedControlRect.topRight.translate(
effectivePadding.topRight.dx,
effectivePadding.topRight.dy,
),
);
expect(
tester.getBottomRight(find.byWidget(children[1]!)),
segmentedControlRect.bottomRight.translate(
effectivePadding.bottomRight.dx,
effectivePadding.bottomRight.dy,
),
);
}
await tester.pumpWidget(
boilerplate(
child: CupertinoSegmentedControl<int>(
key: key,
children: children,
onValueChanged: (int newValue) { },
),
),
);
// Default padding works.
await verifyPadding();
// Switch to Child 2 padding should remain the same.
await tester.tap(find.text('Child 2'));
await tester.pumpAndSettle();
await verifyPadding();
await tester.pumpWidget(
boilerplate(
child: CupertinoSegmentedControl<int>(
key: key,
padding: const EdgeInsets.fromLTRB(1, 3, 5, 7),
children: children,
onValueChanged: (int newValue) { },
),
),
);
// Custom padding works.
await verifyPadding(padding: const EdgeInsets.fromLTRB(1, 3, 5, 7));
// Switch back to Child 1 padding should remain the same.
await tester.tap(find.text('Child 1'));
await tester.pumpAndSettle();
await verifyPadding(padding: const EdgeInsets.fromLTRB(1, 3, 5, 7));
});
testWidgets('Value attribute must be the key of one of the children widgets', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
await expectLater(
() => tester.pumpWidget(
boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) { },
groupValue: 2,
),
),
),
throwsA(isAssertionError.having(
(AssertionError error) => error.toString(),
'.toString()',
contains('children'),
)),
);
});
testWidgets('Widgets have correct default text/icon styles, change correctly on selection', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Icon(IconData(1));
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
await tester.pumpAndSettle();
DefaultTextStyle textStyle = tester.widget(find.widgetWithText(DefaultTextStyle, 'Child 1'));
IconTheme iconTheme = tester.widget(find.widgetWithIcon(IconTheme, const IconData(1)));
expect(textStyle.style.color, isSameColorAs(CupertinoColors.white));
expect(iconTheme.data.color, CupertinoColors.activeBlue);
await tester.tap(find.widgetWithIcon(IconTheme, const IconData(1)));
await tester.pumpAndSettle();
textStyle = tester.widget(find.widgetWithText(DefaultTextStyle, 'Child 1'));
iconTheme = tester.widget(find.widgetWithIcon(IconTheme, const IconData(1)));
expect(textStyle.style.color, CupertinoColors.activeBlue);
expect(iconTheme.data.color, isSameColorAs(CupertinoColors.white));
});
testWidgets(
'Segmented controls respects themes',
(WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Icon(IconData(1));
int sharedValue = 0;
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
);
},
),
),
);
DefaultTextStyle textStyle = tester.widget(find.widgetWithText(DefaultTextStyle, 'Child 1').first);
IconThemeData iconTheme = IconTheme.of(tester.element(find.byIcon(const IconData(1))));
expect(textStyle.style.color, isSameColorAs(CupertinoColors.black));
expect(iconTheme.color, isSameColorAs(CupertinoColors.systemBlue.darkColor));
await tester.tap(find.byIcon(const IconData(1)));
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
textStyle = tester.widget(find.widgetWithText(DefaultTextStyle, 'Child 1').first);
iconTheme = IconTheme.of(tester.element(find.byIcon(const IconData(1))));
expect(textStyle.style.color, isSameColorAs(CupertinoColors.systemBlue.darkColor));
expect(iconTheme.color, isSameColorAs(CupertinoColors.black));
},
);
testWidgets('SegmentedControl is correct when user provides custom colors', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Icon(IconData(1));
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
unselectedColor: CupertinoColors.lightBackgroundGray,
selectedColor: CupertinoColors.activeGreen.color,
borderColor: CupertinoColors.black,
pressedColor: const Color(0x638CFC7B),
),
);
},
),
);
DefaultTextStyle textStyle = tester.widget(find.widgetWithText(DefaultTextStyle, 'Child 1'));
IconTheme iconTheme = tester.widget(find.widgetWithIcon(IconTheme, const IconData(1)));
expect(getBorderColor(tester), CupertinoColors.black);
expect(textStyle.style.color, CupertinoColors.lightBackgroundGray);
expect(iconTheme.data.color, CupertinoColors.activeGreen.color);
expect(getBackgroundColor(tester, 0), CupertinoColors.activeGreen.color);
expect(getBackgroundColor(tester, 1), CupertinoColors.lightBackgroundGray);
await tester.tap(find.widgetWithIcon(IconTheme, const IconData(1)));
await tester.pumpAndSettle();
textStyle = tester.widget(find.widgetWithText(DefaultTextStyle, 'Child 1'));
iconTheme = tester.widget(find.widgetWithIcon(IconTheme, const IconData(1)));
expect(textStyle.style.color, CupertinoColors.activeGreen.color);
expect(iconTheme.data.color, CupertinoColors.lightBackgroundGray);
expect(getBackgroundColor(tester, 0), CupertinoColors.lightBackgroundGray);
expect(getBackgroundColor(tester, 1), CupertinoColors.activeGreen.color);
final Offset center = tester.getCenter(find.text('Child 1'));
final TestGesture gesture = await tester.startGesture(center);
await tester.pumpAndSettle();
expect(getBackgroundColor(tester, 0), const Color(0x638CFC7B));
expect(getBackgroundColor(tester, 1), CupertinoColors.activeGreen.color);
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
});
testWidgets('Widgets are centered within segments', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 200.0,
height: 200.0,
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) { },
),
),
),
),
);
// Widgets are centered taking into account 16px of horizontal padding
expect(tester.getCenter(find.text('Child 1')), const Offset(58.0, 100.0));
expect(tester.getCenter(find.text('Child 2')), const Offset(142.0, 100.0));
});
testWidgets('Tap calls onValueChanged', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
bool value = false;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
value = true;
},
),
);
},
),
);
expect(value, isFalse);
await tester.tap(find.text('Child 2'));
expect(value, isTrue);
});
testWidgets('State does not change if onValueChanged does not call setState()', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
const int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) { },
groupValue: sharedValue,
),
);
},
),
);
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
await tester.tap(find.text('Child 2'));
await tester.pump();
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
});
testWidgets(
'Background color of child should change on selection, '
'and should not change when tapped again',
(WidgetTester tester) async {
await tester.pumpWidget(setupSimpleSegmentedControl());
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
await tester.tap(find.text('Child 2'));
await tester.pumpAndSettle(const Duration(milliseconds: 200));
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
await tester.tap(find.text('Child 2'));
await tester.pump();
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
},
);
testWidgets(
'Children can be non-Text or Icon widgets (in this case, '
'a Container or Placeholder widget)',
(WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = Container(
constraints: const BoxConstraints.tightFor(width: 50.0, height: 50.0),
);
children[2] = const Placeholder();
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
},
);
testWidgets('Passed in value is child initially selected', (WidgetTester tester) async {
await tester.pumpWidget(setupSimpleSegmentedControl());
expect(getSelectedIndex(tester), 0);
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
});
testWidgets('Null input for value results in no child initially selected', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
int? sharedValue;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
expect(getSelectedIndex(tester), null);
expect(getBackgroundColor(tester, 0), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
});
testWidgets('Long press changes background color of not-selected child', (WidgetTester tester) async {
await tester.pumpWidget(setupSimpleSegmentedControl());
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
final Offset center = tester.getCenter(find.text('Child 2'));
final TestGesture gesture = await tester.startGesture(center);
await tester.pumpAndSettle();
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), const Color(0x33007aff));
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
});
testWidgets('Long press does not change background color of currently-selected child', (WidgetTester tester) async {
await tester.pumpWidget(setupSimpleSegmentedControl());
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
final Offset center = tester.getCenter(find.text('Child 1'));
final TestGesture gesture = await tester.startGesture(center);
await tester.pumpAndSettle();
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
});
testWidgets('Height of segmented control is determined by tallest widget', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = Container(
constraints: const BoxConstraints.tightFor(height: 100.0),
);
children[1] = Container(
constraints: const BoxConstraints.tightFor(height: 400.0),
);
children[2] = Container(
constraints: const BoxConstraints.tightFor(height: 200.0),
);
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) { },
),
);
},
),
);
final RenderBox buttonBox = tester.renderObject(find.byKey(const ValueKey<String>('Segmented Control')));
expect(buttonBox.size.height, 400.0);
});
testWidgets('Width of each segmented control segment is determined by widest widget', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = Container(
constraints: const BoxConstraints.tightFor(width: 50.0),
);
children[1] = Container(
constraints: const BoxConstraints.tightFor(width: 100.0),
);
children[2] = Container(
constraints: const BoxConstraints.tightFor(width: 200.0),
);
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) { },
),
);
},
),
);
final RenderBox segmentedControl = tester.renderObject(find.byKey(const ValueKey<String>('Segmented Control')));
// Subtract the 16.0px from each side. Remaining width should be allocated
// to each child equally.
final double childWidth = (segmentedControl.size.width - 32.0) / 3;
expect(childWidth, 200.0);
expect(childWidth, getSurroundingRect(tester).width);
expect(childWidth, getSurroundingRect(tester, child: 1).width);
expect(childWidth, getSurroundingRect(tester, child: 2).width);
});
testWidgets('Width is finite in unbounded space', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: Row(
children: <Widget>[
CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) { },
),
],
),
);
},
),
);
final RenderBox segmentedControl = tester.renderObject(find.byKey(const ValueKey<String>('Segmented Control')));
expect(segmentedControl.size.width.isFinite, isTrue);
});
testWidgets('Directionality test - RTL should reverse order of widgets', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) { },
),
),
),
);
expect(tester.getTopRight(find.text('Child 1')).dx > tester.getTopRight(find.text('Child 2')).dx, isTrue);
});
testWidgets('Correct initial selection and toggling behavior - RTL', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
),
);
},
),
);
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
await tester.tap(find.text('Child 2'));
await tester.pumpAndSettle();
expect(getBackgroundColor(tester, 0), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
await tester.tap(find.text('Child 2'));
await tester.pump();
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
});
testWidgets('Segmented control semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
),
);
},
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
label: 'Child 1',
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.isInMutuallyExclusiveGroup,
SemanticsFlag.isSelected,
],
actions: <SemanticsAction>[
SemanticsAction.tap,
],
),
TestSemantics.rootChild(
label: 'Child 2',
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.isInMutuallyExclusiveGroup,
],
actions: <SemanticsAction>[
SemanticsAction.tap,
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
),
);
await tester.tap(find.text('Child 2'));
await tester.pump();
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
label: 'Child 1',
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.isInMutuallyExclusiveGroup,
],
actions: <SemanticsAction>[
SemanticsAction.tap,
],
),
TestSemantics.rootChild(
label: 'Child 2',
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.isInMutuallyExclusiveGroup,
SemanticsFlag.isSelected,
],
actions: <SemanticsAction>[
SemanticsAction.tap,
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
),
);
semantics.dispose();
});
testWidgets('Non-centered taps work on smaller widgets', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
int sharedValue = 1;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
expect(sharedValue, 1);
final double childWidth = getChildSize(tester).width;
final Offset centerOfSegmentedControl = tester.getCenter(find.text('Child 1'));
// Tap just inside segment bounds
await tester.tapAt(
Offset(
centerOfSegmentedControl.dx + (childWidth / 2) - 10.0,
centerOfSegmentedControl.dy,
),
);
expect(sharedValue, 0);
});
testWidgets('Hit-tests report accurate local position in segments', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
late TapDownDetails tapDownDetails;
children[0] = GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (TapDownDetails details) { tapDownDetails = details; },
child: const SizedBox(width: 200, height: 200),
);
children[1] = const Text('Child 2');
int sharedValue = 1;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
expect(sharedValue, 1);
final Offset segment0GlobalOffset = tester.getTopLeft(find.byWidget(children[0]!));
await tester.tapAt(segment0GlobalOffset + const Offset(7, 11));
expect(tapDownDetails.localPosition, const Offset(7, 11));
expect(tapDownDetails.globalPosition, segment0GlobalOffset + const Offset(7, 11));
});
testWidgets(
'Segment still hittable with a child that has no hitbox',
(WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/57326.
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const SizedBox();
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
expect(sharedValue, 0);
final Offset centerOfTwo = tester.getCenter(find.byWidget(children[1]!));
// Tap within the bounds of children[1], but not at the center.
// children[1] is a SizedBox thus not hittable by itself.
await tester.tapAt(centerOfTwo + const Offset(10, 0));
expect(sharedValue, 1);
},
);
testWidgets('Animation is correct when the selected segment changes', (WidgetTester tester) async {
await tester.pumpWidget(setupSimpleSegmentedControl());
await tester.tap(find.text('Child 2'));
await tester.pump();
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), const Color(0x33007aff));
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), const Color(0xff3d9aff));
expect(getBackgroundColor(tester, 1), const Color(0x64007aff));
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), const Color(0xff7bbaff));
expect(getBackgroundColor(tester, 1), const Color(0x95007aff));
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), const Color(0xffb9daff));
expect(getBackgroundColor(tester, 1), const Color(0xc7007aff));
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), const Color(0xfff7faff));
expect(getBackgroundColor(tester, 1), const Color(0xf8007aff));
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
});
testWidgets('Animation is correct when widget is rebuilt', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('Child 1');
children[1] = const Text('Child 2');
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
await tester.tap(find.text('Child 2'));
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), const Color(0x33007aff));
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
duration: const Duration(milliseconds: 40),
);
expect(getBackgroundColor(tester, 0), const Color(0xff3d9aff));
expect(getBackgroundColor(tester, 1), const Color(0x64007aff));
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
duration: const Duration(milliseconds: 40),
);
expect(getBackgroundColor(tester, 0), const Color(0xff7bbaff));
expect(getBackgroundColor(tester, 1), const Color(0x95007aff));
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
duration: const Duration(milliseconds: 40),
);
expect(getBackgroundColor(tester, 0), const Color(0xffb9daff));
expect(getBackgroundColor(tester, 1), const Color(0xc7007aff));
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
duration: const Duration(milliseconds: 40),
);
expect(getBackgroundColor(tester, 0), const Color(0xfff7faff));
expect(getBackgroundColor(tester, 1), const Color(0xf8007aff));
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
duration: const Duration(milliseconds: 40),
);
expect(getBackgroundColor(tester, 0), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
});
testWidgets('Multiple segments are pressed', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('A');
children[1] = const Text('B');
children[2] = const Text('C');
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.text('B')));
await tester.pumpAndSettle(const Duration(milliseconds: 200));
expect(getBackgroundColor(tester, 1), const Color(0x33007aff));
expect(getBackgroundColor(tester, 2), isSameColorAs(CupertinoColors.white));
final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.text('C')));
await tester.pumpAndSettle(const Duration(milliseconds: 200));
// Press on C has no effect while B is held down.
expect(getBackgroundColor(tester, 1), const Color(0x33007aff));
expect(getBackgroundColor(tester, 2), isSameColorAs(CupertinoColors.white));
// Finish gesture to release resources.
await gesture1.up();
await gesture2.up();
await tester.pumpAndSettle();
});
testWidgets('Transition is triggered while a transition is already occurring', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('A');
children[1] = const Text('B');
children[2] = const Text('C');
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
},
groupValue: sharedValue,
),
);
},
),
);
await tester.tap(find.text('B'));
await tester.pump();
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), const Color(0x33007aff));
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), const Color(0xff3d9aff));
expect(getBackgroundColor(tester, 1), const Color(0x64007aff));
// While A to B transition is occurring, press on C.
await tester.tap(find.text('C'));
await tester.pump();
// A and B are now both transitioning to white.
expect(getBackgroundColor(tester, 0), const Color(0xff3d9aff));
expect(getBackgroundColor(tester, 1), const Color(0xffc1deff));
expect(getBackgroundColor(tester, 2), const Color(0x33007aff));
await tester.pump(const Duration(milliseconds: 40));
// B background color has reached unselected state.
expect(getBackgroundColor(tester, 0), const Color(0xff7bbaff));
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 2), const Color(0x64007aff));
await tester.pump(const Duration(milliseconds: 100));
// A background color has reached unselected state.
expect(getBackgroundColor(tester, 0), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 2), const Color(0xe0007aff));
await tester.pump(const Duration(milliseconds: 40));
// C background color has reached selected state.
expect(getBackgroundColor(tester, 2), CupertinoColors.activeBlue);
});
testWidgets('Segment is selected while it is transitioning to unselected state', (WidgetTester tester) async {
await tester.pumpWidget(setupSimpleSegmentedControl());
await tester.tap(find.text('Child 2'));
await tester.pump();
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), const Color(0x33007aff));
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), const Color(0xff3d9aff));
expect(getBackgroundColor(tester, 1), const Color(0x64007aff));
// While A to B transition is occurring, press on A again.
await tester.tap(find.text('Child 1'));
await tester.pump();
// Both transitions start to reverse.
expect(getBackgroundColor(tester, 0), const Color(0xcd007aff));
expect(getBackgroundColor(tester, 1), const Color(0xffc1deff));
await tester.pump(const Duration(milliseconds: 40));
// A and B finish transitioning.
expect(getBackgroundColor(tester, 0), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
});
testWidgets('Add segment while animation is running', (WidgetTester tester) async {
Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('A');
children[1] = const Text('B');
children[2] = const Text('C');
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
if (sharedValue == 1) {
children = Map<int, Widget>.from(children);
children[3] = const Text('D');
}
},
groupValue: sharedValue,
),
);
},
),
);
await tester.tap(find.text('B'));
await tester.pump();
expect(getBackgroundColor(tester, 0), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 3), isSameColorAs(CupertinoColors.white));
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 3), isSameColorAs(CupertinoColors.white));
await tester.pump(const Duration(milliseconds: 150));
expect(getBackgroundColor(tester, 0), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
expect(getBackgroundColor(tester, 3), isSameColorAs(CupertinoColors.white));
});
testWidgets('Remove segment while animation is running', (WidgetTester tester) async {
Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('A');
children[1] = const Text('B');
children[2] = const Text('C');
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
if (sharedValue == 1) {
children.remove(2);
children = Map<int, Widget>.from(children);
}
},
groupValue: sharedValue,
),
);
},
),
);
expect(getChildCount(tester), 3);
await tester.tap(find.text('B'));
await tester.pump();
expect(getBackgroundColor(tester, 1), const Color(0x33007aff));
expect(getChildCount(tester), 2);
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 1), const Color(0x64007aff));
await tester.pump(const Duration(milliseconds: 150));
expect(getBackgroundColor(tester, 1), CupertinoColors.activeBlue);
});
testWidgets('Remove currently animating segment', (WidgetTester tester) async {
Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('A');
children[1] = const Text('B');
children[2] = const Text('C');
int? sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() {
sharedValue = newValue;
});
if (sharedValue == 1) {
children.remove(1);
children = Map<int, Widget>.from(children);
sharedValue = null;
}
},
groupValue: sharedValue,
),
);
},
),
);
expect(getChildCount(tester), 3);
await tester.tap(find.text('B'));
await tester.pump();
expect(getChildCount(tester), 2);
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), const Color(0xff3d9aff));
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
await tester.pump(const Duration(milliseconds: 40));
expect(getBackgroundColor(tester, 0), const Color(0xff7bbaff));
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
await tester.pump(const Duration(milliseconds: 100));
expect(getBackgroundColor(tester, 0), isSameColorAs(CupertinoColors.white));
expect(getBackgroundColor(tester, 1), isSameColorAs(CupertinoColors.white));
});
// Regression test: https://github.com/flutter/flutter/issues/43414.
testWidgets("Quick double tap doesn't break the internal state", (WidgetTester tester) async {
const Map<int, Widget> children = <int, Widget>{
0: Text('A'),
1: Text('B'),
2: Text('C'),
};
int sharedValue = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) {
setState(() { sharedValue = newValue; });
},
groupValue: sharedValue,
),
);
},
),
);
await tester.tap(find.text('B'));
// sharedValue has been updated but widget.groupValue is not.
expect(sharedValue, 1);
// Land the second tap before the widget gets a chance to rebuild.
final TestGesture secondTap = await tester.startGesture(tester.getCenter(find.text('B')));
await tester.pump();
await secondTap.up();
expect(sharedValue, 1);
await tester.tap(find.text('C'));
expect(sharedValue, 2);
});
testWidgets('Golden Test Placeholder Widget', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = Container();
children[1] = const Placeholder();
children[2] = Container();
const int currentValue = 0;
await tester.pumpWidget(
RepaintBoundary(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: SizedBox(
width: 800.0,
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) { },
groupValue: currentValue,
),
),
);
},
),
),
);
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('segmented_control_test.0.png'),
);
});
testWidgets('Golden Test Pressed State', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('A');
children[1] = const Text('B');
children[2] = const Text('C');
const int currentValue = 0;
await tester.pumpWidget(
RepaintBoundary(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: SizedBox(
width: 800.0,
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) { },
groupValue: currentValue,
),
),
);
},
),
),
);
final Offset center = tester.getCenter(find.text('B'));
final TestGesture gesture = await tester.startGesture(center);
await tester.pumpAndSettle();
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('segmented_control_test.1.png'),
);
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
});
testWidgets('Hovering over Cupertino segmented control updates cursor to clickable on Web', (WidgetTester tester) async {
final Map<int, Widget> children = <int, Widget>{};
children[0] = const Text('A');
children[1] = const Text('B');
children[2] = const Text('C');
const int currentValue = 0;
await tester.pumpWidget(
RepaintBoundary(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: SizedBox(
width: 800.0,
child: CupertinoSegmentedControl<int>(
key: const ValueKey<String>('Segmented Control'),
children: children,
onValueChanged: (int newValue) { },
groupValue: currentValue,
),
),
);
},
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: const Offset(10, 10));
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
final Offset firstChild = tester.getCenter(find.text('A'));
await gesture.moveTo(firstChild);
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic,
);
});
}
| flutter/packages/flutter/test/cupertino/segmented_control_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/segmented_control_test.dart",
"repo_id": "flutter",
"token_count": 23437
} | 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.
@TestOn('browser')
library;
import 'package:flutter_test/flutter_test.dart';
// Regression test for: https://github.com/dart-lang/sdk/issues/47207
// Needs: https://github.com/dart-lang/sdk/commit/6c4593929f067af259113eae5dc1b3b1c04f1035 to pass.
// Originally here: https://github.com/flutter/engine/pull/28808
void main() {
test('Web library environment define exists', () {
expect(const bool.fromEnvironment('dart.library.js_util'), isTrue);
expect(const bool.fromEnvironment('dart.library.someFooLibrary'), isFalse);
});
}
| flutter/packages/flutter/test/dart/browser_environment_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/dart/browser_environment_test.dart",
"repo_id": "flutter",
"token_count": 236
} | 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 'dart:math';
import 'package:flutter/src/foundation/collections.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('listEquals', () {
final List<int> listA = <int>[1, 2, 3];
final List<int> listB = <int>[1, 2, 3];
final List<int> listC = <int>[1, 2];
final List<int> listD = <int>[3, 2, 1];
expect(listEquals<void>(null, null), isTrue);
expect(listEquals(listA, null), isFalse);
expect(listEquals(null, listB), isFalse);
expect(listEquals(listA, listA), isTrue);
expect(listEquals(listA, listB), isTrue);
expect(listEquals(listA, listC), isFalse);
expect(listEquals(listA, listD), isFalse);
});
test('setEquals', () {
final Set<int> setA = <int>{1, 2, 3};
final Set<int> setB = <int>{1, 2, 3};
final Set<int> setC = <int>{1, 2};
final Set<int> setD = <int>{3, 2, 1};
expect(setEquals<void>(null, null), isTrue);
expect(setEquals(setA, null), isFalse);
expect(setEquals(null, setB), isFalse);
expect(setEquals(setA, setA), isTrue);
expect(setEquals(setA, setB), isTrue);
expect(setEquals(setA, setC), isFalse);
expect(setEquals(setA, setD), isTrue);
});
test('mapEquals', () {
final Map<int, int> mapA = <int, int>{1:1, 2:2, 3:3};
final Map<int, int> mapB = <int, int>{1:1, 2:2, 3:3};
final Map<int, int> mapC = <int, int>{1:1, 2:2};
final Map<int, int> mapD = <int, int>{3:3, 2:2, 1:1};
final Map<int, int> mapE = <int, int>{3:1, 2:2, 1:3};
expect(mapEquals<void, void>(null, null), isTrue);
expect(mapEquals(mapA, null), isFalse);
expect(mapEquals(null, mapB), isFalse);
expect(mapEquals(mapA, mapA), isTrue);
expect(mapEquals(mapA, mapB), isTrue);
expect(mapEquals(mapA, mapC), isFalse);
expect(mapEquals(mapA, mapD), isTrue);
expect(mapEquals(mapA, mapE), isFalse);
});
test('binarySearch', () {
final List<int> items = <int>[1, 2, 3];
expect(binarySearch(items, 1), 0);
expect(binarySearch(items, 2), 1);
expect(binarySearch(items, 3), 2);
expect(binarySearch(items, 12), -1);
});
test('MergeSortRandom', () {
final Random random = Random();
for (int i = 0; i < 250; i += 1) {
// Expect some equal elements.
final List<int> list = List<int>.generate(i, (int j) => random.nextInt(i));
mergeSort(list);
for (int j = 1; j < i; j++) {
expect(list[j - 1], lessThanOrEqualTo(list[j]));
}
}
});
test('MergeSortPreservesOrder', () {
final Random random = Random();
// Small case where only insertion call is called,
// larger case where the internal moving insertion sort is used
// larger cases with multiple splittings, numbers just around a power of 2.
for (final int size in <int>[8, 50, 511, 512, 513]) {
// Class OC compares using id.
// With size elements with id's in the range 0..size/4, a number of
// collisions are guaranteed. These should be sorted so that the 'order'
// part of the objects are still in order.
final List<OrderedComparable> list = List<OrderedComparable>.generate(
size,
(int i) => OrderedComparable(random.nextInt(size >> 2), i),
);
mergeSort(list);
OrderedComparable prev = list[0];
for (int i = 1; i < size; i++) {
final OrderedComparable next = list[i];
expect(prev.id, lessThanOrEqualTo(next.id));
if (next.id == prev.id) {
expect(prev.order, lessThanOrEqualTo(next.order));
}
prev = next;
}
// Reverse compare on part of list.
final List<OrderedComparable> copy = list.toList();
final int min = size >> 2;
final int max = size - min;
mergeSort<OrderedComparable>(
list,
start: min,
end: max,
compare: (OrderedComparable a, OrderedComparable b) => b.compareTo(a),
);
prev = list[min];
for (int i = min + 1; i < max; i++) {
final OrderedComparable next = list[i];
expect(prev.id, greaterThanOrEqualTo(next.id));
if (next.id == prev.id) {
expect(prev.order, lessThanOrEqualTo(next.order));
}
prev = next;
}
// Equals on OC objects is identity, so this means the parts before min,
// and the parts after max, didn't change at all.
expect(list.sublist(0, min), equals(copy.sublist(0, min)));
expect(list.sublist(max), equals(copy.sublist(max)));
}
});
test('MergeSortSpecialCases', () {
for (final int size in <int>[511, 512, 513]) {
// All equal.
final List<OrderedComparable> list = List<OrderedComparable>.generate(size, (int i) => OrderedComparable(0, i));
mergeSort(list);
for (int i = 0; i < size; i++) {
expect(list[i].order, equals(i));
}
// All but one equal, first.
list[0] = OrderedComparable(1, 0);
for (int i = 1; i < size; i++) {
list[i] = OrderedComparable(0, i);
}
mergeSort(list);
for (int i = 0; i < size - 1; i++) {
expect(list[i].order, equals(i + 1));
}
expect(list[size - 1].order, equals(0));
// All but one equal, last.
for (int i = 0; i < size - 1; i++) {
list[i] = OrderedComparable(0, i);
}
list[size - 1] = OrderedComparable(-1, size - 1);
mergeSort(list);
expect(list[0].order, equals(size - 1));
for (int i = 1; i < size; i++) {
expect(list[i].order, equals(i - 1));
}
// Reversed.
for (int i = 0; i < size; i++) {
list[i] = OrderedComparable(size - 1 - i, i);
}
mergeSort(list);
for (int i = 0; i < size; i++) {
expect(list[i].id, equals(i));
expect(list[i].order, equals(size - 1 - i));
}
}
});
}
class OrderedComparable implements Comparable<OrderedComparable> {
OrderedComparable(this.id, this.order);
final int id;
final int order;
@override
int compareTo(OrderedComparable other) => id - other.id;
@override
String toString() => 'OverrideComparable[$id,$order]';
}
| flutter/packages/flutter/test/foundation/collections_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/collections_test.dart",
"repo_id": "flutter",
"token_count": 2674
} | 664 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
class TestFoundationFlutterBinding extends BindingBase {
bool? wasLocked;
@override
Future<void> performReassemble() async {
wasLocked = locked;
return super.performReassemble();
}
}
TestFoundationFlutterBinding binding = TestFoundationFlutterBinding();
void main() {
test('Pointer events are locked during reassemble', () async {
await binding.reassembleApplication();
expect(binding.wasLocked, isTrue);
});
}
| flutter/packages/flutter/test/foundation/reassemble_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/reassemble_test.dart",
"repo_id": "flutter",
"token_count": 215
} | 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' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class TestResult {
bool dragStarted = false;
bool dragUpdate = false;
bool dragEnd = false;
}
class NestedScrollableCase extends StatelessWidget {
const NestedScrollableCase({super.key, required this.testResult});
final TestResult testResult;
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverFixedExtentList(
itemExtent: 50.0,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container(
alignment: Alignment.center,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onVerticalDragDown: (DragDownDetails details) {
testResult.dragStarted = true;
},
onVerticalDragUpdate: (DragUpdateDetails details){
testResult.dragUpdate = true;
},
onVerticalDragEnd: (_) {},
child: Text('List Item $index', key: ValueKey<int>(index),
),
),
);
},
),
),
],
),
);
}
}
class NestedDraggableCase extends StatelessWidget {
const NestedDraggableCase({super.key, required this.testResult});
final TestResult testResult;
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverFixedExtentList(
itemExtent: 50.0,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container(
alignment: Alignment.center,
child: Draggable<Object>(
key: ValueKey<int>(index),
feedback: const Text('Dragging'),
child: Text('List Item $index'),
onDragStarted: () {
testResult.dragStarted = true;
},
onDragUpdate: (DragUpdateDetails details){
testResult.dragUpdate = true;
},
onDragEnd: (_) {
testResult.dragEnd = true;
},
),
);
},
),
),
],
),
);
}
}
void main() {
testWidgets('Scroll Views get the same ScrollConfiguration as GestureDetectors', (WidgetTester tester) async {
tester.view.gestureSettings = const ui.GestureSettings(physicalTouchSlop: 4);
addTearDown(tester.view.reset);
final TestResult result = TestResult();
await tester.pumpWidget(MaterialApp(
title: 'Scroll Bug',
home: NestedScrollableCase(testResult: result),
));
// By dragging the scroll view more than the configured touch slop above but less than
// the framework default value, we demonstrate that this causes gesture detectors
// that do not receive the same gesture settings to fire at different times than would
// be expected.
final Offset start = tester.getCenter(find.byKey(const ValueKey<int>(1)));
await tester.timedDragFrom(start, const Offset(0, 5), const Duration(milliseconds: 50));
await tester.pumpAndSettle();
expect(result.dragStarted, true);
expect(result.dragUpdate, true);
});
testWidgets('Scroll Views get the same ScrollConfiguration as Draggables', (WidgetTester tester) async {
tester.view.gestureSettings = const ui.GestureSettings(physicalTouchSlop: 4);
addTearDown(tester.view.reset);
final TestResult result = TestResult();
await tester.pumpWidget(MaterialApp(
title: 'Scroll Bug',
home: NestedDraggableCase(testResult: result),
));
// By dragging the scroll view more than the configured touch slop above but less than
// the framework default value, we demonstrate that this causes gesture detectors
// that do not receive the same gesture settings to fire at different times than would
// be expected.
final Offset start = tester.getCenter(find.byKey(const ValueKey<int>(1)));
await tester.timedDragFrom(start, const Offset(0, 5), const Duration(milliseconds: 50));
await tester.pumpAndSettle();
expect(result.dragStarted, true);
expect(result.dragUpdate, true);
expect(result.dragEnd, true);
});
}
| flutter/packages/flutter/test/gestures/gesture_config_regression_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/gesture_config_regression_test.dart",
"repo_id": "flutter",
"token_count": 2059
} | 666 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_test/flutter_test.dart';
import 'gesture_tester.dart';
class TestGestureArenaMember extends GestureArenaMember {
@override
void acceptGesture(int key) { }
@override
void rejectGesture(int key) { }
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Down/up pair 1: normal tap sequence
const PointerDownEvent down1 = PointerDownEvent(
pointer: 1,
position: Offset(10.0, 10.0),
);
const PointerUpEvent up1 = PointerUpEvent(
pointer: 1,
position: Offset(11.0, 9.0),
);
// Down/up pair 2: normal tap sequence far away from pair 1
const PointerDownEvent down2 = PointerDownEvent(
pointer: 2,
position: Offset(30.0, 30.0),
);
const PointerUpEvent up2 = PointerUpEvent(
pointer: 2,
position: Offset(31.0, 29.0),
);
// Down/move/up sequence 3: intervening motion, more than kTouchSlop. (~21px)
const PointerDownEvent down3 = PointerDownEvent(
pointer: 3,
position: Offset(10.0, 10.0),
);
const PointerMoveEvent move3 = PointerMoveEvent(
pointer: 3,
position: Offset(25.0, 25.0),
);
const PointerUpEvent up3 = PointerUpEvent(
pointer: 3,
position: Offset(25.0, 25.0),
);
// Down/move/up sequence 4: intervening motion, less than kTouchSlop. (~17px)
const PointerDownEvent down4 = PointerDownEvent(
pointer: 4,
position: Offset(10.0, 10.0),
);
const PointerMoveEvent move4 = PointerMoveEvent(
pointer: 4,
position: Offset(22.0, 22.0),
);
const PointerUpEvent up4 = PointerUpEvent(
pointer: 4,
position: Offset(22.0, 22.0),
);
// Down/up sequence 5: tap sequence with secondary button
const PointerDownEvent down5 = PointerDownEvent(
pointer: 5,
position: Offset(20.0, 20.0),
buttons: kSecondaryButton,
);
const PointerUpEvent up5 = PointerUpEvent(
pointer: 5,
position: Offset(20.0, 20.0),
);
// Down/up sequence 6: tap sequence with tertiary button
const PointerDownEvent down6 = PointerDownEvent(
pointer: 6,
position: Offset(20.0, 20.0),
buttons: kTertiaryButton,
);
const PointerUpEvent up6 = PointerUpEvent(
pointer: 6,
position: Offset(20.0, 20.0),
);
testGesture('Should recognize tap', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
addTearDown(tap.dispose);
bool tapRecognized = false;
tap.onTap = () {
tapRecognized = true;
};
tap.addPointer(down1);
tester.closeArena(1);
expect(tapRecognized, isFalse);
tester.route(down1);
expect(tapRecognized, isFalse);
tester.route(up1);
expect(tapRecognized, isTrue);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapRecognized, isTrue);
tap.dispose();
});
testGesture('Should recognize tap for supported devices only', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer(
supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.mouse, PointerDeviceKind.stylus },
);
bool tapRecognized = false;
tap.onTap = () {
tapRecognized = true;
};
const PointerDownEvent touchDown = PointerDownEvent(
pointer: 1,
position: Offset(10.0, 10.0),
);
const PointerUpEvent touchUp = PointerUpEvent(
pointer: 1,
position: Offset(11.0, 9.0),
);
tap.addPointer(touchDown);
tester.closeArena(1);
expect(tapRecognized, isFalse);
tester.route(touchDown);
expect(tapRecognized, isFalse);
tester.route(touchUp);
expect(tapRecognized, isFalse);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapRecognized, isFalse);
const PointerDownEvent mouseDown = PointerDownEvent(
kind: PointerDeviceKind.mouse,
pointer: 1,
position: Offset(10.0, 10.0),
);
const PointerUpEvent mouseUp = PointerUpEvent(
kind: PointerDeviceKind.mouse,
pointer: 1,
position: Offset(11.0, 9.0),
);
tap.addPointer(mouseDown);
tester.closeArena(1);
expect(tapRecognized, isFalse);
tester.route(mouseDown);
expect(tapRecognized, isFalse);
tester.route(mouseUp);
expect(tapRecognized, isTrue);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapRecognized, isTrue);
tapRecognized = false;
const PointerDownEvent stylusDown = PointerDownEvent(
kind: PointerDeviceKind.stylus,
pointer: 1,
position: Offset(10.0, 10.0),
);
const PointerUpEvent stylusUp = PointerUpEvent(
kind: PointerDeviceKind.stylus,
pointer: 1,
position: Offset(11.0, 9.0),
);
tap.addPointer(stylusDown);
tester.closeArena(1);
expect(tapRecognized, isFalse);
tester.route(stylusDown);
expect(tapRecognized, isFalse);
tester.route(stylusUp);
expect(tapRecognized, isTrue);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapRecognized, isTrue);
tap.dispose();
});
testGesture('Details contain the correct device kind', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
TapDownDetails? lastDownDetails;
TapUpDetails? lastUpDetails;
tap.onTapDown = (TapDownDetails details) {
lastDownDetails = details;
};
tap.onTapUp = (TapUpDetails details) {
lastUpDetails = details;
};
const PointerDownEvent mouseDown =
PointerDownEvent(pointer: 1, kind: PointerDeviceKind.mouse);
const PointerUpEvent mouseUp =
PointerUpEvent(pointer: 1, kind: PointerDeviceKind.mouse);
tap.addPointer(mouseDown);
tester.closeArena(1);
tester.route(mouseDown);
expect(lastDownDetails?.kind, PointerDeviceKind.mouse);
tester.route(mouseUp);
expect(lastUpDetails?.kind, PointerDeviceKind.mouse);
tap.dispose();
});
testGesture('No duplicate tap events', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
int tapsRecognized = 0;
tap.onTap = () {
tapsRecognized++;
};
tap.addPointer(down1);
tester.closeArena(1);
expect(tapsRecognized, 0);
tester.route(down1);
expect(tapsRecognized, 0);
tester.route(up1);
expect(tapsRecognized, 1);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapsRecognized, 1);
tap.addPointer(down1);
tester.closeArena(1);
expect(tapsRecognized, 1);
tester.route(down1);
expect(tapsRecognized, 1);
tester.route(up1);
expect(tapsRecognized, 2);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapsRecognized, 2);
tap.dispose();
});
testGesture('Should not recognize two overlapping taps (FIFO)', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
int tapsRecognized = 0;
tap.onTap = () {
tapsRecognized++;
};
tap.addPointer(down1);
tester.closeArena(1);
expect(tapsRecognized, 0);
tester.route(down1);
expect(tapsRecognized, 0);
tap.addPointer(down2);
tester.closeArena(2);
expect(tapsRecognized, 0);
tester.route(down1);
expect(tapsRecognized, 0);
tester.route(up1);
expect(tapsRecognized, 1);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapsRecognized, 1);
tester.route(up2);
expect(tapsRecognized, 1);
GestureBinding.instance.gestureArena.sweep(2);
expect(tapsRecognized, 1);
tap.dispose();
});
testGesture('Should not recognize two overlapping taps (FILO)', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
int tapsRecognized = 0;
tap.onTap = () {
tapsRecognized++;
};
tap.addPointer(down1);
tester.closeArena(1);
expect(tapsRecognized, 0);
tester.route(down1);
expect(tapsRecognized, 0);
tap.addPointer(down2);
tester.closeArena(2);
expect(tapsRecognized, 0);
tester.route(down1);
expect(tapsRecognized, 0);
tester.route(up2);
expect(tapsRecognized, 0);
GestureBinding.instance.gestureArena.sweep(2);
expect(tapsRecognized, 0);
tester.route(up1);
expect(tapsRecognized, 1);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapsRecognized, 1);
tap.dispose();
});
testGesture('Distance cancels tap', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
bool tapRecognized = false;
tap.onTap = () {
tapRecognized = true;
};
bool tapCanceled = false;
tap.onTapCancel = () {
tapCanceled = true;
};
tap.addPointer(down3);
tester.closeArena(3);
expect(tapRecognized, isFalse);
expect(tapCanceled, isFalse);
tester.route(down3);
expect(tapRecognized, isFalse);
expect(tapCanceled, isFalse);
tester.route(move3);
expect(tapRecognized, isFalse);
expect(tapCanceled, isTrue);
tester.route(up3);
expect(tapRecognized, isFalse);
expect(tapCanceled, isTrue);
GestureBinding.instance.gestureArena.sweep(3);
expect(tapRecognized, isFalse);
expect(tapCanceled, isTrue);
tap.dispose();
});
testGesture('Short distance does not cancel tap', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
bool tapRecognized = false;
tap.onTap = () {
tapRecognized = true;
};
bool tapCanceled = false;
tap.onTapCancel = () {
tapCanceled = true;
};
tap.addPointer(down4);
tester.closeArena(4);
expect(tapRecognized, isFalse);
expect(tapCanceled, isFalse);
tester.route(down4);
expect(tapRecognized, isFalse);
expect(tapCanceled, isFalse);
tester.route(move4);
expect(tapRecognized, isFalse);
expect(tapCanceled, isFalse);
tester.route(up4);
expect(tapRecognized, isTrue);
expect(tapCanceled, isFalse);
GestureBinding.instance.gestureArena.sweep(4);
expect(tapRecognized, isTrue);
expect(tapCanceled, isFalse);
tap.dispose();
});
testGesture('Timeout does not cancel tap', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
bool tapRecognized = false;
tap.onTap = () {
tapRecognized = true;
};
tap.addPointer(down1);
tester.closeArena(1);
expect(tapRecognized, isFalse);
tester.route(down1);
expect(tapRecognized, isFalse);
tester.async.elapse(const Duration(milliseconds: 500));
expect(tapRecognized, isFalse);
tester.route(up1);
expect(tapRecognized, isTrue);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapRecognized, isTrue);
tap.dispose();
});
testGesture('Should yield to other arena members', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
bool tapRecognized = false;
tap.onTap = () {
tapRecognized = true;
};
tap.addPointer(down1);
final TestGestureArenaMember member = TestGestureArenaMember();
final GestureArenaEntry entry = GestureBinding.instance.gestureArena.add(1, member);
GestureBinding.instance.gestureArena.hold(1);
tester.closeArena(1);
expect(tapRecognized, isFalse);
tester.route(down1);
expect(tapRecognized, isFalse);
tester.route(up1);
expect(tapRecognized, isFalse);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapRecognized, isFalse);
entry.resolve(GestureDisposition.accepted);
expect(tapRecognized, isFalse);
tap.dispose();
});
testGesture('Should trigger on release of held arena', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
bool tapRecognized = false;
tap.onTap = () {
tapRecognized = true;
};
tap.addPointer(down1);
final TestGestureArenaMember member = TestGestureArenaMember();
final GestureArenaEntry entry = GestureBinding.instance.gestureArena.add(1, member);
GestureBinding.instance.gestureArena.hold(1);
tester.closeArena(1);
expect(tapRecognized, isFalse);
tester.route(down1);
expect(tapRecognized, isFalse);
tester.route(up1);
expect(tapRecognized, isFalse);
GestureBinding.instance.gestureArena.sweep(1);
expect(tapRecognized, isFalse);
entry.resolve(GestureDisposition.rejected);
tester.async.flushMicrotasks();
expect(tapRecognized, isTrue);
tap.dispose();
});
testGesture('Should log exceptions from callbacks', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
tap.onTap = () {
throw Exception(test);
};
final FlutterExceptionHandler? previousErrorHandler = FlutterError.onError;
bool gotError = false;
FlutterError.onError = (FlutterErrorDetails details) {
gotError = true;
};
tap.addPointer(down1);
tester.closeArena(1);
tester.route(down1);
expect(gotError, isFalse);
tester.route(up1);
expect(gotError, isTrue);
FlutterError.onError = previousErrorHandler;
tap.dispose();
});
testGesture('onTapCancel should show reason in the proper format', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
tap.onTapCancel = () {
throw Exception(test);
};
final FlutterExceptionHandler? previousErrorHandler = FlutterError.onError;
bool gotError = false;
FlutterError.onError = (FlutterErrorDetails details) {
expect(details.toString().contains('"spontaneous onTapCancel"') , isTrue);
gotError = true;
};
const int pointer = 1;
tap.addPointer(const PointerDownEvent(pointer: pointer));
tester.closeArena(pointer);
tester.async.elapse(const Duration(milliseconds: 500));
tester.route(const PointerCancelEvent(pointer: pointer));
expect(gotError, isTrue);
FlutterError.onError = previousErrorHandler;
tap.dispose();
});
testGesture('No duplicate tap events', (GestureTester tester) {
final TapGestureRecognizer tapA = TapGestureRecognizer();
final TapGestureRecognizer tapB = TapGestureRecognizer();
final List<String> log = <String>[];
tapA.onTapDown = (TapDownDetails details) { log.add('tapA onTapDown'); };
tapA.onTapUp = (TapUpDetails details) { log.add('tapA onTapUp'); };
tapA.onTap = () { log.add('tapA onTap'); };
tapA.onTapCancel = () { log.add('tapA onTapCancel'); };
tapB.onTapDown = (TapDownDetails details) { log.add('tapB onTapDown'); };
tapB.onTapUp = (TapUpDetails details) { log.add('tapB onTapUp'); };
tapB.onTap = () { log.add('tapB onTap'); };
tapB.onTapCancel = () { log.add('tapB onTapCancel'); };
log.add('start');
tapA.addPointer(down1);
log.add('added 1 to A');
tapB.addPointer(down1);
log.add('added 1 to B');
tester.closeArena(1);
log.add('closed 1');
tester.route(down1);
log.add('routed 1 down');
tester.route(up1);
log.add('routed 1 up');
GestureBinding.instance.gestureArena.sweep(1);
log.add('swept 1');
tapA.addPointer(down2);
log.add('down 2 to A');
tapB.addPointer(down2);
log.add('down 2 to B');
tester.closeArena(2);
log.add('closed 2');
tester.route(down2);
log.add('routed 2 down');
tester.route(up2);
log.add('routed 2 up');
GestureBinding.instance.gestureArena.sweep(2);
log.add('swept 2');
tapA.dispose();
log.add('disposed A');
tapB.dispose();
log.add('disposed B');
expect(log, <String>[
'start',
'added 1 to A',
'added 1 to B',
'closed 1',
'routed 1 down',
'routed 1 up',
'tapA onTapDown',
'tapA onTapUp',
'tapA onTap',
'swept 1',
'down 2 to A',
'down 2 to B',
'closed 2',
'routed 2 down',
'routed 2 up',
'tapA onTapDown',
'tapA onTapUp',
'tapA onTap',
'swept 2',
'disposed A',
'disposed B',
]);
});
testGesture('PointerCancelEvent cancels tap', (GestureTester tester) {
const PointerDownEvent down = PointerDownEvent(
pointer: 5,
position: Offset(10.0, 10.0),
);
const PointerCancelEvent cancel = PointerCancelEvent(
pointer: 5,
position: Offset(10.0, 10.0),
);
final TapGestureRecognizer tap = TapGestureRecognizer();
final List<String> recognized = <String>[];
tap.onTapDown = (_) {
recognized.add('down');
};
tap.onTapUp = (_) {
recognized.add('up');
};
tap.onTap = () {
recognized.add('tap');
};
tap.onTapCancel = () {
recognized.add('cancel');
};
tap.addPointer(down);
tester.closeArena(5);
tester.async.elapse(const Duration(milliseconds: 5000));
expect(recognized, <String>['down']);
tester.route(cancel);
expect(recognized, <String>['down', 'cancel']);
tap.dispose();
});
testGesture('PointerCancelEvent after exceeding deadline cancels tap', (GestureTester tester) {
const PointerDownEvent down = PointerDownEvent(
pointer: 5,
position: Offset(10.0, 10.0),
);
const PointerCancelEvent cancel = PointerCancelEvent(
pointer: 5,
position: Offset(10.0, 10.0),
);
final TapGestureRecognizer tap = TapGestureRecognizer();
final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer()
..onStart = (_) {}; // Need a callback to compete
addTearDown(drag.dispose);
final List<String> recognized = <String>[];
tap.onTapDown = (_) {
recognized.add('down');
};
tap.onTapUp = (_) {
recognized.add('up');
};
tap.onTap = () {
recognized.add('tap');
};
tap.onTapCancel = () {
recognized.add('cancel');
};
tap.addPointer(down);
drag.addPointer(down);
tester.closeArena(5);
tester.route(down);
expect(recognized, <String>[]);
tester.async.elapse(const Duration(milliseconds: 1000));
expect(recognized, <String>['down']);
tester.route(cancel);
expect(recognized, <String>['down', 'cancel']);
tap.dispose();
drag.dispose();
});
testGesture('losing tap gesture recognizer does not send onTapCancel', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
addTearDown(tap.dispose);
final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer();
addTearDown(drag.dispose);
final List<String> recognized = <String>[];
tap.onTapDown = (_) {
recognized.add('down');
};
tap.onTapUp = (_) {
recognized.add('up');
};
tap.onTap = () {
recognized.add('tap');
};
tap.onTapCancel = () {
recognized.add('cancel');
};
tap.addPointer(down3);
drag.addPointer(down3);
tester.closeArena(3);
tester.route(move3);
GestureBinding.instance.gestureArena.sweep(3);
expect(recognized, isEmpty);
tap.dispose();
drag.dispose();
});
testGesture('non-primary pointers does not trigger timeout', (GestureTester tester) {
// Regression test for https://github.com/flutter/flutter/issues/43310
// Pointer1 down, pointer2 down, then pointer 1 up, all within the timeout.
// In this way, `BaseTapGestureRecognizer.didExceedDeadline` can be triggered
// after its `_reset`.
final TapGestureRecognizer tap = TapGestureRecognizer();
addTearDown(tap.dispose);
final List<String> recognized = <String>[];
tap.onTapDown = (_) {
recognized.add('down');
};
tap.onTapUp = (_) {
recognized.add('up');
};
tap.onTap = () {
recognized.add('tap');
};
tap.onTapCancel = () {
recognized.add('cancel');
};
tap.addPointer(down1);
tester.closeArena(down1.pointer);
tap.addPointer(down2);
tester.closeArena(down2.pointer);
expect(recognized, isEmpty);
tester.route(up1);
GestureBinding.instance.gestureArena.sweep(down1.pointer);
expect(recognized, <String>['down', 'up', 'tap']);
recognized.clear();
// If regression happens, the following step will throw error
tester.async.elapse(const Duration(milliseconds: 200));
expect(recognized, isEmpty);
tester.route(up2);
GestureBinding.instance.gestureArena.sweep(down2.pointer);
expect(recognized, isEmpty);
tap.dispose();
});
group('Enforce consistent-button restriction:', () {
// Change buttons during down-up sequence 1
const PointerMoveEvent move1lr = PointerMoveEvent(
pointer: 1,
position: Offset(10.0, 10.0),
buttons: kPrimaryMouseButton | kSecondaryMouseButton,
);
const PointerMoveEvent move1r = PointerMoveEvent(
pointer: 1,
position: Offset(10.0, 10.0),
buttons: kSecondaryMouseButton,
);
final List<String> recognized = <String>[];
late TapGestureRecognizer tap;
setUp(() {
tap = TapGestureRecognizer()
..onTapDown = (TapDownDetails details) {
recognized.add('down');
}
..onTapUp = (TapUpDetails details) {
recognized.add('up');
}
..onTapCancel = () {
recognized.add('cancel');
};
addTearDown(tap.dispose);
});
tearDown(() {
tap.dispose();
recognized.clear();
});
testGesture('changing buttons before TapDown should cancel gesture without sending cancel', (GestureTester tester) {
tap.addPointer(down1);
tester.closeArena(1);
expect(recognized, <String>[]);
tester.route(move1lr);
expect(recognized, <String>[]);
tester.route(move1r);
expect(recognized, <String>[]);
tester.route(up1);
expect(recognized, <String>[]);
tap.dispose();
});
testGesture('changing buttons before TapDown should not prevent the next tap', (GestureTester tester) {
tap.addPointer(down1);
tester.closeArena(1);
tester.route(move1lr);
tester.route(move1r);
tester.route(up1);
expect(recognized, <String>[]);
tap.addPointer(down2);
tester.closeArena(2);
tester.async.elapse(const Duration(milliseconds: 1000));
tester.route(up2);
expect(recognized, <String>['down', 'up']);
tap.dispose();
});
testGesture('changing buttons after TapDown should cancel gesture and send cancel', (GestureTester tester) {
tap.addPointer(down1);
tester.closeArena(1);
expect(recognized, <String>[]);
tester.async.elapse(const Duration(milliseconds: 1000));
expect(recognized, <String>['down']);
tester.route(move1lr);
expect(recognized, <String>['down', 'cancel']);
tester.route(move1r);
expect(recognized, <String>['down', 'cancel']);
tester.route(up1);
expect(recognized, <String>['down', 'cancel']);
tap.dispose();
});
testGesture('changing buttons after TapDown should not prevent the next tap', (GestureTester tester) {
tap.addPointer(down1);
tester.closeArena(1);
tester.async.elapse(const Duration(milliseconds: 1000));
tester.route(move1lr);
tester.route(move1r);
tester.route(up1);
GestureBinding.instance.gestureArena.sweep(1);
expect(recognized, <String>['down', 'cancel']);
tap.addPointer(down2);
tester.closeArena(2);
tester.async.elapse(const Duration(milliseconds: 1000));
tester.route(up2);
GestureBinding.instance.gestureArena.sweep(2);
expect(recognized, <String>['down', 'cancel', 'down', 'up']);
tap.dispose();
});
});
group('Recognizers listening on different buttons do not form competition:', () {
// If a tap gesture has no competitors, a pointer down event triggers
// onTapDown immediately; if there are competitors, onTapDown is triggered
// after a timeout. The following tests make sure that tap recognizers
// listening on different buttons do not form competition.
final List<String> recognized = <String>[];
late TapGestureRecognizer primary;
late TapGestureRecognizer primary2;
late TapGestureRecognizer secondary;
late TapGestureRecognizer tertiary;
setUp(() {
primary = TapGestureRecognizer()
..onTapDown = (TapDownDetails details) {
recognized.add('primaryDown');
}
..onTapUp = (TapUpDetails details) {
recognized.add('primaryUp');
}
..onTapCancel = () {
recognized.add('primaryCancel');
};
addTearDown(primary.dispose);
primary2 = TapGestureRecognizer()
..onTapDown = (TapDownDetails details) {
recognized.add('primary2Down');
}
..onTapUp = (TapUpDetails details) {
recognized.add('primary2Up');
}
..onTapCancel = () {
recognized.add('primary2Cancel');
};
addTearDown(primary2.dispose);
secondary = TapGestureRecognizer()
..onSecondaryTapDown = (TapDownDetails details) {
recognized.add('secondaryDown');
}
..onSecondaryTapUp = (TapUpDetails details) {
recognized.add('secondaryUp');
}
..onSecondaryTapCancel = () {
recognized.add('secondaryCancel');
};
addTearDown(secondary.dispose);
tertiary = TapGestureRecognizer()
..onTertiaryTapDown = (TapDownDetails details) {
recognized.add('tertiaryDown');
}
..onTertiaryTapUp = (TapUpDetails details) {
recognized.add('tertiaryUp');
}
..onTertiaryTapCancel = () {
recognized.add('tertiaryCancel');
};
addTearDown(tertiary.dispose);
});
tearDown(() {
primary.dispose();
primary2.dispose();
secondary.dispose();
tertiary.dispose();
recognized.clear();
});
testGesture('A primary tap recognizer does not form competition with a secondary tap recognizer', (GestureTester tester) {
primary.addPointer(down1);
secondary.addPointer(down1);
tester.closeArena(1);
tester.route(down1);
expect(recognized, <String>['primaryDown']);
recognized.clear();
tester.route(up1);
expect(recognized, <String>['primaryUp']);
});
testGesture('A primary tap recognizer does not form competition with a tertiary tap recognizer', (GestureTester tester) {
primary.addPointer(down1);
tertiary.addPointer(down1);
tester.closeArena(1);
tester.route(down1);
expect(recognized, <String>['primaryDown']);
recognized.clear();
tester.route(up1);
expect(recognized, <String>['primaryUp']);
});
testGesture('A primary tap recognizer forms competition with another primary tap recognizer', (GestureTester tester) {
primary.addPointer(down1);
primary2.addPointer(down1);
tester.closeArena(1);
tester.route(down1);
expect(recognized, <String>[]);
tester.async.elapse(const Duration(milliseconds: 500));
expect(recognized, <String>['primaryDown', 'primary2Down']);
});
});
group('Gestures of different buttons trigger correct callbacks:', () {
final List<String> recognized = <String>[];
late TapGestureRecognizer tap;
const PointerCancelEvent cancel1 = PointerCancelEvent(
pointer: 1,
);
const PointerCancelEvent cancel5 = PointerCancelEvent(
pointer: 5,
);
const PointerCancelEvent cancel6 = PointerCancelEvent(
pointer: 6,
);
setUp(() {
tap = TapGestureRecognizer()
..onTapDown = (TapDownDetails details) {
recognized.add('primaryDown');
}
..onTap = () {
recognized.add('primary');
}
..onTapUp = (TapUpDetails details) {
recognized.add('primaryUp');
}
..onTapCancel = () {
recognized.add('primaryCancel');
}
..onSecondaryTapDown = (TapDownDetails details) {
recognized.add('secondaryDown');
}
..onSecondaryTapUp = (TapUpDetails details) {
recognized.add('secondaryUp');
}
..onSecondaryTapCancel = () {
recognized.add('secondaryCancel');
}
..onTertiaryTapDown = (TapDownDetails details) {
recognized.add('tertiaryDown');
}
..onTertiaryTapUp = (TapUpDetails details) {
recognized.add('tertiaryUp');
}
..onTertiaryTapCancel = () {
recognized.add('tertiaryCancel');
};
});
tearDown(() {
recognized.clear();
tap.dispose();
});
testGesture('A primary tap should trigger primary callbacks', (GestureTester tester) {
tap.addPointer(down1);
tester.closeArena(down1.pointer);
expect(recognized, <String>[]);
tester.async.elapse(const Duration(milliseconds: 500));
expect(recognized, <String>['primaryDown']);
recognized.clear();
tester.route(up1);
expect(recognized, <String>['primaryUp', 'primary']);
GestureBinding.instance.gestureArena.sweep(down1.pointer);
});
testGesture('A primary tap cancel trigger primary callbacks', (GestureTester tester) {
tap.addPointer(down1);
tester.closeArena(down1.pointer);
expect(recognized, <String>[]);
tester.async.elapse(const Duration(milliseconds: 500));
expect(recognized, <String>['primaryDown']);
recognized.clear();
tester.route(cancel1);
expect(recognized, <String>['primaryCancel']);
GestureBinding.instance.gestureArena.sweep(down1.pointer);
});
testGesture('A secondary tap should trigger secondary callbacks', (GestureTester tester) {
tap.addPointer(down5);
tester.closeArena(down5.pointer);
expect(recognized, <String>[]);
tester.async.elapse(const Duration(milliseconds: 500));
expect(recognized, <String>['secondaryDown']);
recognized.clear();
tester.route(up5);
GestureBinding.instance.gestureArena.sweep(down5.pointer);
expect(recognized, <String>['secondaryUp']);
});
testGesture('A tertiary tap should trigger tertiary callbacks', (GestureTester tester) {
tap.addPointer(down6);
tester.closeArena(down6.pointer);
expect(recognized, <String>[]);
tester.async.elapse(const Duration(milliseconds: 500));
expect(recognized, <String>['tertiaryDown']);
recognized.clear();
tester.route(up6);
GestureBinding.instance.gestureArena.sweep(down6.pointer);
expect(recognized, <String>['tertiaryUp']);
});
testGesture('A secondary tap cancel should trigger secondary callbacks', (GestureTester tester) {
tap.addPointer(down5);
tester.closeArena(down5.pointer);
expect(recognized, <String>[]);
tester.async.elapse(const Duration(milliseconds: 500));
expect(recognized, <String>['secondaryDown']);
recognized.clear();
tester.route(cancel5);
GestureBinding.instance.gestureArena.sweep(down5.pointer);
expect(recognized, <String>['secondaryCancel']);
});
testGesture('A tertiary tap cancel should trigger tertiary callbacks', (GestureTester tester) {
tap.addPointer(down6);
tester.closeArena(down6.pointer);
expect(recognized, <String>[]);
tester.async.elapse(const Duration(milliseconds: 500));
expect(recognized, <String>['tertiaryDown']);
recognized.clear();
tester.route(cancel6);
GestureBinding.instance.gestureArena.sweep(down6.pointer);
expect(recognized, <String>['tertiaryCancel']);
});
});
testGesture('A second tap after rejection is ignored', (GestureTester tester) {
bool didTap = false;
final TapGestureRecognizer tap = TapGestureRecognizer()
..onTap = () {
didTap = true;
};
addTearDown(tap.dispose);
// Add drag recognizer for competition
final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer()
..onStart = (_) {};
addTearDown(drag.dispose);
final TestPointer pointer1 = TestPointer();
final PointerDownEvent down = pointer1.down(Offset.zero);
drag.addPointer(down);
tap.addPointer(down);
tester.closeArena(1);
// One-finger moves, canceling the tap
tester.route(down);
tester.route(pointer1.move(const Offset(50.0, 0)));
// Add another finger
final TestPointer pointer2 = TestPointer(2);
final PointerDownEvent down2 = pointer2.down(const Offset(10.0, 20.0));
drag.addPointer(down2);
tap.addPointer(down2);
tester.closeArena(2);
tester.route(down2);
expect(didTap, isFalse);
});
}
| flutter/packages/flutter/test/gestures/tap_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/tap_test.dart",
"repo_id": "flutter",
"token_count": 13444
} | 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.
@Tags(<String>['reduced-test-set'])
library;
import 'dart:math' as math show pi;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
class MockCanvas extends Fake implements Canvas {
late Path capturedPath;
late Paint capturedPaint;
@override
void drawPath(Path path, Paint paint) {
capturedPath = path;
capturedPaint = paint;
}
late double capturedSx;
late double capturedSy;
@override
void scale(double sx, [double? sy]) {
capturedSx = sx;
capturedSy = sy!;
invocations.add(RecordedScale(sx, sy));
}
final List<RecordedCanvasCall> invocations = <RecordedCanvasCall>[];
@override
void rotate(double radians) {
invocations.add(RecordedRotate(radians));
}
@override
void translate(double dx, double dy) {
invocations.add(RecordedTranslate(dx, dy));
}
}
@immutable
abstract class RecordedCanvasCall {
const RecordedCanvasCall();
}
class RecordedRotate extends RecordedCanvasCall {
const RecordedRotate(this.radians);
final double radians;
@override
bool operator ==(Object other) {
return other is RecordedRotate && other.radians == radians;
}
@override
int get hashCode => radians.hashCode;
}
class RecordedTranslate extends RecordedCanvasCall {
const RecordedTranslate(this.dx, this.dy);
final double dx;
final double dy;
@override
bool operator ==(Object other) {
return other is RecordedTranslate && other.dx == dx && other.dy == dy;
}
@override
int get hashCode => Object.hash(dx, dy);
}
class RecordedScale extends RecordedCanvasCall {
const RecordedScale(this.sx, this.sy);
final double sx;
final double sy;
@override
bool operator ==(Object other) {
return other is RecordedScale && other.sx == sx && other.sy == sy;
}
@override
int get hashCode => Object.hash(sx, sy);
}
void main() {
testWidgets('IconTheme color', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
color: Color(0xFF666666),
),
child: AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
),
),
),
);
final CustomPaint customPaint = tester.widget(find.byType(CustomPaint));
final MockCanvas canvas = MockCanvas();
customPaint.painter!.paint(canvas, const Size(48.0, 48.0));
expect(canvas.capturedPaint, hasColor(0xFF666666));
});
testWidgets('IconTheme opacity', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
color: Color(0xFF666666),
opacity: 0.5,
),
child: AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
),
),
),
);
final CustomPaint customPaint = tester.widget(find.byType(CustomPaint));
final MockCanvas canvas = MockCanvas();
customPaint.painter!.paint(canvas, const Size(48.0, 48.0));
expect(canvas.capturedPaint, hasColor(0x80666666));
});
testWidgets('color overrides IconTheme color', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
color: Color(0xFF666666),
),
child: AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
color: Color(0xFF0000FF),
),
),
),
);
final CustomPaint customPaint = tester.widget(find.byType(CustomPaint));
final MockCanvas canvas = MockCanvas();
customPaint.painter!.paint(canvas, const Size(48.0, 48.0));
expect(canvas.capturedPaint, hasColor(0xFF0000FF));
});
testWidgets('IconTheme size', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
color: Color(0xFF666666),
size: 12.0,
),
child: AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
),
),
),
);
final CustomPaint customPaint = tester.widget(find.byType(CustomPaint));
final MockCanvas canvas = MockCanvas();
customPaint.painter!.paint(canvas, const Size(12.0, 12.0));
// arrow_menu default size is 48x48 so we expect it to be scaled by 0.25.
expect(canvas.capturedSx, 0.25);
expect(canvas.capturedSy, 0.25);
});
testWidgets('size overridesIconTheme size', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
color: Color(0xFF666666),
size: 12.0,
),
child: AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
size: 96.0,
),
),
),
);
final CustomPaint customPaint = tester.widget(find.byType(CustomPaint));
final MockCanvas canvas = MockCanvas();
customPaint.painter!.paint(canvas, const Size(12.0, 12.0));
// arrow_menu default size is 48x48 so we expect it to be scaled by 2.
expect(canvas.capturedSx, 2);
expect(canvas.capturedSy, 2);
});
testWidgets('Semantic label', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
size: 96.0,
semanticLabel: 'a label',
),
),
);
expect(semantics, includesNodeWith(label: 'a label'));
semantics.dispose();
});
testWidgets('Inherited text direction rtl', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.rtl,
child: IconTheme(
data: IconThemeData(
color: Color(0xFF666666),
),
child: RepaintBoundary(
child: AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
),
),
),
),
);
final CustomPaint customPaint = tester.widget(find.byType(CustomPaint));
final MockCanvas canvas = MockCanvas();
customPaint.painter!.paint(canvas, const Size(48.0, 48.0));
expect(canvas.invocations, const <RecordedCanvasCall>[
RecordedRotate(math.pi),
RecordedTranslate(-48, -48),
RecordedScale(0.5, 0.5),
]);
await expectLater(find.byType(AnimatedIcon),
matchesGoldenFile('animated_icons_test.icon.rtl.png'));
});
testWidgets('Inherited text direction ltr', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
color: Color(0xFF666666),
),
child: RepaintBoundary(
child: AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
),
),
),
),
);
final CustomPaint customPaint = tester.widget(find.byType(CustomPaint));
final MockCanvas canvas = MockCanvas();
customPaint.painter!.paint(canvas, const Size(48.0, 48.0));
expect(canvas.invocations, const <RecordedCanvasCall>[
RecordedScale(0.5, 0.5),
]);
await expectLater(find.byType(AnimatedIcon),
matchesGoldenFile('animated_icons_test.icon.ltr.png'));
});
testWidgets('Inherited text direction overridden', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
color: Color(0xFF666666),
),
child: AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
textDirection: TextDirection.rtl,
),
),
),
);
final CustomPaint customPaint = tester.widget(find.byType(CustomPaint));
final MockCanvas canvas = MockCanvas();
customPaint.painter!.paint(canvas, const Size(48.0, 48.0));
expect(canvas.invocations, const <RecordedCanvasCall>[
RecordedRotate(math.pi),
RecordedTranslate(-48, -48),
RecordedScale(0.5, 0.5),
]);
});
testWidgets('Direction has no effect on position of widget', (WidgetTester tester) async {
const AnimatedIcon icon = AnimatedIcon(
progress: AlwaysStoppedAnimation<double>(0.0),
icon: AnimatedIcons.arrow_menu,
);
await tester.pumpWidget(
const Directionality(textDirection: TextDirection.rtl, child: icon),
);
final Rect rtlRect = tester.getRect(find.byType(AnimatedIcon));
await tester.pumpWidget(
const Directionality(textDirection: TextDirection.ltr, child: icon),
);
final Rect ltrRect = tester.getRect(find.byType(AnimatedIcon));
expect(rtlRect, ltrRect);
});
}
PaintColorMatcher hasColor(int color) {
return PaintColorMatcher(color);
}
class PaintColorMatcher extends Matcher {
const PaintColorMatcher(this.expectedColor);
final int expectedColor;
@override
Description describe(Description description) =>
description.add('color was not $expectedColor');
@override
bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
final Paint actualPaint = item as Paint;
return actualPaint.color == Color(expectedColor);
}
}
| flutter/packages/flutter/test/material/animated_icons_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/animated_icons_test.dart",
"repo_id": "flutter",
"token_count": 4258
} | 668 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'dart:math';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:vector_math/vector_math_64.dart' show Vector3;
import '../widgets/semantics_tester.dart';
import 'feedback_tester.dart';
void main() {
testWidgets('BottomNavigationBar callback test', (WidgetTester tester) async {
late int mutatedIndex;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
onTap: (int index) {
mutatedIndex = index;
},
),
),
),
);
await tester.tap(find.text('Alarm'));
expect(mutatedIndex, 1);
});
testWidgets('Material2 - BottomNavigationBar content test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final RenderBox box = tester.renderObject(find.byType(BottomNavigationBar));
expect(box.size.height, kBottomNavigationBarHeight);
expect(find.text('AC'), findsOneWidget);
expect(find.text('Alarm'), findsOneWidget);
});
testWidgets('Material3 - BottomNavigationBar content test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final RenderBox box = tester.renderObject(find.byType(BottomNavigationBar));
// kBottomNavigationBarHeight is a minimum dimension.
expect(box.size.height, greaterThanOrEqualTo(kBottomNavigationBarHeight));
expect(find.text('AC'), findsOneWidget);
expect(find.text('Alarm'), findsOneWidget);
});
testWidgets('Material2 - Fixed BottomNavigationBar defaults', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000001);
const Color unselectedWidgetColor = Color(0xFF000002);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.light(useMaterial3: false).copyWith(
colorScheme: const ColorScheme.light().copyWith(primary: primaryColor),
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
const double selectedFontSize = 14.0;
const double unselectedFontSize = 12.0;
final TextStyle selectedFontStyle = tester.renderObject<RenderParagraph>(find.text('AC')).text.style!;
final TextStyle unselectedFontStyle = tester.renderObject<RenderParagraph>(find.text('Alarm')).text.style!;
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedFontStyle.color, equals(primaryColor));
expect(selectedFontStyle.fontSize, selectedFontSize);
expect(selectedFontStyle.fontWeight, equals(FontWeight.w400));
expect(selectedFontStyle.height, isNull);
expect(unselectedFontStyle.color, equals(unselectedWidgetColor));
expect(unselectedFontStyle.fontWeight, equals(FontWeight.w400));
expect(unselectedFontStyle.height, isNull);
// Unselected label has a font size of 14 but is scaled down to be font size 12.
expect(
tester.firstWidget<Transform>(find.ancestor(of: find.text('Alarm'), matching: find.byType(Transform))).transform,
equals(Matrix4.diagonal3(Vector3.all(unselectedFontSize / selectedFontSize))),
);
expect(selectedIcon.color, equals(primaryColor));
expect(selectedIcon.fontSize, equals(24.0));
expect(unselectedIcon.color, equals(unselectedWidgetColor));
expect(unselectedIcon.fontSize, equals(24.0));
// There should not be any [Opacity] or [FadeTransition] widgets
// since showUnselectedLabels and showSelectedLabels are true.
final Finder findOpacity = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(Opacity),
);
final Finder findFadeTransition = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(FadeTransition),
);
expect(findOpacity, findsNothing);
expect(findFadeTransition, findsNothing);
expect(_getMaterial(tester).elevation, equals(8.0));
});
testWidgets('Material3 - Fixed BottomNavigationBar defaults', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000001);
const Color unselectedWidgetColor = Color(0xFF000002);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
colorScheme: const ColorScheme.light().copyWith(primary: primaryColor),
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
const double selectedFontSize = 14.0;
const double unselectedFontSize = 12.0;
final TextStyle selectedFontStyle = tester.renderObject<RenderParagraph>(find.text('AC')).text.style!;
final TextStyle unselectedFontStyle = tester.renderObject<RenderParagraph>(find.text('Alarm')).text.style!;
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedFontStyle.color, equals(primaryColor));
expect(selectedFontStyle.fontSize, selectedFontSize);
expect(selectedFontStyle.fontWeight, equals(FontWeight.w400));
expect(selectedFontStyle.height, 1.43);
expect(unselectedFontStyle.color, equals(unselectedWidgetColor));
expect(unselectedFontStyle.fontWeight, equals(FontWeight.w400));
expect(unselectedFontStyle.height, 1.43);
// Unselected label has a font size of 14 but is scaled down to be font size 12.
expect(
tester.firstWidget<Transform>(find.ancestor(of: find.text('Alarm'), matching: find.byType(Transform))).transform,
equals(Matrix4.diagonal3(Vector3.all(unselectedFontSize / selectedFontSize))),
);
expect(selectedIcon.color, equals(primaryColor));
expect(selectedIcon.fontSize, equals(24.0));
expect(unselectedIcon.color, equals(unselectedWidgetColor));
expect(unselectedIcon.fontSize, equals(24.0));
// There should not be any [Opacity] or [FadeTransition] widgets
// since showUnselectedLabels and showSelectedLabels are true.
final Finder findOpacity = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(Opacity),
);
final Finder findFadeTransition = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(FadeTransition),
);
expect(findOpacity, findsNothing);
expect(findFadeTransition, findsNothing);
expect(_getMaterial(tester).elevation, equals(8.0));
});
testWidgets('Custom selected and unselected font styles', (WidgetTester tester) async {
const TextStyle selectedTextStyle = TextStyle(fontWeight: FontWeight.w200, fontSize: 18.0);
const TextStyle unselectedTextStyle = TextStyle(fontWeight: FontWeight.w600, fontSize: 12.0);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedLabelStyle: selectedTextStyle,
unselectedLabelStyle: unselectedTextStyle,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedFontStyle = tester.renderObject<RenderParagraph>(find.text('AC')).text.style!;
final TextStyle unselectedFontStyle = tester.renderObject<RenderParagraph>(find.text('Alarm')).text.style!;
expect(selectedFontStyle.fontSize, equals(selectedTextStyle.fontSize));
expect(selectedFontStyle.fontWeight, equals(selectedTextStyle.fontWeight));
expect(
tester.firstWidget<Transform>(find.ancestor(of: find.text('Alarm'), matching: find.byType(Transform))).transform,
equals(Matrix4.diagonal3(Vector3.all(unselectedTextStyle.fontSize! / selectedTextStyle.fontSize!))),
);
expect(unselectedFontStyle.fontWeight, equals(unselectedTextStyle.fontWeight));
});
testWidgets('font size on text styles overrides font size params', (WidgetTester tester) async {
const TextStyle selectedTextStyle = TextStyle(fontSize: 18.0);
const TextStyle unselectedTextStyle = TextStyle(fontSize: 12.0);
const double selectedFontSize = 17.0;
const double unselectedFontSize = 11.0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedLabelStyle: selectedTextStyle,
unselectedLabelStyle: unselectedTextStyle,
selectedFontSize: selectedFontSize,
unselectedFontSize: unselectedFontSize,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedFontStyle = tester.renderObject<RenderParagraph>(find.text('AC')).text.style!;
expect(selectedFontStyle.fontSize, equals(selectedTextStyle.fontSize));
expect(
tester.firstWidget<Transform>(find.ancestor(of: find.text('Alarm'), matching: find.byType(Transform))).transform,
equals(Matrix4.diagonal3(Vector3.all(unselectedTextStyle.fontSize! / selectedTextStyle.fontSize!))),
);
});
testWidgets('Custom selected and unselected icon themes', (WidgetTester tester) async {
const IconThemeData selectedIconTheme = IconThemeData(size: 36, color: Color(0x00000001));
const IconThemeData unselectedIconTheme = IconThemeData(size: 18, color: Color(0x00000002));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedIcon.color, equals(selectedIconTheme.color));
expect(selectedIcon.fontSize, equals(selectedIconTheme.size));
expect(unselectedIcon.color, equals(unselectedIconTheme.color));
expect(unselectedIcon.fontSize, equals(unselectedIconTheme.size));
});
testWidgets('color on icon theme overrides selected and unselected item colors', (WidgetTester tester) async {
const IconThemeData selectedIconTheme = IconThemeData(size: 36, color: Color(0x00000001));
const IconThemeData unselectedIconTheme = IconThemeData(size: 18, color: Color(0x00000002));
const Color selectedItemColor = Color(0x00000003);
const Color unselectedItemColor = Color(0x00000004);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
selectedItemColor: selectedItemColor,
unselectedItemColor: unselectedItemColor,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedFontStyle = tester.renderObject<RenderParagraph>(find.text('AC')).text.style!;
final TextStyle unselectedFontStyle = tester.renderObject<RenderParagraph>(find.text('Alarm')).text.style!;
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedIcon.color, equals(selectedIconTheme.color));
expect(unselectedIcon.color, equals(unselectedIconTheme.color));
expect(selectedFontStyle.color, equals(selectedItemColor));
expect(unselectedFontStyle.color, equals(unselectedItemColor));
});
testWidgets('Padding is calculated properly on items - all labels', (WidgetTester tester) async {
const double selectedFontSize = 16.0;
const double selectedIconSize = 36.0;
const double unselectedIconSize = 20.0;
const IconThemeData selectedIconTheme = IconThemeData(size: selectedIconSize);
const IconThemeData unselectedIconTheme = IconThemeData(size: unselectedIconSize);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
showSelectedLabels: true,
showUnselectedLabels: true,
selectedFontSize: selectedFontSize,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final EdgeInsets selectedItemPadding = _itemPadding(tester, Icons.ac_unit);
expect(selectedItemPadding.top, equals(selectedFontSize / 2.0));
expect(selectedItemPadding.bottom, equals(selectedFontSize / 2.0));
final EdgeInsets unselectedItemPadding = _itemPadding(tester, Icons.access_alarm);
const double expectedUnselectedPadding = (selectedIconSize - unselectedIconSize) / 2.0 + selectedFontSize / 2.0;
expect(unselectedItemPadding.top, equals(expectedUnselectedPadding));
expect(unselectedItemPadding.bottom, equals(expectedUnselectedPadding));
});
testWidgets('Padding is calculated properly on items - selected labels only', (WidgetTester tester) async {
const double selectedFontSize = 16.0;
const double selectedIconSize = 36.0;
const double unselectedIconSize = 20.0;
const IconThemeData selectedIconTheme = IconThemeData(size: selectedIconSize);
const IconThemeData unselectedIconTheme = IconThemeData(size: unselectedIconSize);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
showSelectedLabels: true,
showUnselectedLabels: false,
selectedFontSize: selectedFontSize,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final EdgeInsets selectedItemPadding = _itemPadding(tester, Icons.ac_unit);
expect(selectedItemPadding.top, equals(selectedFontSize / 2.0));
expect(selectedItemPadding.bottom, equals(selectedFontSize / 2.0));
final EdgeInsets unselectedItemPadding = _itemPadding(tester, Icons.access_alarm);
expect(unselectedItemPadding.top, equals((selectedIconSize - unselectedIconSize) / 2.0 + selectedFontSize));
expect(unselectedItemPadding.bottom, equals((selectedIconSize - unselectedIconSize) / 2.0));
});
testWidgets('Padding is calculated properly on items - no labels', (WidgetTester tester) async {
const double selectedFontSize = 16.0;
const double selectedIconSize = 36.0;
const double unselectedIconSize = 20.0;
const IconThemeData selectedIconTheme = IconThemeData(size: selectedIconSize);
const IconThemeData unselectedIconTheme = IconThemeData(size: unselectedIconSize);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
showSelectedLabels: false,
showUnselectedLabels: false,
selectedFontSize: selectedFontSize,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final EdgeInsets selectedItemPadding = _itemPadding(tester, Icons.ac_unit);
expect(selectedItemPadding.top, equals(selectedFontSize));
expect(selectedItemPadding.bottom, equals(0.0));
final EdgeInsets unselectedItemPadding = _itemPadding(tester, Icons.access_alarm);
expect(unselectedItemPadding.top, equals((selectedIconSize - unselectedIconSize) / 2.0 + selectedFontSize));
expect(unselectedItemPadding.bottom, equals((selectedIconSize - unselectedIconSize) / 2.0));
});
testWidgets('Material2 - Shifting BottomNavigationBar defaults', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
const double selectedFontSize = 14.0;
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.fontSize, selectedFontSize);
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.color, equals(Colors.white));
expect(_getOpacity(tester, 'Alarm'), equals(0.0));
expect(_getMaterial(tester).elevation, equals(8.0));
});
testWidgets('Material3 - Shifting BottomNavigationBar defaults', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
const double selectedFontSize = 14.0;
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.fontSize, selectedFontSize);
final ThemeData theme = Theme.of(tester.element(find.text('AC')));
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.color, equals(theme.colorScheme.surface));
expect(_getOpacity(tester, 'Alarm'), equals(0.0));
expect(_getMaterial(tester).elevation, equals(8.0));
});
testWidgets('Fixed BottomNavigationBar custom font size, color', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000000);
const Color unselectedWidgetColor = Color(0xFFD501FF);
const Color selectedColor = Color(0xFF0004FF);
const Color unselectedColor = Color(0xFFE5FF00);
const double selectedFontSize = 18.0;
const double unselectedFontSize = 14.0;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
primaryColor: primaryColor,
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedFontSize: selectedFontSize,
unselectedFontSize: unselectedFontSize,
selectedItemColor: selectedColor,
unselectedItemColor: unselectedColor,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.fontSize, selectedFontSize);
// Unselected label has a font size of 18 but is scaled down to be font size 14.
expect(tester.renderObject<RenderParagraph>(find.text('Alarm')).text.style!.fontSize, selectedFontSize);
expect(
tester.firstWidget<Transform>(find.ancestor(of: find.text('Alarm'), matching: find.byType(Transform))).transform,
equals(Matrix4.diagonal3(Vector3.all(unselectedFontSize / selectedFontSize))),
);
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.color, equals(selectedColor));
expect(tester.renderObject<RenderParagraph>(find.text('Alarm')).text.style!.color, equals(unselectedColor));
expect(selectedIcon.color, equals(selectedColor));
expect(unselectedIcon.color, equals(unselectedColor));
// There should not be any [Opacity] or [FadeTransition] widgets
// since showUnselectedLabels and showSelectedLabels are true.
final Finder findOpacity = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(Opacity),
);
final Finder findFadeTransition = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byType(FadeTransition),
);
expect(findOpacity, findsNothing);
expect(findFadeTransition, findsNothing);
});
testWidgets('Shifting BottomNavigationBar custom font size, color', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000000);
const Color unselectedWidgetColor = Color(0xFFD501FF);
const Color selectedColor = Color(0xFF0004FF);
const Color unselectedColor = Color(0xFFE5FF00);
const double selectedFontSize = 18.0;
const double unselectedFontSize = 14.0;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
primaryColor: primaryColor,
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
selectedFontSize: selectedFontSize,
unselectedFontSize: unselectedFontSize,
selectedItemColor: selectedColor,
unselectedItemColor: unselectedColor,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.fontSize, selectedFontSize);
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.color, equals(selectedColor));
expect(_getOpacity(tester, 'Alarm'), equals(0.0));
expect(selectedIcon.color, equals(selectedColor));
expect(unselectedIcon.color, equals(unselectedColor));
});
testWidgets('label style color should override itemColor only for the label for BottomNavigationBarType.fixed', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000000);
const Color unselectedWidgetColor = Color(0xFFD501FF);
const Color selectedColor = Color(0xFF0004FF);
const Color unselectedColor = Color(0xFFE5FF00);
const Color selectedLabelColor = Color(0xFFFF9900);
const Color unselectedLabelColor = Color(0xFF92F74E);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
primaryColor: primaryColor,
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedLabelStyle: const TextStyle(color: selectedLabelColor),
unselectedLabelStyle: const TextStyle(color: unselectedLabelColor),
selectedItemColor: selectedColor,
unselectedItemColor: unselectedColor,
useLegacyColorScheme: false,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedIcon.color, equals(selectedColor));
expect(unselectedIcon.color, equals(unselectedColor));
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.color, equals(selectedLabelColor));
expect(tester.renderObject<RenderParagraph>(find.text('Alarm')).text.style!.color, equals(unselectedLabelColor));
});
testWidgets('label style color should override itemColor only for the label for BottomNavigationBarType.shifting', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000000);
const Color unselectedWidgetColor = Color(0xFFD501FF);
const Color selectedColor = Color(0xFF0004FF);
const Color unselectedColor = Color(0xFFE5FF00);
const Color selectedLabelColor = Color(0xFFFF9900);
const Color unselectedLabelColor = Color(0xFF92F74E);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
primaryColor: primaryColor,
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
selectedLabelStyle: const TextStyle(color: selectedLabelColor),
unselectedLabelStyle: const TextStyle(color: unselectedLabelColor),
selectedItemColor: selectedColor,
unselectedItemColor: unselectedColor,
useLegacyColorScheme: false,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedIcon.color, equals(selectedColor));
expect(unselectedIcon.color, equals(unselectedColor));
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.color, equals(selectedLabelColor));
expect(tester.renderObject<RenderParagraph>(find.text('Alarm')).text.style!.color, equals(unselectedLabelColor));
});
testWidgets('iconTheme color should override itemColor for BottomNavigationBarType.fixed', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000000);
const Color unselectedWidgetColor = Color(0xFFD501FF);
const Color selectedColor = Color(0xFF0004FF);
const Color unselectedColor = Color(0xFFE5FF00);
const Color selectedLabelColor = Color(0xFFFF9900);
const Color unselectedLabelColor = Color(0xFF92F74E);
const Color selectedIconThemeColor = Color(0xFF1E7723);
const Color unselectedIconThemeColor = Color(0xFF009688);
const IconThemeData selectedIconTheme = IconThemeData(size: 20, color: selectedIconThemeColor);
const IconThemeData unselectedIconTheme = IconThemeData(size: 18, color: unselectedIconThemeColor);
const TextStyle selectedTextStyle = TextStyle(fontSize: 18.0, color: selectedLabelColor);
const TextStyle unselectedTextStyle = TextStyle(fontSize: 18.0, color: unselectedLabelColor);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
primaryColor: primaryColor,
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedLabelStyle: selectedTextStyle,
unselectedLabelStyle: unselectedTextStyle,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
selectedItemColor: selectedColor,
unselectedItemColor: unselectedColor,
useLegacyColorScheme: false,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedIcon.color, equals(selectedIconThemeColor));
expect(unselectedIcon.color, equals(unselectedIconThemeColor));
});
testWidgets('iconTheme color should override itemColor for BottomNavigationBarType.shifted', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000000);
const Color unselectedWidgetColor = Color(0xFFD501FF);
const Color selectedLabelColor = Color(0xFFFF9900);
const Color unselectedLabelColor = Color(0xFF92F74E);
const Color selectedIconThemeColor = Color(0xFF1E7723);
const Color unselectedIconThemeColor = Color(0xFF009688);
const IconThemeData selectedIconTheme = IconThemeData(size: 20, color: selectedIconThemeColor);
const IconThemeData unselectedIconTheme = IconThemeData(size: 18, color: unselectedIconThemeColor);
const TextStyle selectedTextStyle = TextStyle(fontSize: 18.0, color: selectedLabelColor);
const TextStyle unselectedTextStyle = TextStyle(fontSize: 18.0, color: unselectedLabelColor);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
primaryColor: primaryColor,
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
selectedLabelStyle: selectedTextStyle,
unselectedLabelStyle: unselectedTextStyle,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
useLegacyColorScheme: false,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedIcon.color, equals(selectedIconThemeColor));
expect(unselectedIcon.color, equals(unselectedIconThemeColor));
});
testWidgets('iconTheme color should override itemColor color for BottomNavigationBarType.fixed', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000000);
const Color unselectedWidgetColor = Color(0xFFD501FF);
const Color selectedIconThemeColor = Color(0xFF1E7723);
const Color unselectedIconThemeColor = Color(0xFF009688);
const IconThemeData selectedIconTheme = IconThemeData(size: 20, color: selectedIconThemeColor);
const IconThemeData unselectedIconTheme = IconThemeData(size: 18, color: unselectedIconThemeColor);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
primaryColor: primaryColor,
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
useLegacyColorScheme: false,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedIcon.color, equals(selectedIconThemeColor));
expect(unselectedIcon.color, equals(unselectedIconThemeColor));
});
testWidgets('iconTheme color should override itemColor for BottomNavigationBarType.shifted', (WidgetTester tester) async {
const Color primaryColor = Color(0xFF000000);
const Color unselectedWidgetColor = Color(0xFFD501FF);
const Color selectedColor = Color(0xFF0004FF);
const Color unselectedColor = Color(0xFFE5FF00);
const Color selectedIconThemeColor = Color(0xFF1E7723);
const Color unselectedIconThemeColor = Color(0xFF009688);
const IconThemeData selectedIconTheme = IconThemeData(size: 20, color: selectedIconThemeColor);
const IconThemeData unselectedIconTheme = IconThemeData(size: 18, color: unselectedIconThemeColor);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
primaryColor: primaryColor,
unselectedWidgetColor: unselectedWidgetColor,
),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
selectedIconTheme: selectedIconTheme,
unselectedIconTheme: unselectedIconTheme,
selectedItemColor: selectedColor,
unselectedItemColor: unselectedColor,
useLegacyColorScheme: false,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
final TextStyle selectedIcon = _iconStyle(tester, Icons.ac_unit);
final TextStyle unselectedIcon = _iconStyle(tester, Icons.access_alarm);
expect(selectedIcon.color, equals(selectedIconThemeColor));
expect(unselectedIcon.color, equals(unselectedIconThemeColor));
});
testWidgets('Fixed BottomNavigationBar can hide unselected labels', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
showUnselectedLabels: false,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
expect(_getOpacity(tester, 'AC'), equals(1.0));
expect(_getOpacity(tester, 'Alarm'), equals(0.0));
});
testWidgets('Fixed BottomNavigationBar can update background color', (WidgetTester tester) async {
const Color color = Colors.yellow;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: color,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
expect(_getMaterial(tester).color, equals(color));
});
testWidgets('Shifting BottomNavigationBar background color is overridden by item color', (WidgetTester tester) async {
const Color itemColor = Colors.yellow;
const Color backgroundColor = Colors.blue;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
backgroundColor: backgroundColor,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
backgroundColor: itemColor,
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
expect(_getMaterial(tester).color, equals(itemColor));
});
testWidgets('Specifying both selectedItemColor and fixedColor asserts', (WidgetTester tester) async {
expect(
() {
return BottomNavigationBar(
selectedItemColor: Colors.black,
fixedColor: Colors.black,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
);
},
throwsAssertionError,
);
});
testWidgets('Fixed BottomNavigationBar uses fixedColor when selectedItemColor not provided', (WidgetTester tester) async {
const Color fixedColor = Colors.black;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
fixedColor: fixedColor,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
expect(tester.renderObject<RenderParagraph>(find.text('AC')).text.style!.color, equals(fixedColor));
});
testWidgets('setting selectedFontSize to zero hides all labels', (WidgetTester tester) async {
const double customElevation = 3.0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
elevation: customElevation,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
expect(_getMaterial(tester).elevation, equals(customElevation));
});
testWidgets('Material2 - BottomNavigationBar adds bottom padding to height', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: MediaQuery(
data: const MediaQueryData(viewPadding: EdgeInsets.only(bottom: 40.0)),
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
),
);
const double expectedHeight = kBottomNavigationBarHeight + 40.0;
expect(tester.getSize(find.byType(BottomNavigationBar)).height, expectedHeight);
});
testWidgets('Material3 - BottomNavigationBar adds bottom padding to height', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(viewPadding: EdgeInsets.only(bottom: 40.0)),
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
),
);
const double expectedMinHeight = kBottomNavigationBarHeight + 40.0;
expect(tester.getSize(find.byType(BottomNavigationBar)).height >= expectedMinHeight, isTrue);
});
testWidgets('BottomNavigationBar adds bottom padding to height with a custom font size', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(viewPadding: EdgeInsets.only(bottom: 40.0)),
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
selectedFontSize: 8,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
),
);
const double expectedHeight = kBottomNavigationBarHeight + 40.0;
expect(tester.getSize(find.byType(BottomNavigationBar)).height, expectedHeight);
});
testWidgets('BottomNavigationBar height will not change when toggle keyboard', (WidgetTester tester) async {
final Widget child = Scaffold(
bottomNavigationBar: BottomNavigationBar(
selectedFontSize: 8,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
);
// Test the bar height is correct when not showing the keyboard.
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(
viewPadding: EdgeInsets.only(bottom: 40.0),
padding: EdgeInsets.only(bottom: 40.0),
),
child: child,
),
),
);
// Expect the height is the correct.
const double expectedHeight = kBottomNavigationBarHeight + 40.0;
expect(tester.getSize(find.byType(BottomNavigationBar)).height, expectedHeight);
// Now we show the keyboard.
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(
viewPadding: EdgeInsets.only(bottom: 40.0),
viewInsets: EdgeInsets.only(bottom: 336.0),
),
child: child,
),
),
);
// Expect the height is the same.
expect(tester.getSize(find.byType(BottomNavigationBar)).height, expectedHeight);
});
testWidgets('BottomNavigationBar action size test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
Iterable<RenderBox> actions = tester.renderObjectList(find.byType(InkResponse));
expect(actions.length, 2);
expect(actions.elementAt(0).size.width, 480.0);
expect(actions.elementAt(1).size.width, 320.0);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
currentIndex: 1,
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
),
);
await tester.pump(const Duration(milliseconds: 200));
actions = tester.renderObjectList(find.byType(InkResponse));
expect(actions.length, 2);
expect(actions.elementAt(0).size.width, 320.0);
expect(actions.elementAt(1).size.width, 480.0);
});
testWidgets('BottomNavigationBar multiple taps test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_time),
label: 'Time',
),
BottomNavigationBarItem(
icon: Icon(Icons.add),
label: 'Add',
),
],
),
),
),
);
// We want to make sure that the last label does not get displaced,
// irrespective of how many taps happen on the first N - 1 labels and how
// they grow.
Iterable<RenderBox> actions = tester.renderObjectList(find.byType(InkResponse));
final Offset originalOrigin = actions.elementAt(3).localToGlobal(Offset.zero);
await tester.tap(find.text('AC'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
actions = tester.renderObjectList(find.byType(InkResponse));
expect(actions.elementAt(3).localToGlobal(Offset.zero), equals(originalOrigin));
await tester.tap(find.text('Alarm'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
actions = tester.renderObjectList(find.byType(InkResponse));
expect(actions.elementAt(3).localToGlobal(Offset.zero), equals(originalOrigin));
await tester.tap(find.text('Time'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
actions = tester.renderObjectList(find.byType(InkResponse));
expect(actions.elementAt(3).localToGlobal(Offset.zero), equals(originalOrigin));
});
testWidgets('BottomNavigationBar inherits shadowed app theme for shifting navbar', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(brightness: Brightness.light),
home: Theme(
data: ThemeData(brightness: Brightness.dark),
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_time),
label: 'Time',
),
BottomNavigationBarItem(
icon: Icon(Icons.add),
label: 'Add',
),
],
),
),
),
),
);
await tester.tap(find.text('Alarm'));
await tester.pump(const Duration(seconds: 1));
expect(Theme.of(tester.element(find.text('Alarm'))).brightness, equals(Brightness.dark));
});
testWidgets('BottomNavigationBar inherits shadowed app theme for fixed navbar', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(brightness: Brightness.light),
home: Theme(
data: ThemeData(brightness: Brightness.dark),
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_time),
label: 'Time',
),
BottomNavigationBarItem(
icon: Icon(Icons.add),
label: 'Add',
),
],
),
),
),
),
);
await tester.tap(find.text('Alarm'));
await tester.pump(const Duration(seconds: 1));
expect(Theme.of(tester.element(find.text('Alarm'))).brightness, equals(Brightness.dark));
});
testWidgets('BottomNavigationBar iconSize test', (WidgetTester tester) async {
late double builderIconSize;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
iconSize: 12.0,
items: <BottomNavigationBarItem>[
const BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Builder(
builder: (BuildContext context) {
builderIconSize = IconTheme.of(context).size!;
return SizedBox(
width: builderIconSize,
height: builderIconSize,
);
},
),
),
],
),
),
),
);
final RenderBox box = tester.renderObject(find.byType(Icon));
expect(box.size.width, equals(12.0));
expect(box.size.height, equals(12.0));
expect(builderIconSize, 12.0);
});
testWidgets('Material2 - BottomNavigationBar responds to textScaleFactor', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
);
final RenderBox defaultBox = tester.renderObject(find.byType(BottomNavigationBar));
expect(defaultBox.size.height, equals(kBottomNavigationBarHeight));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
);
final RenderBox shiftingBox = tester.renderObject(find.byType(BottomNavigationBar));
expect(shiftingBox.size.height, equals(kBottomNavigationBarHeight));
await tester.pumpWidget(
MaterialApp(
home: MediaQuery.withClampedTextScaling(
minScaleFactor: 2.0,
maxScaleFactor: 2.0,
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
),
);
final RenderBox box = tester.renderObject(find.byType(BottomNavigationBar));
expect(box.size.height, equals(56.0));
});
testWidgets('Material3 - BottomNavigationBar responds to textScaleFactor', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
);
final RenderBox defaultBox = tester.renderObject(find.byType(BottomNavigationBar));
// kBottomNavigationBarHeight is a minimum dimension.
expect(defaultBox.size.height, greaterThanOrEqualTo(kBottomNavigationBarHeight));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
);
final RenderBox shiftingBox = tester.renderObject(find.byType(BottomNavigationBar));
// kBottomNavigationBarHeight is a minimum dimension.
expect(shiftingBox.size.height, greaterThanOrEqualTo(kBottomNavigationBarHeight));
await tester.pumpWidget(
MaterialApp(
home: MediaQuery.withClampedTextScaling(
minScaleFactor: 2.0,
maxScaleFactor: 2.0,
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
),
);
final RenderBox box = tester.renderObject(find.byType(BottomNavigationBar));
// kBottomNavigationBarHeight is a minimum dimension.
expect(box.size.height, greaterThanOrEqualTo(kBottomNavigationBarHeight));
});
testWidgets('Material2 - BottomNavigationBar does not grow with textScaleFactor when labels are provided', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
);
final RenderBox defaultBox = tester.renderObject(find.byType(BottomNavigationBar));
expect(defaultBox.size.height, equals(kBottomNavigationBarHeight));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
);
final RenderBox shiftingBox = tester.renderObject(find.byType(BottomNavigationBar));
expect(shiftingBox.size.height, equals(kBottomNavigationBarHeight));
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(textScaler: TextScaler.linear(2.0)),
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
),
);
final RenderBox box = tester.renderObject(find.byType(BottomNavigationBar));
expect(box.size.height, equals(kBottomNavigationBarHeight));
});
testWidgets('Material3 - BottomNavigationBar does not grow with textScaleFactor when labels are provided', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
);
final RenderBox defaultBox = tester.renderObject(find.byType(BottomNavigationBar));
// kBottomNavigationBarHeight is a minimum dimension.
expect(defaultBox.size.height, greaterThanOrEqualTo(kBottomNavigationBarHeight));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
);
final RenderBox shiftingBox = tester.renderObject(find.byType(BottomNavigationBar));
// kBottomNavigationBarHeight is a minimum dimension.
expect(shiftingBox.size.height, greaterThanOrEqualTo(kBottomNavigationBarHeight));
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(textScaler: TextScaler.linear(2.0)),
child: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
),
);
final RenderBox box = tester.renderObject(find.byType(BottomNavigationBar));
expect(box.size.height, equals(defaultBox.size.height));
expect(box.size.height, equals(shiftingBox.size.height));
});
testWidgets('Material2 - BottomNavigationBar shows tool tips with text scaling on long press when labels are provided', (WidgetTester tester) async {
const String label = 'Foo';
Widget buildApp({ required double textScaleFactor }) {
return MediaQuery.withClampedTextScaling(
minScaleFactor: textScaleFactor,
maxScaleFactor: textScaleFactor,
child: Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: Directionality(
textDirection: TextDirection.ltr,
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
builder: (BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: label,
icon: Icon(Icons.ac_unit),
tooltip: label,
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
);
},
);
},
),
),
),
);
}
await tester.pumpWidget(buildApp(textScaleFactor: 1.0));
expect(find.text(label), findsOneWidget);
await tester.longPress(find.text(label));
expect(find.text(label), findsNWidgets(2));
expect(tester.getSize(find.text(label).last), equals(const Size(42.0, 14.0)));
await tester.pumpAndSettle(const Duration(seconds: 2));
await tester.pumpWidget(buildApp(textScaleFactor: 4.0));
expect(find.text(label), findsOneWidget);
await tester.longPress(find.text(label));
expect(tester.getSize(find.text(label).last), equals(const Size(168.0, 56.0)));
});
testWidgets('Material3 - BottomNavigationBar shows tool tips with text scaling on long press when labels are provided', (WidgetTester tester) async {
const String label = 'Foo';
Widget buildApp({ required TextScaler textScaler }) {
return MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: Directionality(
textDirection: TextDirection.ltr,
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
builder: (BuildContext context) {
return MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: label,
icon: Icon(Icons.ac_unit),
tooltip: label,
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
);
},
);
},
),
),
),
);
}
await tester.pumpWidget(buildApp(textScaler: TextScaler.noScaling));
expect(find.text(label), findsOneWidget);
await tester.longPress(find.text(label));
expect(find.text(label), findsNWidgets(2));
expect(tester.getSize(find.text(label).last).height, equals(20.0));
await tester.pumpAndSettle(const Duration(seconds: 2));
await tester.pumpWidget(buildApp(textScaler: const TextScaler.linear(4.0)));
expect(find.text(label), findsOneWidget);
await tester.longPress(find.text(label));
expect(tester.getSize(find.text(label).last).height, equals(80.0));
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('Different behaviour of tool tip in BottomNavigationBarItem', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
tooltip: 'A tooltip',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
BottomNavigationBarItem(
label: 'C',
icon: Icon(Icons.cake),
tooltip: '',
),
],
),
),
),
);
expect(find.text('A'), findsOneWidget);
await tester.longPress(find.text('A'));
expect(find.byTooltip('A tooltip'), findsOneWidget);
expect(find.text('B'), findsOneWidget);
await tester.longPress(find.text('B'));
expect(find.byTooltip('B'), findsNothing);
expect(find.text('C'), findsOneWidget);
await tester.longPress(find.text('C'));
expect(find.byTooltip('C'), findsNothing);
});
testWidgets('BottomNavigationBar limits width of tiles with long labels', (WidgetTester tester) async {
final String longTextA = List<String>.generate(100, (int index) => 'A').toString();
final String longTextB = List<String>.generate(100, (int index) => 'B').toString();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: longTextA,
icon: const Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: longTextB,
icon: const Icon(Icons.battery_alert),
),
],
),
),
),
);
final RenderBox box = tester.renderObject(find.byType(BottomNavigationBar));
expect(box.size.height, greaterThanOrEqualTo(kBottomNavigationBarHeight));
final RenderBox itemBoxA = tester.renderObject(find.text(longTextA));
expect(itemBoxA.size.width, equals(400.0));
final RenderBox itemBoxB = tester.renderObject(find.text(longTextB));
expect(itemBoxB.size.width, equals(400.0));
});
testWidgets('Material2 - BottomNavigationBar paints circles', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
useMaterial3: false,
textDirection: TextDirection.ltr,
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
);
final RenderBox box = tester.renderObject(find.byType(BottomNavigationBar));
expect(box, isNot(paints..circle()));
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 20));
expect(box, paints..circle(x: 200.0));
await tester.tap(find.text('B'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 20));
expect(box, paints..circle(x: 200.0)..translate(x: 400.0)..circle(x: 200.0));
// Now we flip the directionality and verify that the circles switch positions.
await tester.pumpWidget(
boilerplate(
useMaterial3: false,
textDirection: TextDirection.rtl,
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
);
expect(box, paints..translate()..save()..translate(x: 400.0)..circle(x: 200.0)..restore()..circle(x: 200.0));
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 20));
expect(
box,
paints
..translate(x: 0.0, y: 0.0)
..save()
..translate(x: 400.0)
..circle(x: 200.0)
..restore()
..circle(x: 200.0)
..translate(x: 400.0)
..circle(x: 200.0),
);
});
testWidgets('BottomNavigationBar inactiveIcon shown', (WidgetTester tester) async {
const Key filled = Key('filled');
const Key stroked = Key('stroked');
int selectedItem = 0;
await tester.pumpWidget(
boilerplate(
textDirection: TextDirection.ltr,
bottomNavigationBar: BottomNavigationBar(
currentIndex: selectedItem,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
activeIcon: Icon(Icons.favorite, key: filled),
icon: Icon(Icons.favorite_border, key: stroked),
label: 'Favorite',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
);
expect(find.byKey(filled), findsOneWidget);
expect(find.byKey(stroked), findsNothing);
selectedItem = 1;
await tester.pumpWidget(
boilerplate(
textDirection: TextDirection.ltr,
bottomNavigationBar: BottomNavigationBar(
currentIndex: selectedItem,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
activeIcon: Icon(Icons.favorite, key: filled),
icon: Icon(Icons.favorite_border, key: stroked),
label: 'Favorite',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
);
expect(find.byKey(filled), findsNothing);
expect(find.byKey(stroked), findsOneWidget);
});
testWidgets('BottomNavigationBar.fixed semantics', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
textDirection: TextDirection.ltr,
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
BottomNavigationBarItem(
icon: Icon(Icons.hot_tub),
label: 'Hot Tub',
),
],
),
),
);
expect(
tester.getSemantics(find.text('AC')),
matchesSemantics(
label: 'AC\nTab 1 of 3',
textDirection: TextDirection.ltr,
isFocusable: true,
isSelected: true,
hasTapAction: true,
),
);
expect(
tester.getSemantics(find.text('Alarm')),
matchesSemantics(
label: 'Alarm\nTab 2 of 3',
textDirection: TextDirection.ltr,
isFocusable: true,
hasTapAction: true,
),
);
expect(
tester.getSemantics(find.text('Hot Tub')),
matchesSemantics(
label: 'Hot Tub\nTab 3 of 3',
textDirection: TextDirection.ltr,
isFocusable: true,
hasTapAction: true,
),
);
});
testWidgets('BottomNavigationBar.shifting semantics', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
textDirection: TextDirection.ltr,
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
BottomNavigationBarItem(
icon: Icon(Icons.hot_tub),
label: 'Hot Tub',
),
],
),
),
);
expect(
tester.getSemantics(find.text('AC')),
matchesSemantics(
label: 'AC\nTab 1 of 3',
textDirection: TextDirection.ltr,
isFocusable: true,
isSelected: true,
hasTapAction: true,
),
);
expect(
tester.getSemantics(find.text('Alarm')),
matchesSemantics(
label: 'Alarm\nTab 2 of 3',
textDirection: TextDirection.ltr,
isFocusable: true,
hasTapAction: true,
),
);
expect(
tester.getSemantics(find.text('Hot Tub')),
matchesSemantics(
label: 'Hot Tub\nTab 3 of 3',
textDirection: TextDirection.ltr,
isFocusable: true,
hasTapAction: true,
),
);
});
testWidgets('BottomNavigationBar handles items.length changes', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/10322
Widget buildFrame(int itemCount) {
return MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: List<BottomNavigationBarItem>.generate(itemCount, (int itemIndex) {
return BottomNavigationBarItem(
icon: const Icon(Icons.android),
label: 'item $itemIndex',
);
}),
),
),
);
}
await tester.pumpWidget(buildFrame(3));
expect(find.text('item 0'), findsOneWidget);
expect(find.text('item 1'), findsOneWidget);
expect(find.text('item 2'), findsOneWidget);
expect(find.text('item 3'), findsNothing);
await tester.pumpWidget(buildFrame(4));
expect(find.text('item 0'), findsOneWidget);
expect(find.text('item 1'), findsOneWidget);
expect(find.text('item 2'), findsOneWidget);
expect(find.text('item 3'), findsOneWidget);
await tester.pumpWidget(buildFrame(2));
expect(find.text('item 0'), findsOneWidget);
expect(find.text('item 1'), findsOneWidget);
expect(find.text('item 2'), findsNothing);
expect(find.text('item 3'), findsNothing);
});
testWidgets('BottomNavigationBar change backgroundColor test', (WidgetTester tester) async {
// Regression test for: https://github.com/flutter/flutter/issues/19653
Color backgroundColor = Colors.red;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
body: Center(
child: ElevatedButton(
child: const Text('green'),
onPressed: () {
setState(() {
backgroundColor = Colors.green;
});
},
),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Page 1',
backgroundColor: backgroundColor,
icon: const Icon(Icons.dashboard),
),
BottomNavigationBarItem(
label: 'Page 2',
backgroundColor: backgroundColor,
icon: const Icon(Icons.menu),
),
],
),
);
},
),
),
);
final Finder backgroundMaterial = find.descendant(
of: find.byType(BottomNavigationBar),
matching: find.byWidgetPredicate((Widget w) {
if (w is Material) {
return w.type == MaterialType.canvas;
}
return false;
}),
);
expect(backgroundColor, Colors.red);
expect(tester.widget<Material>(backgroundMaterial).color, Colors.red);
await tester.tap(find.text('green'));
await tester.pumpAndSettle();
expect(backgroundColor, Colors.green);
expect(tester.widget<Material>(backgroundMaterial).color, Colors.green);
});
group('Material2 - BottomNavigationBar shifting backgroundColor with transition', () {
// Regression test for: https://github.com/flutter/flutter/issues/22226
Widget runTest() {
int currentIndex = 0;
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
bottomNavigationBar: RepaintBoundary(
child: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
currentIndex: currentIndex,
onTap: (int index) {
setState(() {
currentIndex = index;
});
},
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Red',
backgroundColor: Colors.red,
icon: Icon(Icons.dashboard),
),
BottomNavigationBarItem(
label: 'Green',
backgroundColor: Colors.green,
icon: Icon(Icons.menu),
),
],
),
),
);
},
),
);
}
for (int pump = 1; pump < 9; pump++) {
testWidgets('pump $pump', (WidgetTester tester) async {
await tester.pumpWidget(runTest());
await tester.tap(find.text('Green'));
for (int i = 0; i < pump; i++) {
await tester.pump(const Duration(milliseconds: 30));
}
await expectLater(
find.byType(BottomNavigationBar),
matchesGoldenFile('m2_bottom_navigation_bar.shifting_transition.${pump - 1}.png'),
);
});
}
});
group('Material3 - BottomNavigationBar shifting backgroundColor with transition', () {
// Regression test for: https://github.com/flutter/flutter/issues/22226
Widget runTest() {
int currentIndex = 0;
return MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
bottomNavigationBar: RepaintBoundary(
child: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
currentIndex: currentIndex,
onTap: (int index) {
setState(() {
currentIndex = index;
});
},
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Red',
backgroundColor: Colors.red,
icon: Icon(Icons.dashboard),
),
BottomNavigationBarItem(
label: 'Green',
backgroundColor: Colors.green,
icon: Icon(Icons.menu),
),
],
),
),
);
},
),
);
}
for (int pump = 1; pump < 9; pump++) {
testWidgets('pump $pump', (WidgetTester tester) async {
await tester.pumpWidget(runTest());
await tester.tap(find.text('Green'));
for (int i = 0; i < pump; i++) {
await tester.pump(const Duration(milliseconds: 30));
}
await expectLater(
find.byType(BottomNavigationBar),
matchesGoldenFile('m3_bottom_navigation_bar.shifting_transition.${pump - 1}.png'),
);
});
}
});
testWidgets('BottomNavigationBar item label should not be nullable', (WidgetTester tester) async {
expect(() {
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'AC',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
),
],
),
),
);
}, throwsAssertionError);
});
testWidgets(
'BottomNavigationBar [showSelectedLabels]=false and [showUnselectedLabels]=false '
'for shifting navbar, expect that there is no rendered text',
(WidgetTester tester) async {
final Widget widget = MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Red',
backgroundColor: Colors.red,
icon: Icon(Icons.dashboard),
),
BottomNavigationBarItem(
label: 'Green',
backgroundColor: Colors.green,
icon: Icon(Icons.menu),
),
],
),
);
},
),
);
await tester.pumpWidget(widget);
expect(find.text('Red'), findsOneWidget);
expect(find.text('Green'), findsOneWidget);
expect(tester.widget<Visibility>(find.byType(Visibility).first).visible, false);
expect(tester.widget<Visibility>(find.byType(Visibility).last).visible, false);
},
);
testWidgets(
'BottomNavigationBar [showSelectedLabels]=false and [showUnselectedLabels]=false '
'for fixed navbar, expect that there is no rendered text',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Red',
backgroundColor: Colors.red,
icon: Icon(Icons.dashboard),
),
BottomNavigationBarItem(
label: 'Green',
backgroundColor: Colors.green,
icon: Icon(Icons.menu),
),
],
),
);
},
),
),
);
expect(find.text('Red'), findsOneWidget);
expect(find.text('Green'), findsOneWidget);
expect(tester.widget<Visibility>(find.byType(Visibility).first).visible, false);
expect(tester.widget<Visibility>(find.byType(Visibility).last).visible, false);
},
);
testWidgets('BottomNavigationBar.fixed [showSelectedLabels]=false and [showUnselectedLabels]=false semantics', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
textDirection: TextDirection.ltr,
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'Red',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Green',
),
],
),
),
);
expect(
tester.getSemantics(find.text('Red')),
matchesSemantics(
label: 'Red\nTab 1 of 2',
textDirection: TextDirection.ltr,
isFocusable: true,
isSelected: true,
hasTapAction: true,
),
);
expect(
tester.getSemantics(find.text('Green')),
matchesSemantics(
label: 'Green\nTab 2 of 2',
textDirection: TextDirection.ltr,
isFocusable: true,
hasTapAction: true,
),
);
});
testWidgets('BottomNavigationBar.shifting [showSelectedLabels]=false and [showUnselectedLabels]=false semantics', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
textDirection: TextDirection.ltr,
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
type: BottomNavigationBarType.shifting,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.ac_unit),
label: 'Red',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_alarm),
label: 'Green',
),
],
),
),
);
expect(
tester.getSemantics(find.text('Red')),
matchesSemantics(
label: 'Red\nTab 1 of 2',
textDirection: TextDirection.ltr,
isFocusable: true,
isSelected: true,
hasTapAction: true,
),
);
expect(
tester.getSemantics(find.text('Green')),
matchesSemantics(
label: 'Green\nTab 2 of 2',
textDirection: TextDirection.ltr,
isFocusable: true,
hasTapAction: true,
),
);
});
testWidgets('BottomNavigationBar changes mouse cursor when the tile is hovered over', (WidgetTester tester) async {
// Test BottomNavigationBar() constructor
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: BottomNavigationBar(
mouseCursor: SystemMouseCursors.text,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.ac_unit), label: 'AC'),
BottomNavigationBarItem(icon: Icon(Icons.access_alarm), label: 'Alarm'),
],
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.text('AC')));
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test default cursor
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.ac_unit), label: 'AC'),
BottomNavigationBarItem(icon: Icon(Icons.access_alarm), label: 'Alarm'),
],
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
});
group('feedback', () {
late FeedbackTester feedback;
setUp(() {
feedback = FeedbackTester();
});
tearDown(() {
feedback.dispose();
});
Widget feedbackBoilerplate({bool? enableFeedback, bool? enableFeedbackTheme}) {
return MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBarTheme(
data: BottomNavigationBarThemeData(
enableFeedback: enableFeedbackTheme,
),
child: BottomNavigationBar(
enableFeedback: enableFeedback,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.ac_unit), label: 'AC'),
BottomNavigationBarItem(icon: Icon(Icons.access_alarm), label: 'Alarm'),
],
),
),
),
);
}
testWidgets('BottomNavigationBar with enabled feedback', (WidgetTester tester) async {
const bool enableFeedback = true;
await tester.pumpWidget(feedbackBoilerplate(enableFeedback: enableFeedback));
await tester.tap(find.byType(InkResponse).first);
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
});
testWidgets('BottomNavigationBar with disabled feedback', (WidgetTester tester) async {
const bool enableFeedback = false;
await tester.pumpWidget(feedbackBoilerplate(enableFeedback: enableFeedback));
await tester.tap(find.byType(InkResponse).first);
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 0);
expect(feedback.hapticCount, 0);
});
testWidgets('BottomNavigationBar with enabled feedback by default', (WidgetTester tester) async {
await tester.pumpWidget(feedbackBoilerplate());
await tester.tap(find.byType(InkResponse).first);
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
});
testWidgets('BottomNavigationBar with disabled feedback using BottomNavigationBarTheme', (WidgetTester tester) async {
const bool enableFeedbackTheme = false;
await tester.pumpWidget(feedbackBoilerplate(enableFeedbackTheme: enableFeedbackTheme));
await tester.tap(find.byType(InkResponse).first);
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 0);
expect(feedback.hapticCount, 0);
});
testWidgets('BottomNavigationBar.enableFeedback overrides BottomNavigationBarTheme.enableFeedback', (WidgetTester tester) async {
const bool enableFeedbackTheme = false;
const bool enableFeedback = true;
await tester.pumpWidget(feedbackBoilerplate(
enableFeedbackTheme: enableFeedbackTheme,
enableFeedback: enableFeedback,
));
await tester.tap(find.byType(InkResponse).first);
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
});
});
testWidgets('BottomNavigationBar excludes semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'A',
icon: Icon(Icons.ac_unit),
),
BottomNavigationBarItem(
label: 'B',
icon: Icon(Icons.battery_alert),
),
],
),
),
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isSelected,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'A\nTab 1 of 2',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.isFocusable],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'B\nTab 2 of 2',
textDirection: TextDirection.ltr,
),
],
),
],
),
],
),
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
),
);
semantics.dispose();
});
testWidgets('Material2 - BottomNavigationBar default layout', (WidgetTester tester) async {
final Key icon0 = UniqueKey();
final Key icon1 = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: SizedBox(key: icon0, width: 200, height: 10),
label: 'Title0',
),
BottomNavigationBarItem(
icon: SizedBox(key: icon1, width: 200, height: 10),
label: 'Title1',
),
],
),
);
},
),
),
);
expect(tester.getSize(find.byType(BottomNavigationBar)), const Size(800, kBottomNavigationBarHeight));
expect(tester.getRect(find.byType(BottomNavigationBar)), const Rect.fromLTRB(0, 600 - kBottomNavigationBarHeight, 800, 600));
// The height of the navigation bar is kBottomNavigationBarHeight = 56
// The top of the navigation bar is 600 - 56 = 544
// The top and bottom of the selected item is defined by its centered icon/label column:
// top = 544 + ((56 - (10 + 10)) / 2) = 562
// bottom = top + 10 + 10 = 582
expect(tester.getRect(find.byKey(icon0)).top, 560.0);
expect(tester.getRect(find.text('Title0')).bottom, 584.0);
// The items are padded horizontally according to
// MainAxisAlignment.spaceAround. Left/right padding is:
// 800 - (200 * 2) / 4 = 100
// The layout of the unselected item's label is slightly different; not
// checking that here.
expect(tester.getRect(find.text('Title0')), const Rect.fromLTRB(158.0, 570.0, 242.0, 584.0));
expect(tester.getRect(find.byKey(icon0)), const Rect.fromLTRB(100.0, 560.0, 300.0, 570.0));
expect(tester.getRect(find.byKey(icon1)), const Rect.fromLTRB(500.0, 560.0, 700.0, 570.0));
});
testWidgets('Material3 - BottomNavigationBar default layout', (WidgetTester tester) async {
final Key icon0 = UniqueKey();
final Key icon1 = UniqueKey();
const double iconHeight = 10;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: SizedBox(key: icon0, width: 200, height: iconHeight),
label: 'Title0',
),
BottomNavigationBarItem(
icon: SizedBox(key: icon1, width: 200, height: iconHeight),
label: 'Title1',
),
],
),
);
},
),
),
);
expect(tester.getSize(find.byType(BottomNavigationBar)), const Size(800, kBottomNavigationBarHeight));
expect(tester.getRect(find.byType(BottomNavigationBar)), const Rect.fromLTRB(0, 600 - kBottomNavigationBarHeight, 800, 600));
const double navigationBarTop = 600 - kBottomNavigationBarHeight; // 544
const double selectedFontSize = 14.0;
const double m3LineHeight = 1.43;
final double labelHeight = (selectedFontSize * m3LineHeight).floorToDouble(); // 20
const double navigationTileVerticalPadding = selectedFontSize / 2; // 7.0
final double navigationTileHeight = iconHeight + labelHeight + 2 * navigationTileVerticalPadding;
// Navigation tiles parent is a Row with crossAxisAlignment set to center.
final double navigationTileVerticalOffset = (kBottomNavigationBarHeight - navigationTileHeight) / 2;
final double iconTop = navigationBarTop + navigationTileVerticalOffset + navigationTileVerticalPadding;
final double labelBottom = 600 - (navigationTileVerticalOffset + navigationTileVerticalPadding);
expect(tester.getRect(find.byKey(icon0)).top, iconTop);
expect(tester.getRect(find.text('Title0')).bottom, labelBottom);
// The items are padded horizontally according to
// MainAxisAlignment.spaceAround. Left/right padding is:
// 800 - (200 * 2) / 4 = 100
// The layout of the unselected item's label is slightly different; not
// checking that here.
final double firstLabelWidth = tester.getSize(find.text('Title0')).width;
const double itemsWidth = 800 / 2; // 2 items.
const double firstLabelCenter = itemsWidth / 2;
expect(
tester.getRect(find.text('Title0')),
Rect.fromLTRB(
firstLabelCenter - firstLabelWidth / 2,
labelBottom - labelHeight,
firstLabelCenter + firstLabelWidth / 2,
labelBottom,
),
);
expect(tester.getRect(find.byKey(icon0)), Rect.fromLTRB(100.0, iconTop, 300.0, iconTop + iconHeight));
expect(tester.getRect(find.byKey(icon1)), Rect.fromLTRB(500.0, iconTop, 700.0, iconTop + iconHeight));
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('Material2 - BottomNavigationBar centered landscape layout', (WidgetTester tester) async {
final Key icon0 = UniqueKey();
final Key icon1 = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
landscapeLayout: BottomNavigationBarLandscapeLayout.centered,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: SizedBox(key: icon0, width: 200, height: 10),
label: 'Title0',
),
BottomNavigationBarItem(
icon: SizedBox(key: icon1, width: 200, height: 10),
label: 'Title1',
),
],
),
);
},
),
),
);
expect(tester.getSize(find.byType(BottomNavigationBar)), const Size(800, kBottomNavigationBarHeight));
expect(tester.getRect(find.byType(BottomNavigationBar)), const Rect.fromLTRB(0, 600 - kBottomNavigationBarHeight, 800, 600));
// The items are laid out as in the default case, within width = 600
// (the "portrait" width) and the result is centered with the
// landscape width = 800.
// So item 0's left edges are:
// ((800 - 600) / 2) + ((600 - 400) / 4) = 150.
// Item 1's right edge is:
// 800 - 150 = 650
// The layout of the unselected item's label is slightly different; not
// checking that here.
expect(tester.getRect(find.text('Title0')), const Rect.fromLTRB(208.0, 570.0, 292.0, 584.0));
expect(tester.getRect(find.byKey(icon0)), const Rect.fromLTRB(150.0, 560.0, 350.0, 570.0));
expect(tester.getRect(find.byKey(icon1)), const Rect.fromLTRB(450.0, 560.0, 650.0, 570.0));
});
testWidgets('Material3 - BottomNavigationBar centered landscape layout', (WidgetTester tester) async {
final Key icon0 = UniqueKey();
final Key icon1 = UniqueKey();
const double iconWidth = 200;
const double iconHeight = 10;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
landscapeLayout: BottomNavigationBarLandscapeLayout.centered,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: SizedBox(key: icon0, width: iconWidth, height: iconHeight),
label: 'Title0',
),
BottomNavigationBarItem(
icon: SizedBox(key: icon1, width: iconWidth, height: iconHeight),
label: 'Title1',
),
],
),
);
},
),
),
);
expect(tester.getSize(find.byType(BottomNavigationBar)), const Size(800, kBottomNavigationBarHeight));
expect(tester.getRect(find.byType(BottomNavigationBar)), const Rect.fromLTRB(0, 600 - kBottomNavigationBarHeight, 800, 600));
const double navigationBarTop = 600 - kBottomNavigationBarHeight; // 544
const double selectedFontSize = 14.0;
const double m3LineHeight = 1.43;
final double labelHeight = (selectedFontSize * m3LineHeight).floorToDouble(); // 20
const double navigationTileVerticalPadding = selectedFontSize / 2; // 7.0
final double navigationTileHeight = iconHeight + labelHeight + 2 * navigationTileVerticalPadding;
// Navigation tiles parent is a Row with crossAxisAlignment sets to center.
final double navigationTileVerticalOffset = (kBottomNavigationBarHeight - navigationTileHeight) / 2;
final double iconTop = navigationBarTop + navigationTileVerticalOffset + navigationTileVerticalPadding;
final double labelBottom = 600 - (navigationTileVerticalOffset + navigationTileVerticalPadding);
// The items are laid out as in the default case, within width = 600
// (the "portrait" width) and the result is centered with the
// landscape width = 800.
// So item 0's left edges are:
// ((800 - 600) / 2) + ((600 - 400) / 4) = 150.
// Item 1's right edge is:
// 800 - 150 = 650
// The layout of the unselected item's label is slightly different; not
// checking that here.
final double firstLabelWidth = tester.getSize(find.text('Title0')).width;
const double itemWidth = iconWidth; // 200
const double firstItemLeft = 150;
const double firstLabelCenter = firstItemLeft + itemWidth / 2; // 250
expect(tester.getRect(
find.text('Title0')),
Rect.fromLTRB(
firstLabelCenter - firstLabelWidth / 2,
labelBottom - labelHeight,
firstLabelCenter + firstLabelWidth / 2,
labelBottom,
),
);
expect(tester.getRect(find.byKey(icon0)), Rect.fromLTRB(150.0, iconTop, 350.0, iconTop + iconHeight));
expect(tester.getRect(find.byKey(icon1)), Rect.fromLTRB(450.0, iconTop, 650.0, iconTop + iconHeight));
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('Material2 - BottomNavigationBar linear landscape layout', (WidgetTester tester) async {
final Key icon0 = UniqueKey();
final Key icon1 = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
landscapeLayout: BottomNavigationBarLandscapeLayout.linear,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: SizedBox(key: icon0, width: 100, height: 20),
label: 'Title0',
),
BottomNavigationBarItem(
icon: SizedBox(key: icon1, width: 100, height: 20),
label: 'Title1',
),
],
),
);
},
),
),
);
expect(tester.getSize(find.byType(BottomNavigationBar)), const Size(800, kBottomNavigationBarHeight));
expect(tester.getRect(find.byType(BottomNavigationBar)), const Rect.fromLTRB(0, 600 - kBottomNavigationBarHeight, 800, 600));
// The items are laid out as in the default case except each
// item's icon/label is arranged in a row, with 8 pixels in
// between the icon and label. The layout of the unselected
// item's label is slightly different; not checking that here.
expect(tester.getRect(find.text('Title0')), const Rect.fromLTRB(212.0, 565.0, 296.0, 579.0));
expect(tester.getRect(find.byKey(icon0)), const Rect.fromLTRB(104.0, 562.0, 204.0, 582.0));
expect(tester.getRect(find.byKey(icon1)), const Rect.fromLTRB(504.0, 562.0, 604.0, 582.0));
});
testWidgets('Material3 - BottomNavigationBar linear landscape layout', (WidgetTester tester) async {
final Key icon0 = UniqueKey();
final Key icon1 = UniqueKey();
const double iconWidth = 100;
const double iconHeight = 20;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(),
home: Builder(
builder: (BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
landscapeLayout: BottomNavigationBarLandscapeLayout.linear,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: SizedBox(key: icon0, width: iconWidth, height: iconHeight),
label: 'Title0',
),
BottomNavigationBarItem(
icon: SizedBox(key: icon1, width: iconWidth, height: iconHeight),
label: 'Title1',
),
],
),
);
},
),
),
);
expect(tester.getSize(find.byType(BottomNavigationBar)), const Size(800, kBottomNavigationBarHeight));
expect(tester.getRect(find.byType(BottomNavigationBar)), const Rect.fromLTRB(0, 600 - kBottomNavigationBarHeight, 800, 600));
const double navigationBarTop = 600 - kBottomNavigationBarHeight; // 544
const double selectedFontSize = 14.0;
const double m3LineHeight = 1.43;
final double labelHeight = (selectedFontSize * m3LineHeight).floorToDouble(); // 20
const double navigationTileVerticalPadding = selectedFontSize / 2; // 7.0
// Icon and label are in the same row.
final double navigationTileHeight = max(iconHeight, labelHeight) + 2 * navigationTileVerticalPadding;
// Navigation tiles parent is a Row with crossAxisAlignment sets to center.
final double navigationTileVerticalOffset = (kBottomNavigationBarHeight - navigationTileHeight) / 2;
final double iconTop = navigationBarTop + navigationTileVerticalOffset + navigationTileVerticalPadding;
final double labelBottom = 600 - (navigationTileVerticalOffset + navigationTileVerticalPadding);
// The items are laid out as in the default case except each
// item's icon/label is arranged in a row, with 8 pixels in
// between the icon and label. The layout of the unselected
// item's label is slightly different; not checking that here.
const double itemFullWith = 800 / 2; // Two items in the navigation bar.
const double separatorWidth = 8;
final double firstLabelWidth = tester.getSize(find.text('Title0')).width;
final double firstItemContentWidth = iconWidth + separatorWidth + firstLabelWidth;
final double firstItemLeft = itemFullWith / 2 - firstItemContentWidth / 2;
final double secondLabelWidth = tester.getSize(find.text('Title1')).width;
final double secondItemContentWidth = iconWidth + separatorWidth + secondLabelWidth;
final double secondItemLeft = itemFullWith + itemFullWith / 2 - secondItemContentWidth / 2;
expect(tester.getRect(
find.text('Title0')),
Rect.fromLTRB(
firstItemLeft + iconWidth + separatorWidth,
labelBottom - labelHeight,
firstItemLeft + iconWidth + separatorWidth + firstLabelWidth,
labelBottom,
),
);
expect(tester.getRect(find.byKey(icon0)), Rect.fromLTRB(firstItemLeft, iconTop, firstItemLeft + iconWidth, iconTop + iconHeight));
expect(tester.getRect(find.byKey(icon1)), Rect.fromLTRB(secondItemLeft, iconTop, secondItemLeft + iconWidth, iconTop + iconHeight));
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('BottomNavigationBar linear landscape layout label RenderFlex overflow',(WidgetTester tester) async {
//Regression test for https://github.com/flutter/flutter/issues/112163
tester.view.physicalSize = const Size(540, 340);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
landscapeLayout: BottomNavigationBarLandscapeLayout.linear,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home_rounded),
label: 'Home Challenges',
backgroundColor: Colors.grey,
tooltip: '',
),
BottomNavigationBarItem(
icon: Icon(Icons.date_range_rounded),
label: 'Daily Challenges',
backgroundColor: Colors.grey,
tooltip: '',
),
BottomNavigationBarItem(
icon: Icon(Icons.wind_power),
label: 'Awards Challenges',
backgroundColor: Colors.grey,
tooltip: '',
),
BottomNavigationBarItem(
icon: Icon(Icons.bar_chart_rounded),
label: 'Statistics Challenges',
backgroundColor: Colors.grey,
tooltip: '',
),
],
));
},
),
),
);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('bottom_navigation_bar.label_overflow.png'),
);
addTearDown(tester.view.resetPhysicalSize);
});
testWidgets('BottomNavigationBar keys passed through', (WidgetTester tester) async {
const Key key1 = Key('key1');
const Key key2 = Key('key2');
await tester.pumpWidget(
boilerplate(
textDirection: TextDirection.ltr,
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
key: key1,
icon: Icon(Icons.favorite_border),
label: 'Favorite',
),
BottomNavigationBarItem(
key: key2,
icon: Icon(Icons.access_alarm),
label: 'Alarm',
),
],
),
),
);
expect(find.byKey(key1), findsOneWidget);
expect(find.byKey(key2), findsOneWidget);
});
}
Widget boilerplate({ Widget? bottomNavigationBar, required TextDirection textDirection, bool? useMaterial3 }) {
return MaterialApp(
theme: ThemeData(useMaterial3: useMaterial3),
home: Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: Directionality(
textDirection: textDirection,
child: MediaQuery(
data: const MediaQueryData(),
child: Material(
child: Scaffold(
bottomNavigationBar: bottomNavigationBar,
),
),
),
),
),
);
}
double _getOpacity(WidgetTester tester, String textValue) {
final FadeTransition opacityWidget = tester.widget<FadeTransition>(
find.ancestor(
of: find.text(textValue),
matching: find.byType(FadeTransition),
).first,
);
return opacityWidget.opacity.value;
}
Material _getMaterial(WidgetTester tester) {
return tester.firstWidget<Material>(
find.descendant(of: find.byType(BottomNavigationBar), matching: find.byType(Material)),
);
}
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!;
}
EdgeInsets _itemPadding(WidgetTester tester, IconData icon) {
return tester.widget<Padding>(
find.descendant(
of: find.ancestor(of: find.byIcon(icon), matching: find.byType(InkResponse)),
matching: find.byType(Padding),
).first,
).padding.resolve(TextDirection.ltr);
}
| flutter/packages/flutter/test/material/bottom_navigation_bar_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/bottom_navigation_bar_test.dart",
"repo_id": "flutter",
"token_count": 54324
} | 669 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
RenderBox getMaterialBox(WidgetTester tester, Finder type) {
return tester.firstRenderObject<RenderBox>(
find.descendant(
of: type,
matching: find.byType(CustomPaint),
),
);
}
Material getMaterial(WidgetTester tester) {
return tester.widget<Material>(
find.descendant(
of: find.byType(ChoiceChip),
matching: find.byType(Material),
),
);
}
IconThemeData getIconData(WidgetTester tester) {
final IconTheme iconTheme = tester.firstWidget(
find.descendant(
of: find.byType(RawChip),
matching: find.byType(IconTheme),
),
);
return iconTheme.data;
}
DefaultTextStyle getLabelStyle(WidgetTester tester, String labelText) {
return tester.widget(
find.ancestor(
of: find.text(labelText),
matching: find.byType(DefaultTextStyle),
).first,
);
}
/// Adds the basic requirements for a Chip.
Widget wrapForChip({
required Widget child,
TextDirection textDirection = TextDirection.ltr,
TextScaler textScaler = TextScaler.noScaling,
Brightness brightness = Brightness.light,
bool? useMaterial3,
}) {
return MaterialApp(
theme: ThemeData(brightness: brightness, useMaterial3: useMaterial3),
home: Directionality(
textDirection: textDirection,
child: MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: Material(child: child),
),
),
);
}
void checkChipMaterialClipBehavior(WidgetTester tester, Clip clipBehavior) {
final Iterable<Material> materials = tester.widgetList<Material>(find.byType(Material));
// There should be two Material widgets, first Material is from the "_wrapForChip" and
// last Material is from the "RawChip".
expect(materials.length, 2);
// The last Material from `RawChip` should have the clip behavior.
expect(materials.last.clipBehavior, clipBehavior);
}
void main() {
testWidgets('Material2 - ChoiceChip defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
const String label = 'choice chip';
// Test enabled ChoiceChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: ChoiceChip(
selected: false,
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
),
);
// Test default chip size.
expect(tester.getSize(find.byType(ChoiceChip)), const Size(178.0, 48.0));
// Test default label style.
expect(
getLabelStyle(tester, label).style.color,
theme.textTheme.bodyLarge!.color!.withAlpha(0xde),
);
Material chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.black);
expect(chipMaterial.shape, const StadiumBorder());
ShapeDecoration decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, Colors.black.withAlpha(0x1f));
// Test disabled ChoiceChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: ChoiceChip(
selected: false,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.black);
expect(chipMaterial.shape, const StadiumBorder());
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, Colors.black38);
// Test selected enabled ChoiceChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: ChoiceChip(
selected: true,
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.black);
expect(chipMaterial.shape, const StadiumBorder());
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, Colors.black.withAlpha(0x3d));
// Test selected disabled ChoiceChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: ChoiceChip(
selected: true,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.black);
expect(chipMaterial.shape, const StadiumBorder());
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, Colors.black.withAlpha(0x3d));
});
testWidgets('Material3 - ChoiceChip defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
const String label = 'choice chip';
// Test enabled ChoiceChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: ChoiceChip(
selected: false,
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
),
);
// Test default chip size.
expect(
tester.getSize(find.byType(ChoiceChip)),
within(distance: 0.01, from: const Size(189.1, 48.0)),
);
// Test default label style.
expect(
getLabelStyle(tester, label).style.color!.value,
theme.colorScheme.onSurfaceVariant.value,
);
Material chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.transparent);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: theme.colorScheme.outline),
),
);
ShapeDecoration decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, null);
// Test disabled ChoiceChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: ChoiceChip(
selected: false,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.transparent);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: theme.colorScheme.onSurface.withOpacity(0.12)),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, null);
// Test selected enabled ChoiceChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: ChoiceChip(
selected: true,
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, null);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.secondaryContainer);
// Test selected disabled ChoiceChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: ChoiceChip(
selected: true,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, null);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.onSurface.withOpacity(0.12));
});
testWidgets('Material3 - ChoiceChip.elevated defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
const String label = 'choice chip';
// Test enabled ChoiceChip.elevated defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: ChoiceChip.elevated(
selected: false,
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
),
);
// Test default chip size.
expect(
tester.getSize(find.byType(ChoiceChip)),
within(distance: 0.01, from: const Size(189.1, 48.0)),
);
// Test default label style.
expect(
getLabelStyle(tester, label).style.color!.value,
theme.colorScheme.onSurfaceVariant.value,
);
Material chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 1);
expect(chipMaterial.shadowColor, theme.colorScheme.shadow);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
ShapeDecoration decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.surfaceContainerLow);
// Test disabled ChoiceChip.elevated defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: ChoiceChip.elevated(
selected: false,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, theme.colorScheme.shadow);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.onSurface.withOpacity(0.12));
// Test selected enabled ChoiceChip.elevated defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: ChoiceChip.elevated(
selected: true,
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 1);
expect(chipMaterial.shadowColor, null);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.secondaryContainer);
// Test selected disabled ChoiceChip.elevated defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: ChoiceChip.elevated(
selected: false,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, theme.colorScheme.shadow);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.onSurface.withOpacity(0.12));
});
testWidgets('ChoiceChip.color resolves material states', (WidgetTester tester) async {
const Color disabledSelectedColor = Color(0xffffff00);
const Color disabledColor = Color(0xff00ff00);
const Color backgroundColor = Color(0xff0000ff);
const Color selectedColor = Color(0xffff0000);
final MaterialStateProperty<Color?> color = MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled) && states.contains(MaterialState.selected)) {
return disabledSelectedColor;
}
if (states.contains(MaterialState.disabled)) {
return disabledColor;
}
if (states.contains(MaterialState.selected)) {
return selectedColor;
}
return backgroundColor;
});
Widget buildApp({ required bool enabled, required bool selected }) {
return wrapForChip(
useMaterial3: true,
child: Column(
children: <Widget>[
ChoiceChip(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
color: color,
label: const Text('ChoiceChip'),
),
ChoiceChip.elevated(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
color: color,
label: const Text('ChoiceChip.elevated'),
),
],
),
);
}
// Test enabled state.
await tester.pumpWidget(buildApp(enabled: true, selected: false));
// Enabled ChoiceChip should have the provided backgroundColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: backgroundColor),
);
// Enabled elevated ChoiceChip should have the provided backgroundColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: backgroundColor),
);
// Test disabled state.
await tester.pumpWidget(buildApp(enabled: false, selected: false));
await tester.pumpAndSettle();
// Disabled ChoiceChip should have the provided disabledColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: disabledColor),
);
// Disabled elevated ChoiceChip should have the provided disabledColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: disabledColor),
);
// Test enabled & selected state.
await tester.pumpWidget(buildApp(enabled: true, selected: true));
await tester.pumpAndSettle();
// Enabled & selected ChoiceChip should have the provided selectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: selectedColor),
);
// Enabled & selected elevated ChoiceChip should have the provided selectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: selectedColor),
);
// Test disabled & selected state.
await tester.pumpWidget(buildApp(enabled: false, selected: true));
await tester.pumpAndSettle();
// Disabled & selected ChoiceChip should have the provided disabledSelectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: disabledSelectedColor),
);
// Disabled & selected elevated ChoiceChip should have the provided disabledSelectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: disabledSelectedColor),
);
});
testWidgets('ChoiceChip uses provided state color properties', (WidgetTester tester) async {
const Color disabledColor = Color(0xff00ff00);
const Color backgroundColor = Color(0xff0000ff);
const Color selectedColor = Color(0xffff0000);
Widget buildApp({ required bool enabled, required bool selected }) {
return wrapForChip(
useMaterial3: true,
child: Column(
children: <Widget>[
ChoiceChip(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
disabledColor: disabledColor,
backgroundColor: backgroundColor,
selectedColor: selectedColor,
label: const Text('ChoiceChip'),
),
ChoiceChip.elevated(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
disabledColor: disabledColor,
backgroundColor: backgroundColor,
selectedColor: selectedColor,
label: const Text('ChoiceChip.elevated'),
),
],
),
);
}
// Test enabled chips.
await tester.pumpWidget(buildApp(enabled: true, selected: false));
// Enabled ChoiceChip should have the provided backgroundColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: backgroundColor),
);
// Enabled elevated ChoiceChip should have the provided backgroundColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: backgroundColor),
);
// Test disabled chips.
await tester.pumpWidget(buildApp(enabled: false, selected: false));
await tester.pumpAndSettle();
// Disabled ChoiceChip should have the provided disabledColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: disabledColor),
);
// Disabled elevated ChoiceChip should have the provided disabledColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: disabledColor),
);
// Test enabled & selected chips.
await tester.pumpWidget(buildApp(enabled: true, selected: true));
await tester.pumpAndSettle();
// Enabled & selected ChoiceChip should have the provided selectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: selectedColor),
);
// Enabled & selected elevated ChoiceChip should have the provided selectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: selectedColor),
);
});
testWidgets('ChoiceChip can be tapped', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: ChoiceChip(
selected: false,
label: Text('choice chip'),
),
),
),
);
await tester.tap(find.byType(ChoiceChip));
expect(tester.takeException(), null);
});
testWidgets('ChoiceChip clipBehavior properly passes through to the Material', (WidgetTester tester) async {
const Text label = Text('label');
await tester.pumpWidget(wrapForChip(child: const ChoiceChip(label: label, selected: false)));
checkChipMaterialClipBehavior(tester, Clip.none);
await tester.pumpWidget(wrapForChip(child: const ChoiceChip(label: label, selected: false, clipBehavior: Clip.antiAlias)));
checkChipMaterialClipBehavior(tester, Clip.antiAlias);
});
testWidgets('ChoiceChip passes iconTheme property to RawChip', (WidgetTester tester) async {
const IconThemeData iconTheme = IconThemeData(color: Colors.red);
await tester.pumpWidget(wrapForChip(
child: const ChoiceChip(
label: Text('Test'),
selected: true,
iconTheme: iconTheme,
)));
final RawChip rawChip = tester.widget(find.byType(RawChip));
expect(rawChip.iconTheme, iconTheme);
});
testWidgets('ChoiceChip passes showCheckmark from ChipTheme to RawChip', (WidgetTester tester) async {
const bool showCheckmark = false;
await tester.pumpWidget(wrapForChip(
child: const ChipTheme(
data: ChipThemeData(
showCheckmark: showCheckmark,
),
child: ChoiceChip(
label: Text('Test'),
selected: true,
),
),
));
final RawChip rawChip = tester.widget(find.byType(RawChip));
expect(rawChip.showCheckmark, showCheckmark);
});
testWidgets('ChoiceChip passes checkmark properties to RawChip', (WidgetTester tester) async {
const bool showCheckmark = false;
const Color checkmarkColor = Color(0xff0000ff);
await tester.pumpWidget(wrapForChip(
child: const ChoiceChip(
label: Text('Test'),
selected: true,
showCheckmark: showCheckmark,
checkmarkColor: checkmarkColor,
),
));
final RawChip rawChip = tester.widget(find.byType(RawChip));
expect(rawChip.showCheckmark, showCheckmark);
expect(rawChip.checkmarkColor, checkmarkColor);
});
testWidgets('ChoiceChip uses provided iconTheme', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
Widget buildChip({ IconThemeData? iconTheme }) {
return MaterialApp(
theme: theme,
home: Material(
child: ChoiceChip(
iconTheme: iconTheme,
avatar: const Icon(Icons.add),
label: const Text('Test'),
selected: false,
onSelected: (bool _) {},
),
),
);
}
// Test default icon theme.
await tester.pumpWidget(buildChip());
expect(getIconData(tester).color, theme.colorScheme.primary);
// Test provided icon theme.
await tester.pumpWidget(buildChip(iconTheme: const IconThemeData(color: Color(0xff00ff00))));
expect(getIconData(tester).color, const Color(0xff00ff00));
});
testWidgets('ChoiceChip avatar layout constraints can be customized', (WidgetTester tester) async {
const double border = 1.0;
const double iconSize = 18.0;
const double labelPadding = 8.0;
const double padding = 8.0;
const Size labelSize = Size(100, 100);
Widget buildChip({BoxConstraints? avatarBoxConstraints}) {
return wrapForChip(
child: Center(
child: ChoiceChip(
avatarBoxConstraints: avatarBoxConstraints,
avatar: const Icon(Icons.favorite),
label: Container(
width: labelSize.width,
height: labelSize.width,
color: const Color(0xFFFF0000),
),
selected: false,
),
),
);
}
// Test default avatar layout constraints.
await tester.pumpWidget(buildChip());
expect(tester.getSize(find.byType(ChoiceChip)).width, equals(234.0));
expect(tester.getSize(find.byType(ChoiceChip)).height, equals(118.0));
// Calculate the distance between avatar and chip edges.
Offset chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester)));
final Offset avatarCenter = tester.getCenter(find.byIcon(Icons.favorite));
expect(chipTopLeft.dx, avatarCenter.dx - (labelSize.width / 2) - padding - border);
expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distance between avatar and label.
Offset labelTopLeft = tester.getTopLeft(find.byType(Container));
expect(labelTopLeft.dx, avatarCenter.dx + (labelSize.width / 2) + labelPadding);
// Test custom avatar layout constraints.
await tester.pumpWidget(buildChip(avatarBoxConstraints: const BoxConstraints.tightForFinite()));
await tester.pump();
expect(tester.getSize(find.byType(ChoiceChip)).width, equals(152.0));
expect(tester.getSize(find.byType(ChoiceChip)).height, equals(118.0));
// Calculate the distance between avatar and chip edges.
chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester)));
expect(chipTopLeft.dx, avatarCenter.dx - (iconSize / 2) - padding - border);
expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distance between avatar and label.
labelTopLeft = tester.getTopLeft(find.byType(Container));
expect(labelTopLeft.dx, avatarCenter.dx + (iconSize / 2) + labelPadding);
});
}
| flutter/packages/flutter/test/material/choice_chip_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/choice_chip_test.dart",
"repo_id": "flutter",
"token_count": 9932
} | 670 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('DividerThemeData copyWith, ==, hashCode basics', () {
expect(const DividerThemeData(), const DividerThemeData().copyWith());
expect(const DividerThemeData().hashCode, const DividerThemeData().copyWith().hashCode);
});
test('DividerThemeData null fields by default', () {
const DividerThemeData dividerTheme = DividerThemeData();
expect(dividerTheme.color, null);
expect(dividerTheme.space, null);
expect(dividerTheme.thickness, null);
expect(dividerTheme.indent, null);
expect(dividerTheme.endIndent, null);
});
testWidgets('Default DividerThemeData debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const DividerThemeData().debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[]);
});
testWidgets('DividerThemeData implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const DividerThemeData(
color: Color(0xFFFFFFFF),
space: 5.0,
thickness: 4.0,
indent: 3.0,
endIndent: 2.0,
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'color: Color(0xffffffff)',
'space: 5.0',
'thickness: 4.0',
'indent: 3.0',
'endIndent: 2.0',
]);
});
group('Material3 - Horizontal Divider', () {
testWidgets('Passing no DividerThemeData returns defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(MaterialApp(
theme: theme,
home: const Scaffold(
body: Divider(),
),
));
final RenderBox box = tester.firstRenderObject(find.byType(Divider));
expect(box.size.height, 16.0);
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
expect(decoration.border!.bottom.width, 1.0);
expect(decoration.border!.bottom.color, theme.colorScheme.outlineVariant);
final Rect dividerRect = tester.getRect(find.byType(Divider));
final Rect lineRect = tester.getRect(find.byType(DecoratedBox));
expect(lineRect.left, dividerRect.left);
expect(lineRect.right, dividerRect.right);
});
testWidgets('Uses values from DividerThemeData', (WidgetTester tester) async {
final DividerThemeData dividerTheme = _dividerTheme();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true, dividerTheme: dividerTheme),
home: const Scaffold(
body: Divider(),
),
));
final RenderBox box = tester.firstRenderObject(find.byType(Divider));
expect(box.size.height, dividerTheme.space);
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
expect(decoration.border!.bottom.width, dividerTheme.thickness);
expect(decoration.border!.bottom.color, dividerTheme.color);
final Rect dividerRect = tester.getRect(find.byType(Divider));
final Rect lineRect = tester.getRect(find.byType(DecoratedBox));
expect(lineRect.left, dividerRect.left + dividerTheme.indent!);
expect(lineRect.right, dividerRect.right - dividerTheme.endIndent!);
});
testWidgets('DividerTheme overrides defaults', (WidgetTester tester) async {
final DividerThemeData dividerTheme = _dividerTheme();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: DividerTheme(
data: dividerTheme,
child: const Divider(),
),
),
));
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
expect(decoration.border!.bottom.width, dividerTheme.thickness);
expect(decoration.border!.bottom.color, dividerTheme.color);
});
testWidgets('Widget properties take priority over theme', (WidgetTester tester) async {
const Color color = Colors.purple;
const double height = 10.0;
const double thickness = 5.0;
const double indent = 8.0;
const double endIndent = 9.0;
final DividerThemeData dividerTheme = _dividerTheme();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(dividerTheme: dividerTheme),
home: const Scaffold(
body: Divider(
color: color,
height: height,
thickness: thickness,
indent: indent,
endIndent: endIndent,
),
),
));
final RenderBox box = tester.firstRenderObject(find.byType(Divider));
expect(box.size.height, height);
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
expect(decoration.border!.bottom.width, thickness);
expect(decoration.border!.bottom.color, color);
final Rect dividerRect = tester.getRect(find.byType(Divider));
final Rect lineRect = tester.getRect(find.byType(DecoratedBox));
expect(lineRect.left, dividerRect.left + indent);
expect(lineRect.right, dividerRect.right - endIndent);
});
});
group('Material3 - Vertical Divider', () {
testWidgets('Passing no DividerThemeData returns defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(MaterialApp(
theme: theme,
home: const Scaffold(
body: VerticalDivider(),
),
));
final RenderBox box = tester.firstRenderObject(find.byType(VerticalDivider));
expect(box.size.width, 16.0);
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
final Border border = decoration.border! as Border;
expect(border.left.width, 1.0);
expect(border.left.color, theme.colorScheme.outlineVariant);
final Rect dividerRect = tester.getRect(find.byType(VerticalDivider));
final Rect lineRect = tester.getRect(find.byType(DecoratedBox));
expect(lineRect.top, dividerRect.top);
expect(lineRect.bottom, dividerRect.bottom);
});
testWidgets('Uses values from DividerThemeData', (WidgetTester tester) async {
final DividerThemeData dividerTheme = _dividerTheme();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(dividerTheme: dividerTheme),
home: const Scaffold(
body: VerticalDivider(),
),
));
final RenderBox box = tester.firstRenderObject(find.byType(VerticalDivider));
expect(box.size.width, dividerTheme.space);
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
final Border border = decoration.border! as Border;
expect(border.left.width, dividerTheme.thickness);
expect(border.left.color, dividerTheme.color);
final Rect dividerRect = tester.getRect(find.byType(VerticalDivider));
final Rect lineRect = tester.getRect(find.byType(DecoratedBox));
expect(lineRect.top, dividerRect.top + dividerTheme.indent!);
expect(lineRect.bottom, dividerRect.bottom - dividerTheme.endIndent!);
});
testWidgets('DividerTheme overrides defaults', (WidgetTester tester) async {
final DividerThemeData dividerTheme = _dividerTheme();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: DividerTheme(
data: dividerTheme,
child: const VerticalDivider(),
),
),
));
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
final Border border = decoration.border! as Border;
expect(border.left.width, dividerTheme.thickness);
expect(border.left.color, dividerTheme.color);
});
testWidgets('Widget properties take priority over theme', (WidgetTester tester) async {
const Color color = Colors.purple;
const double width = 10.0;
const double thickness = 5.0;
const double indent = 8.0;
const double endIndent = 9.0;
final DividerThemeData dividerTheme = _dividerTheme();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(dividerTheme: dividerTheme),
home: const Scaffold(
body: VerticalDivider(
color: color,
width: width,
thickness: thickness,
indent: indent,
endIndent: endIndent,
),
),
));
final RenderBox box = tester.firstRenderObject(find.byType(VerticalDivider));
expect(box.size.width, width);
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
final Border border = decoration.border! as Border;
expect(border.left.width, thickness);
expect(border.left.color, color);
final Rect dividerRect = tester.getRect(find.byType(VerticalDivider));
final Rect lineRect = tester.getRect(find.byType(DecoratedBox));
expect(lineRect.top, dividerRect.top + indent);
expect(lineRect.bottom, dividerRect.bottom - endIndent);
});
});
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.
group('Material2 - Horizontal Divider', () {
testWidgets('Passing no DividerThemeData returns defaults', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: const Scaffold(
body: Divider(),
),
));
final RenderBox box = tester.firstRenderObject(find.byType(Divider));
expect(box.size.height, 16.0);
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
expect(decoration.border!.bottom.width, 0.0);
final ThemeData theme = ThemeData(useMaterial3: false);
expect(decoration.border!.bottom.color, theme.dividerColor);
final Rect dividerRect = tester.getRect(find.byType(Divider));
final Rect lineRect = tester.getRect(find.byType(DecoratedBox));
expect(lineRect.left, dividerRect.left);
expect(lineRect.right, dividerRect.right);
});
testWidgets('DividerTheme overrides defaults', (WidgetTester tester) async {
final DividerThemeData theme = _dividerTheme();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: DividerTheme(
data: theme,
child: const Divider(),
),
),
));
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
expect(decoration.border!.bottom.width, theme.thickness);
expect(decoration.border!.bottom.color, theme.color);
});
});
group('Material2 - Vertical Divider', () {
testWidgets('Passing no DividerThemeData returns defaults', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: const Scaffold(
body: VerticalDivider(),
),
));
final RenderBox box = tester.firstRenderObject(find.byType(VerticalDivider));
expect(box.size.width, 16.0);
final Container container = tester.widget(find.byType(Container));
final BoxDecoration decoration = container.decoration! as BoxDecoration;
final Border border = decoration.border! as Border;
expect(border.left.width, 0.0);
final ThemeData theme = ThemeData(useMaterial3: false);
expect(border.left.color, theme.dividerColor);
final Rect dividerRect = tester.getRect(find.byType(VerticalDivider));
final Rect lineRect = tester.getRect(find.byType(DecoratedBox));
expect(lineRect.top, dividerRect.top);
expect(lineRect.bottom, dividerRect.bottom);
});
});
});
}
DividerThemeData _dividerTheme() {
return const DividerThemeData(
color: Colors.orange,
space: 12.0,
thickness: 2.0,
indent: 7.0,
endIndent: 5.0,
);
}
| flutter/packages/flutter/test/material/divider_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/divider_theme_test.dart",
"repo_id": "flutter",
"token_count": 5148
} | 671 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
/// Tracks how often feedback has been requested since its instantiation.
///
/// It replaces the MockMethodCallHandler of [SystemChannels.platform] and
/// cannot be used in combination with other classes that do the same.
class FeedbackTester {
FeedbackTester() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, _handler);
}
/// Number of times haptic feedback was requested (vibration).
int get hapticCount => _hapticCount;
int _hapticCount = 0;
/// Number of times the click sound was requested to play.
int get clickSoundCount => _clickSoundCount;
int _clickSoundCount = 0;
Future<void> _handler(MethodCall methodCall) async {
if (methodCall.method == 'HapticFeedback.vibrate') {
_hapticCount++;
}
if (methodCall.method == 'SystemSound.play' &&
methodCall.arguments == SystemSoundType.click.toString()) {
_clickSoundCount++;
}
}
/// Stops tracking.
void dispose() {
assert(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(SystemChannels.platform.name, _handler));
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
}
}
| flutter/packages/flutter/test/material/feedback_tester.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/feedback_tester.dart",
"repo_id": "flutter",
"token_count": 461
} | 672 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('The Ink widget expands when no dimensions are set', (WidgetTester tester) async {
await tester.pumpWidget(
Material(
child: Ink(),
),
);
expect(find.byType(Ink), findsOneWidget);
expect(tester.getSize(find.byType(Ink)), const Size(800.0, 600.0));
});
testWidgets('The Ink widget fits the specified size', (WidgetTester tester) async {
const double height = 150.0;
const double width = 200.0;
await tester.pumpWidget(
Material(
child: Center( // used to constrain to child's size
child: Ink(
height: height,
width: width,
),
),
),
);
await tester.pumpAndSettle();
expect(find.byType(Ink), findsOneWidget);
expect(tester.getSize(find.byType(Ink)), const Size(width, height));
});
testWidgets('The Ink widget expands on a unspecified dimension', (WidgetTester tester) async {
const double height = 150.0;
await tester.pumpWidget(
Material(
child: Center( // used to constrain to child's size
child: Ink(
height: height,
),
),
),
);
await tester.pumpAndSettle();
expect(find.byType(Ink), findsOneWidget);
expect(tester.getSize(find.byType(Ink)), const Size(800, height));
});
testWidgets('Material2 - InkWell widget renders an ink splash', (WidgetTester tester) async {
const Color splashColor = Color(0xAA0000FF);
const BorderRadius borderRadius = BorderRadius.all(Radius.circular(6.0));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: SizedBox(
width: 200.0,
height: 60.0,
child: InkWell(
borderRadius: borderRadius,
splashColor: splashColor,
onTap: () { },
),
),
),
),
),
);
final Offset center = tester.getCenter(find.byType(InkWell));
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
final RenderBox box = Material.of(tester.element(find.byType(InkWell))) as RenderBox;
expect(
box,
paints
..translate(x: 0.0, y: 0.0)
..save()
..translate(x: 300.0, y: 270.0)
..clipRRect(rrect: RRect.fromLTRBR(0.0, 0.0, 200.0, 60.0, const Radius.circular(6.0)))
..circle(x: 100.0, y: 30.0, radius: 21.0, color: splashColor)
..restore()
);
await gesture.up();
});
testWidgets('Material3 - InkWell widget renders an ink splash', (WidgetTester tester) async {
const Key inkWellKey = Key('InkWell');
const Color splashColor = Color(0xAA0000FF);
const BorderRadius borderRadius = BorderRadius.all(Radius.circular(6.0));
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: SizedBox(
width: 200.0,
height: 60.0,
child: InkWell(
key: inkWellKey,
borderRadius: borderRadius,
splashColor: splashColor,
onTap: () { },
),
),
),
),
),
);
final Offset center = tester.getCenter(find.byType(InkWell));
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
final RenderBox box = Material.of(tester.element(find.byType(InkWell))) as RenderBox;
if (kIsWeb && isCanvasKit) {
expect(
box,
paints
..save()
..translate(x: 0.0, y: 0.0)
..clipRect()
..save()
..translate(x: 300.0, y: 270.0)
..clipRRect(rrect: RRect.fromLTRBR(0.0, 0.0, 200.0, 60.0, const Radius.circular(6.0)))
..circle()
..restore()
);
} else {
expect(
box,
paints
..translate(x: 0.0, y: 0.0)
..save()
..translate(x: 300.0, y: 270.0)
..clipRRect(rrect: RRect.fromLTRBR(0.0, 0.0, 200.0, 60.0, const Radius.circular(6.0)))
..rect(rect: const Rect.fromLTRB(0.0, 0.0, 200, 60))
..restore()
);
}
// Material 3 uses the InkSparkle which uses a shader, so we can't capture
// the effect with paint methods. Use a golden test instead.
await expectLater(
find.byKey(inkWellKey),
matchesGoldenFile('m3_ink_well.renders.ink_splash.png'),
);
await gesture.up();
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('The InkWell widget renders an ink ripple', (WidgetTester tester) async {
const Color highlightColor = Color(0xAAFF0000);
const Color splashColor = Color(0xB40000FF);
const BorderRadius borderRadius = BorderRadius.all(Radius.circular(6.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: SizedBox(
width: 100.0,
height: 100.0,
child: InkWell(
borderRadius: borderRadius,
highlightColor: highlightColor,
splashColor: splashColor,
onTap: () { },
radius: 100.0,
splashFactory: InkRipple.splashFactory,
),
),
),
),
),
);
final Offset tapDownOffset = tester.getTopLeft(find.byType(InkWell));
final Offset inkWellCenter = tester.getCenter(find.byType(InkWell));
//final TestGesture gesture = await tester.startGesture(tapDownOffset);
await tester.tapAt(tapDownOffset);
await tester.pump(); // start gesture
final RenderBox box = Material.of(tester.element(find.byType(InkWell)))as RenderBox;
bool offsetsAreClose(Offset a, Offset b) => (a - b).distance < 1.0;
bool radiiAreClose(double a, double b) => (a - b).abs() < 1.0;
PaintPattern ripplePattern(Offset expectedCenter, double expectedRadius, int expectedAlpha) {
return paints
..translate(x: 0.0, y: 0.0)
..translate(x: tapDownOffset.dx, y: tapDownOffset.dy)
..something((Symbol method, List<dynamic> arguments) {
if (method != #drawCircle) {
return false;
}
final Offset center = arguments[0] as Offset;
final double radius = arguments[1] as double;
final Paint paint = arguments[2] as Paint;
if (offsetsAreClose(center, expectedCenter) && radiiAreClose(radius, expectedRadius) && paint.color.alpha == expectedAlpha) {
return true;
}
throw '''
Expected: center == $expectedCenter, radius == $expectedRadius, alpha == $expectedAlpha
Found: center == $center radius == $radius alpha == ${paint.color.alpha}''';
}
);
}
// Initially the ripple's center is where the tap occurred;
// ripplePattern always add a translation of tapDownOffset.
expect(box, ripplePattern(Offset.zero, 30.0, 0));
// The ripple fades in for 75ms. During that time its alpha is eased from
// 0 to the splashColor's alpha value and its center moves towards the
// center of the ink well.
await tester.pump(const Duration(milliseconds: 50));
expect(box, ripplePattern(const Offset(17.0, 17.0), 56.0, 120));
// At 75ms the ripple has fade in: it's alpha matches the splashColor's
// alpha and its center has moved closer to the ink well's center.
await tester.pump(const Duration(milliseconds: 25));
expect(box, ripplePattern(const Offset(29.0, 29.0), 73.0, 180));
// At this point the splash radius has expanded to its limit: 5 past the
// ink well's radius parameter. The splash center has moved to its final
// location at the inkwell's center and the fade-out is about to start.
// The fade-out begins at 225ms = 50ms + 25ms + 150ms.
await tester.pump(const Duration(milliseconds: 150));
expect(box, ripplePattern(inkWellCenter - tapDownOffset, 105.0, 180));
// After another 150ms the fade-out is complete.
await tester.pump(const Duration(milliseconds: 150));
expect(box, ripplePattern(inkWellCenter - tapDownOffset, 105.0, 0));
});
testWidgets('Material2 - Does the Ink widget render anything', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: Ink(
color: Colors.blue,
width: 200.0,
height: 200.0,
child: InkWell(
splashColor: Colors.green,
onTap: () { },
),
),
),
),
),
);
final Offset center = tester.getCenter(find.byType(InkWell));
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
final RenderBox box = Material.of(tester.element(find.byType(InkWell)))as RenderBox;
expect(
box,
paints
..rect(rect: const Rect.fromLTRB(300.0, 200.0, 500.0, 400.0), color: Color(Colors.blue.value))
..circle(color: Color(Colors.green.value)),
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: Ink(
color: Colors.red,
width: 200.0,
height: 200.0,
child: InkWell(
splashColor: Colors.green,
onTap: () { },
),
),
),
),
),
);
expect(Material.of(tester.element(find.byType(InkWell))), same(box));
expect(
box,
paints
..rect(rect: const Rect.fromLTRB(300.0, 200.0, 500.0, 400.0), color: Color(Colors.red.value))
..circle(color: Color(Colors.green.value)),
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: InkWell( // this is at a different depth in the tree so it's now a new InkWell
splashColor: Colors.green,
onTap: () { },
),
),
),
),
);
expect(Material.of(tester.element(find.byType(InkWell))), same(box));
expect(box, isNot(paints..rect()));
expect(box, isNot(paints..circle()));
await gesture.up();
});
testWidgets('Material3 - Does the Ink widget render anything', (WidgetTester tester) async {
const Key inkWellKey = Key('InkWell');
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Ink(
color: Colors.blue,
width: 200.0,
height: 200.0,
child: InkWell(
key: inkWellKey,
splashColor: Colors.green,
onTap: () { },
),
),
),
),
),
);
final Offset center = tester.getCenter(find.byType(InkWell));
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
final RenderBox box = Material.of(tester.element(find.byType(InkWell)))as RenderBox;
expect(box, paints..rect(rect: const Rect.fromLTRB(300.0, 200.0, 500.0, 400.0), color: Color(Colors.blue.value)));
// Material 3 uses the InkSparkle which uses a shader, so we can't capture
// the effect with paint methods. Use a golden test instead.
await expectLater(
find.byKey(inkWellKey),
matchesGoldenFile('m3_ink.renders.anything.0.png'),
);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Ink(
color: Colors.red,
width: 200.0,
height: 200.0,
child: InkWell(
key: inkWellKey,
splashColor: Colors.green,
onTap: () { },
),
),
),
),
),
);
expect(Material.of(tester.element(find.byType(InkWell))), same(box));
expect(box, paints..rect(rect: const Rect.fromLTRB(300.0, 200.0, 500.0, 400.0), color: Color(Colors.red.value)));
// Material 3 uses the InkSparkle which uses a shader, so we can't capture
// the effect with paint methods. Use a golden test instead.
await expectLater(
find.byKey(inkWellKey),
matchesGoldenFile('m3_ink.renders.anything.1.png'),
);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: InkWell( // This is at a different depth in the tree so it's now a new InkWell.
key: inkWellKey,
splashColor: Colors.green,
onTap: () { },
),
),
),
),
);
expect(Material.of(tester.element(find.byType(InkWell))), same(box));
expect(box, isNot(paints..rect()));
expect(box, isNot(paints..rect()));
await gesture.up();
});
testWidgets('The InkWell widget renders an SelectAction or ActivateAction-induced ink ripple', (WidgetTester tester) async {
const Color highlightColor = Color(0xAAFF0000);
const Color splashColor = Color(0xB40000FF);
const BorderRadius borderRadius = BorderRadius.all(Radius.circular(6.0));
final FocusNode focusNode = FocusNode(debugLabel: 'Test Node');
addTearDown(focusNode.dispose);
Future<void> buildTest(Intent intent) async {
return tester.pumpWidget(
Shortcuts(
shortcuts: <ShortcutActivator, Intent>{
const SingleActivator(LogicalKeyboardKey.space): intent,
},
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: SizedBox(
width: 100.0,
height: 100.0,
child: InkWell(
borderRadius: borderRadius,
highlightColor: highlightColor,
splashColor: splashColor,
focusNode: focusNode,
onTap: () { },
radius: 100.0,
splashFactory: InkRipple.splashFactory,
),
),
),
),
),
),
);
}
await buildTest(const ActivateIntent());
focusNode.requestFocus();
await tester.pumpAndSettle();
final Offset topLeft = tester.getTopLeft(find.byType(InkWell));
final Offset inkWellCenter = tester.getCenter(find.byType(InkWell)) - topLeft;
bool offsetsAreClose(Offset a, Offset b) => (a - b).distance < 1.0;
bool radiiAreClose(double a, double b) => (a - b).abs() < 1.0;
PaintPattern ripplePattern(double expectedRadius, int expectedAlpha) {
return paints
..translate(x: 0.0, y: 0.0)
..translate(x: topLeft.dx, y: topLeft.dy)
..something((Symbol method, List<dynamic> arguments) {
if (method != #drawCircle) {
return false;
}
final Offset center = arguments[0] as Offset;
final double radius = arguments[1] as double;
final Paint paint = arguments[2] as Paint;
if (offsetsAreClose(center, inkWellCenter) &&
radiiAreClose(radius, expectedRadius) &&
paint.color.alpha == expectedAlpha) {
return true;
}
throw '''
Expected: center == $inkWellCenter, radius == $expectedRadius, alpha == $expectedAlpha
Found: center == $center radius == $radius alpha == ${paint.color.alpha}''';
},
);
}
await buildTest(const ActivateIntent());
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pump();
final RenderBox box = Material.of(tester.element(find.byType(InkWell)))as RenderBox;
// ripplePattern always add a translation of topLeft.
expect(box, ripplePattern(30.0, 0));
// The ripple fades in for 75ms. During that time its alpha is eased from
// 0 to the splashColor's alpha value.
await tester.pump(const Duration(milliseconds: 50));
expect(box, ripplePattern(56.0, 120));
// At 75ms the ripple has faded in: it's alpha matches the splashColor's
// alpha.
await tester.pump(const Duration(milliseconds: 25));
expect(box, ripplePattern(73.0, 180));
// At this point the splash radius has expanded to its limit: 5 past the
// ink well's radius parameter. The fade-out is about to start.
// The fade-out begins at 225ms = 50ms + 25ms + 150ms.
await tester.pump(const Duration(milliseconds: 150));
expect(box, ripplePattern(105.0, 180));
// After another 150ms the fade-out is complete.
await tester.pump(const Duration(milliseconds: 150));
expect(box, ripplePattern(105.0, 0));
});
testWidgets('Cancel an InkRipple that was disposed when its animation ended', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/14391
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: SizedBox(
width: 100.0,
height: 100.0,
child: InkWell(
onTap: () { },
radius: 100.0,
splashFactory: InkRipple.splashFactory,
),
),
),
),
),
);
final Offset tapDownOffset = tester.getTopLeft(find.byType(InkWell));
await tester.tapAt(tapDownOffset);
await tester.pump(); // start splash
await tester.pump(const Duration(milliseconds: 375)); // _kFadeOutDuration, in_ripple.dart
final TestGesture gesture = await tester.startGesture(tapDownOffset);
await tester.pump(); // start gesture
await gesture.moveTo(Offset.zero);
await gesture.up(); // generates a tap cancel
await tester.pumpAndSettle();
});
testWidgets('Cancel an InkRipple that was disposed when its animation ended', (WidgetTester tester) async {
const Color highlightColor = Color(0xAAFF0000);
const Color splashColor = Color(0xB40000FF);
// Regression test for https://github.com/flutter/flutter/issues/14391
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: SizedBox(
width: 100.0,
height: 100.0,
child: InkWell(
splashColor: splashColor,
highlightColor: highlightColor,
onTap: () { },
radius: 100.0,
splashFactory: InkRipple.splashFactory,
),
),
),
),
),
);
final Offset tapDownOffset = tester.getTopLeft(find.byType(InkWell));
await tester.tapAt(tapDownOffset);
await tester.pump(); // start splash
// No delay here so _fadeInController.value=1.0 (InkRipple.dart)
// Generate a tap cancel; Will cancel the ink splash before it started
final TestGesture gesture = await tester.startGesture(tapDownOffset);
await tester.pump(); // start gesture
await gesture.moveTo(Offset.zero);
await gesture.up(); // generates a tap cancel
final RenderBox box = Material.of(tester.element(find.byType(InkWell)))as RenderBox;
expect(box, paints..everything((Symbol method, List<dynamic> arguments) {
if (method != #drawCircle) {
return true;
}
final Paint paint = arguments[2] as Paint;
if (paint.color.alpha == 0) {
return true;
}
throw 'Expected: paint.color.alpha == 0, found: ${paint.color.alpha}';
}));
});
testWidgets('The InkWell widget on OverlayPortal does not throw', (WidgetTester tester) async {
final OverlayPortalController controller = OverlayPortalController();
controller.show();
late OverlayEntry overlayEntry;
addTearDown(() => overlayEntry..remove()..dispose());
await tester.pumpWidget(
Center(
child: RepaintBoundary(
child: SizedBox.square(
dimension: 200,
child: Directionality(
textDirection: TextDirection.ltr,
child: Overlay(
initialEntries: <OverlayEntry>[
overlayEntry = OverlayEntry(
builder: (BuildContext context) {
return Center(
child: SizedBox.square(
dimension: 100,
// The material partially overlaps the overlayChild.
// This is to verify that the `overlayChild`'s ink
// features aren't clipped by it.
child: Material(
color: Colors.black,
child: OverlayPortal(
controller: controller,
overlayChildBuilder: (BuildContext context) {
return Positioned(
right: 0,
bottom: 0,
child: InkWell(
splashColor: Colors.red,
onTap: () {},
child: const SizedBox.square(dimension: 100),
),
);
},
),
),
),
);
},
),
],
),
),
),
),
),
);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(InkWell)));
addTearDown(() async {
await gesture.up();
});
await tester.pump(); // start gesture
await tester.pump(const Duration(seconds: 2));
expect(tester.takeException(), isNull);
});
testWidgets('Material2 - Custom rectCallback renders an ink splash from its center', (WidgetTester tester) async {
const Color splashColor = Color(0xff00ff00);
Widget buildWidget({InteractiveInkFeatureFactory? splashFactory}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: SizedBox(
width: 100.0,
height: 200.0,
child: InkResponse(
splashColor: splashColor,
containedInkWell: true,
highlightShape: BoxShape.rectangle,
splashFactory: splashFactory,
onTap: () { },
),
),
),
),
);
}
await tester.pumpWidget(buildWidget());
final Offset center = tester.getCenter(find.byType(SizedBox));
TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start gesture
await tester.pumpAndSettle(); // Finish rendering ink splash.
RenderBox box = Material.of(tester.element(find.byType(InkResponse))) as RenderBox;
expect(
box,
paints
..circle(x: 50.0, y: 100.0, color: splashColor)
);
await gesture.up();
await tester.pumpWidget(buildWidget(splashFactory: _InkRippleFactory()));
await tester.pumpAndSettle(); // Finish rendering ink splash.
gesture = await tester.startGesture(center);
await tester.pump(); // start gesture
await tester.pumpAndSettle(); // Finish rendering ink splash.
box = Material.of(tester.element(find.byType(InkResponse))) as RenderBox;
expect(
box,
paints
..circle(x: 50.0, y: 50.0, color: splashColor)
);
});
testWidgets('Material3 - Custom rectCallback renders an ink splash from its center', (WidgetTester tester) async {
const Key inkWResponseKey = Key('InkResponse');
const Color splashColor = Color(0xff00ff00);
Widget buildWidget({InteractiveInkFeatureFactory? splashFactory}) {
return MaterialApp(
home: Material(
child: Center(
child: SizedBox(
width: 100.0,
height: 200.0,
child: InkResponse(
key: inkWResponseKey,
splashColor: splashColor,
containedInkWell: true,
highlightShape: BoxShape.rectangle,
splashFactory: splashFactory,
onTap: () { },
),
),
),
),
);
}
await tester.pumpWidget(buildWidget());
final Offset center = tester.getCenter(find.byType(SizedBox));
TestGesture gesture = await tester.startGesture(center);
await tester.pump(); // start gesture
await tester.pumpAndSettle(); // Finish rendering ink splash.
// Material 3 uses the InkSparkle which uses a shader, so we can't capture
// the effect with paint methods. Use a golden test instead.
await expectLater(
find.byKey(inkWResponseKey),
matchesGoldenFile('m3_ink_response.renders.ink_splash_from_its_center.0.png'),
);
await gesture.up();
await tester.pumpWidget(buildWidget(splashFactory: _InkRippleFactory()));
await tester.pumpAndSettle(); // Finish rendering ink splash.
gesture = await tester.startGesture(center);
await tester.pump(); // start gesture
await tester.pumpAndSettle(); // Finish rendering ink splash.
// Material 3 uses the InkSparkle which uses a shader, so we can't capture
// the effect with paint methods. Use a golden test instead.
await expectLater(
find.byKey(inkWResponseKey),
matchesGoldenFile('m3_ink_response.renders.ink_splash_from_its_center.1.png'),
);
});
testWidgets('Ink with isVisible=false does not paint', (WidgetTester tester) async {
const Color testColor = Color(0xffff1234);
Widget inkWidget({required bool isVisible}) {
return Material(
child: Visibility.maintain(
visible: isVisible,
child: Ink(
decoration: const BoxDecoration(color: testColor),
),
),
);
}
await tester.pumpWidget(inkWidget(isVisible: true));
RenderBox box = tester.renderObject(find.byType(Material));
expect(box, paints..rect(color: testColor));
await tester.pumpWidget(inkWidget(isVisible: false));
box = tester.renderObject(find.byType(Material));
expect(box, isNot(paints..rect(color: testColor)));
});
}
class _InkRippleFactory extends InteractiveInkFeatureFactory {
@override
InteractiveInkFeature create({
required MaterialInkController controller,
required RenderBox referenceBox,
required Offset position,
required Color color,
required TextDirection textDirection,
bool containedInkWell = false,
RectCallback? rectCallback,
BorderRadius? borderRadius,
ShapeBorder? customBorder,
double? radius,
VoidCallback? onRemoved,
}) {
return InkRipple(
controller: controller,
referenceBox: referenceBox,
position: position,
color: color,
containedInkWell: containedInkWell,
rectCallback: () => Offset.zero & const Size(100, 100),
borderRadius: borderRadius,
customBorder: customBorder,
radius: radius,
onRemoved: onRemoved,
textDirection: textDirection,
);
}
}
| flutter/packages/flutter/test/material/ink_paint_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/ink_paint_test.dart",
"repo_id": "flutter",
"token_count": 12757
} | 673 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() {
late MenuController controller;
String? focusedMenu;
final List<TestMenu> selected = <TestMenu>[];
final List<TestMenu> opened = <TestMenu>[];
final List<TestMenu> closed = <TestMenu>[];
final GlobalKey menuItemKey = GlobalKey();
void onPressed(TestMenu item) {
selected.add(item);
}
void onOpen(TestMenu item) {
opened.add(item);
}
void onClose(TestMenu item) {
closed.add(item);
}
void handleFocusChange() {
focusedMenu = (primaryFocus?.debugLabel ?? primaryFocus).toString();
}
setUp(() {
focusedMenu = null;
selected.clear();
opened.clear();
closed.clear();
controller = MenuController();
focusedMenu = null;
});
Future<void> changeSurfaceSize(WidgetTester tester, Size size) async {
await tester.binding.setSurfaceSize(size);
addTearDown(() async {
await tester.binding.setSurfaceSize(null);
});
}
void listenForFocusChanges() {
FocusManager.instance.addListener(handleFocusChange);
addTearDown(() => FocusManager.instance.removeListener(handleFocusChange));
}
Finder findMenuPanels() {
return find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_MenuPanel');
}
Finder findMenuBarItemLabels() {
return find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_MenuItemLabel');
}
// Finds the mnemonic associated with the menu item that has the given label.
Finder findMnemonic(String label) {
return find
.descendant(
of: find.ancestor(of: find.text(label), matching: findMenuBarItemLabels()),
matching: find.byType(Text),
)
.last;
}
Widget buildTestApp({
AlignmentGeometry? alignment,
Offset alignmentOffset = Offset.zero,
TextDirection textDirection = TextDirection.ltr,
bool consumesOutsideTap = false,
void Function(TestMenu)? onPressed,
void Function(TestMenu)? onOpen,
void Function(TestMenu)? onClose,
}) {
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: textDirection,
child: Column(
children: <Widget>[
GestureDetector(
onTap: () {
onPressed?.call(TestMenu.outsideButton);
},
child: Text(TestMenu.outsideButton.label)),
MenuAnchor(
childFocusNode: focusNode,
controller: controller,
alignmentOffset: alignmentOffset,
consumeOutsideTap: consumesOutsideTap,
style: MenuStyle(alignment: alignment),
onOpen: () {
onOpen?.call(TestMenu.anchorButton);
},
onClose: () {
onClose?.call(TestMenu.anchorButton);
},
menuChildren: <Widget>[
MenuItemButton(
key: menuItemKey,
shortcut: const SingleActivator(
LogicalKeyboardKey.keyB,
control: true,
),
onPressed: () {
onPressed?.call(TestMenu.subMenu00);
},
child: Text(TestMenu.subMenu00.label),
),
MenuItemButton(
leadingIcon: const Icon(Icons.send),
trailingIcon: const Icon(Icons.mail),
onPressed: () {
onPressed?.call(TestMenu.subMenu01);
},
child: Text(TestMenu.subMenu01.label),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return ElevatedButton(
focusNode: focusNode,
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
onPressed?.call(TestMenu.anchorButton);
},
child: child,
);
},
child: Text(TestMenu.anchorButton.label),
),
],
),
),
),
);
}
Future<TestGesture> hoverOver(WidgetTester tester, Finder finder) async {
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(finder));
await tester.pumpAndSettle();
return gesture;
}
Material getMenuBarMaterial(WidgetTester tester) {
return tester.widget<Material>(
find.descendant(of: findMenuPanels(), matching: find.byType(Material)).first,
);
}
testWidgets('Menu responds to density changes', (WidgetTester tester) async {
Widget buildMenu({VisualDensity? visualDensity = VisualDensity.standard}) {
return MaterialApp(
theme: ThemeData(visualDensity: visualDensity, useMaterial3: false),
home: Material(
child: Column(
children: <Widget>[
MenuBar(
children: createTestMenus(onPressed: onPressed),
),
const Expanded(child: Placeholder()),
],
),
),
);
}
await tester.pumpWidget(buildMenu());
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(145.0, 0.0, 655.0, 48.0)));
// Open and make sure things are the right size.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(145.0, 0.0, 655.0, 48.0)));
expect(
tester.getRect(find.widgetWithText(MenuItemButton, TestMenu.subMenu10.label)),
equals(const Rect.fromLTRB(257.0, 56.0, 471.0, 104.0)),
);
expect(
tester.getRect(
find.ancestor(of: find.text(TestMenu.subMenu10.label), matching: find.byType(Material)).at(1),
),
equals(const Rect.fromLTRB(257.0, 48.0, 471.0, 208.0)),
);
// Test compact visual density (-2, -2)
await tester.pumpWidget(Container());
await tester.pumpWidget(buildMenu(visualDensity: VisualDensity.compact));
await tester.pump();
// The original horizontal padding with standard visual density for menu buttons are 12 px, and the total length
// for the menu bar is (655 - 145) = 510.
// There are 4 buttons in the test menu bar, and with compact visual density,
// the padding will reduce by abs(2 * (-2)) = 4. So the total length
// now should reduce by abs(4 * 2 * (-4)) = 32, which would be 510 - 32 = 478, and
// 478 = 639 - 161
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(161.0, 0.0, 639.0, 40.0)));
// Open and make sure things are the right size.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(161.0, 0.0, 639.0, 40.0)));
expect(
tester.getRect(find.widgetWithText(MenuItemButton, TestMenu.subMenu10.label)),
equals(const Rect.fromLTRB(265.0, 40.0, 467.0, 80.0)),
);
expect(
tester.getRect(
find.ancestor(of: find.text(TestMenu.subMenu10.label), matching: find.byType(Material)).at(1),
),
equals(const Rect.fromLTRB(265.0, 40.0, 467.0, 160.0)),
);
await tester.pumpWidget(Container());
await tester.pumpWidget(buildMenu(visualDensity: const VisualDensity(horizontal: 2.0, vertical: 2.0)));
await tester.pump();
// Similarly, there are 4 buttons in the test menu bar, and with (2, 2) visual density,
// the padding will increase by abs(2 * 4) = 8. So the total length for buttons
// should increase by abs(4 * 2 * 8) = 64. The horizontal padding for the menu bar
// increases by 2 * 8, so the total width increases to 510 + 64 + 16 = 590, and
// 590 = 695 - 105
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(105.0, 0.0, 695.0, 72.0)));
// Open and make sure things are the right size.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(105.0, 0.0, 695.0, 72.0)));
expect(
tester.getRect(find.widgetWithText(MenuItemButton, TestMenu.subMenu10.label)),
equals(const Rect.fromLTRB(249.0, 80.0, 483.0, 136.0)),
);
expect(
tester.getRect(
find.ancestor(of: find.text(TestMenu.subMenu10.label), matching: find.byType(Material)).at(1),
),
equals(const Rect.fromLTRB(241.0, 64.0, 491.0, 264.0)),
);
});
testWidgets('Menu defaults', (WidgetTester tester) async {
final ThemeData themeData = ThemeData();
await tester.pumpWidget(
MaterialApp(
theme: themeData,
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
);
// menu bar(horizontal menu)
Finder menuMaterial = find
.ancestor(
of: find.byType(TextButton),
matching: find.byType(Material),
)
.first;
Material material = tester.widget<Material>(menuMaterial);
expect(opened, isEmpty);
expect(material.color, themeData.colorScheme.surfaceContainer);
expect(material.shadowColor, themeData.colorScheme.shadow);
expect(material.surfaceTintColor, Colors.transparent);
expect(material.elevation, 3.0);
expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))));
Finder buttonMaterial = find
.descendant(
of: find.byType(TextButton),
matching: find.byType(Material),
)
.first;
material = tester.widget<Material>(buttonMaterial);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shape, const RoundedRectangleBorder());
expect(material.textStyle?.color, themeData.colorScheme.onSurface);
expect(material.textStyle?.fontSize, 14.0);
expect(material.textStyle?.height, 1.43);
// vertical menu
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
menuMaterial = find
.ancestor(
of: find.widgetWithText(TextButton, TestMenu.subMenu10.label),
matching: find.byType(Material),
)
.first;
material = tester.widget<Material>(menuMaterial);
expect(opened.last, equals(TestMenu.mainMenu1));
expect(material.color, themeData.colorScheme.surfaceContainer);
expect(material.shadowColor, themeData.colorScheme.shadow);
expect(material.surfaceTintColor, Colors.transparent);
expect(material.elevation, 3.0);
expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))));
buttonMaterial = find
.descendant(
of: find.widgetWithText(TextButton, TestMenu.subMenu10.label),
matching: find.byType(Material),
)
.first;
material = tester.widget<Material>(buttonMaterial);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shape, const RoundedRectangleBorder());
expect(material.textStyle?.color, themeData.colorScheme.onSurface);
expect(material.textStyle?.fontSize, 14.0);
expect(material.textStyle?.height, 1.43);
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(find.byIcon(Icons.add), findsOneWidget);
final RichText iconRichText = tester.widget<RichText>(
find.descendant(of: find.byIcon(Icons.add), matching: find.byType(RichText)),
);
expect(iconRichText.text.style?.color, themeData.colorScheme.onSurfaceVariant);
});
testWidgets('Menu defaults - disabled', (WidgetTester tester) async {
final ThemeData themeData = ThemeData();
await tester.pumpWidget(
MaterialApp(
theme: themeData,
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
);
// menu bar(horizontal menu)
Finder menuMaterial = find
.ancestor(
of: find.widgetWithText(TextButton, TestMenu.mainMenu5.label),
matching: find.byType(Material),
)
.first;
Material material = tester.widget<Material>(menuMaterial);
expect(opened, isEmpty);
expect(material.color, themeData.colorScheme.surfaceContainer);
expect(material.shadowColor, themeData.colorScheme.shadow);
expect(material.surfaceTintColor, Colors.transparent);
expect(material.elevation, 3.0);
expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))));
Finder buttonMaterial = find
.descendant(
of: find.widgetWithText(TextButton, TestMenu.mainMenu5.label),
matching: find.byType(Material),
)
.first;
material = tester.widget<Material>(buttonMaterial);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shape, const RoundedRectangleBorder());
expect(material.textStyle?.color, themeData.colorScheme.onSurface.withOpacity(0.38));
// vertical menu
await tester.tap(find.text(TestMenu.mainMenu2.label));
await tester.pump();
menuMaterial = find
.ancestor(
of: find.widgetWithText(TextButton, TestMenu.subMenu20.label),
matching: find.byType(Material),
)
.first;
material = tester.widget<Material>(menuMaterial);
expect(material.color, themeData.colorScheme.surfaceContainer);
expect(material.shadowColor, themeData.colorScheme.shadow);
expect(material.surfaceTintColor, Colors.transparent);
expect(material.elevation, 3.0);
expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))));
buttonMaterial = find
.descendant(
of: find.widgetWithText(TextButton, TestMenu.subMenu20.label),
matching: find.byType(Material),
)
.first;
material = tester.widget<Material>(buttonMaterial);
expect(material.color, Colors.transparent);
expect(material.elevation, 0.0);
expect(material.shape, const RoundedRectangleBorder());
expect(material.textStyle?.color, themeData.colorScheme.onSurface.withOpacity(0.38));
expect(find.byIcon(Icons.ac_unit), findsOneWidget);
final RichText iconRichText = tester.widget<RichText>(
find.descendant(of: find.byIcon(Icons.ac_unit), matching: find.byType(RichText)),
);
expect(iconRichText.text.style?.color, themeData.colorScheme.onSurface.withOpacity(0.38));
});
testWidgets('Menu scrollbar inherits ScrollbarTheme', (WidgetTester tester) async {
const ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(
thumbColor: MaterialStatePropertyAll<Color?>(Color(0xffff0000)),
thumbVisibility: MaterialStatePropertyAll<bool?>(true),
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(scrollbarTheme: scrollbarTheme),
home: Material(
child: MenuBar(
children: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
style: ButtonStyle(
minimumSize: MaterialStateProperty.all<Size>(
const Size.fromHeight(1000),
),
),
onPressed: () {},
child: const Text(
'Category',
),
),
],
child: const Text(
'Main Menu',
),
),
],
),
),
),
);
await tester.tap(find.text('Main Menu'));
await tester.pumpAndSettle();
// Test Scrollbar thumb color.
expect(
find.byType(Scrollbar).last,
paints..rrect(color: const Color(0xffff0000)),
);
// Close the menu.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(scrollbarTheme: scrollbarTheme),
home: Material(
child: ScrollbarTheme(
data: scrollbarTheme.copyWith(
thumbColor: const MaterialStatePropertyAll<Color?>(Color(0xff00ff00)),
),
child: MenuBar(
children: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
style: ButtonStyle(
minimumSize: MaterialStateProperty.all<Size>(
const Size.fromHeight(1000),
),
),
onPressed: () {},
child: const Text(
'Category',
),
),
],
child: const Text(
'Main Menu',
),
),
],
),
),
),
),
);
await tester.tap(find.text('Main Menu'));
await tester.pumpAndSettle();
// Scrollbar thumb color should be updated.
expect(
find.byType(Scrollbar).last,
paints..rrect(color: const Color(0xff00ff00)),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets('focus is returned to previous focus before invoking onPressed', (WidgetTester tester) async {
final FocusNode buttonFocus = FocusNode(debugLabel: 'Button Focus');
addTearDown(buttonFocus.dispose);
FocusNode? focusInOnPressed;
void onMenuSelected(TestMenu item) {
focusInOnPressed = FocusManager.instance.primaryFocus;
}
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onMenuSelected,
),
),
ElevatedButton(
autofocus: true,
onPressed: () {},
focusNode: buttonFocus,
child: const Text('Press Me'),
),
],
),
),
),
);
await tester.pump();
expect(FocusManager.instance.primaryFocus, equals(buttonFocus));
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subSubMenu110.label));
await tester.pump();
expect(focusInOnPressed, equals(buttonFocus));
expect(FocusManager.instance.primaryFocus, equals(buttonFocus));
});
group('Menu functions', () {
testWidgets('basic menu structure', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
);
expect(find.text(TestMenu.mainMenu0.label), findsOneWidget);
expect(find.text(TestMenu.mainMenu1.label), findsOneWidget);
expect(find.text(TestMenu.mainMenu2.label), findsOneWidget);
expect(find.text(TestMenu.subMenu10.label), findsNothing);
expect(find.text(TestMenu.subSubMenu110.label), findsNothing);
expect(opened, isEmpty);
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(find.text(TestMenu.mainMenu0.label), findsOneWidget);
expect(find.text(TestMenu.mainMenu1.label), findsOneWidget);
expect(find.text(TestMenu.mainMenu2.label), findsOneWidget);
expect(find.text(TestMenu.subMenu10.label), findsOneWidget);
expect(find.text(TestMenu.subMenu11.label), findsOneWidget);
expect(find.text(TestMenu.subMenu12.label), findsOneWidget);
expect(find.text(TestMenu.subSubMenu110.label), findsNothing);
expect(find.text(TestMenu.subSubMenu111.label), findsNothing);
expect(find.text(TestMenu.subSubMenu112.label), findsNothing);
expect(opened.last, equals(TestMenu.mainMenu1));
opened.clear();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(find.text(TestMenu.mainMenu0.label), findsOneWidget);
expect(find.text(TestMenu.mainMenu1.label), findsOneWidget);
expect(find.text(TestMenu.mainMenu2.label), findsOneWidget);
expect(find.text(TestMenu.subMenu10.label), findsOneWidget);
expect(find.text(TestMenu.subMenu11.label), findsOneWidget);
expect(find.text(TestMenu.subMenu12.label), findsOneWidget);
expect(find.text(TestMenu.subSubMenu110.label), findsOneWidget);
expect(find.text(TestMenu.subSubMenu111.label), findsOneWidget);
expect(find.text(TestMenu.subSubMenu112.label), findsOneWidget);
expect(opened.last, equals(TestMenu.subMenu11));
});
testWidgets('geometry', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: MenuBar(
children: createTestMenus(onPressed: onPressed),
),
),
],
),
const Expanded(child: Placeholder()),
],
),
),
),
);
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(0, 0, 800, 48)));
// Open and make sure things are the right size.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(0, 0, 800, 48)));
expect(
tester.getRect(find.text(TestMenu.subMenu10.label)),
equals(const Rect.fromLTRB(124.0, 73.0, 278.0, 87.0)),
);
expect(
tester.getRect(
find.ancestor(of: find.text(TestMenu.subMenu10.label), matching: find.byType(Material)).at(1),
),
equals(const Rect.fromLTRB(112.0, 48.0, 326.0, 208.0)),
);
// Test menu bar size when not expanded.
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
MenuBar(
children: createTestMenus(onPressed: onPressed),
),
const Expanded(child: Placeholder()),
],
),
),
),
);
await tester.pump();
expect(
tester.getRect(find.byType(MenuBar)),
equals(const Rect.fromLTRB(145.0, 0.0, 655.0, 48.0)),
);
});
testWidgets('geometry with RTL direction', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.rtl,
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: MenuBar(
children: createTestMenus(onPressed: onPressed),
),
),
],
),
const Expanded(child: Placeholder()),
],
),
),
),
),
);
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(0, 0, 800, 48)));
// Open and make sure things are the right size.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(0, 0, 800, 48)));
expect(
tester.getRect(find.text(TestMenu.subMenu10.label)),
equals(const Rect.fromLTRB(522.0, 73.0, 676.0, 87.0)),
);
expect(
tester.getRect(
find.ancestor(of: find.text(TestMenu.subMenu10.label), matching: find.byType(Material)).at(1),
),
equals(const Rect.fromLTRB(474.0, 48.0, 688.0, 208.0)),
);
// Close and make sure it goes back where it was.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(0, 0, 800, 48)));
// Test menu bar size when not expanded.
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Directionality(
textDirection: TextDirection.rtl,
child: Column(
children: <Widget>[
MenuBar(
children: createTestMenus(onPressed: onPressed),
),
const Expanded(child: Placeholder()),
],
),
),
),
),
);
await tester.pump();
expect(
tester.getRect(find.byType(MenuBar)),
equals(const Rect.fromLTRB(145.0, 0.0, 655.0, 48.0)),
);
});
testWidgets('menu alignment and offset in LTR', (WidgetTester tester) async {
await tester.pumpWidget(buildTestApp());
final Rect buttonRect = tester.getRect(find.byType(ElevatedButton));
expect(buttonRect, equals(const Rect.fromLTRB(328.0, 14.0, 472.0, 62.0)));
final Finder findMenuScope = find.ancestor(of: find.byKey(menuItemKey), matching: find.byType(FocusScope)).first;
// Open the menu and make sure things are the right size, in the right place.
await tester.tap(find.text('Press Me'));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(328.0, 62.0, 602.0, 174.0)));
await tester.pumpWidget(buildTestApp(alignment: AlignmentDirectional.topStart));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(328.0, 14.0, 602.0, 126.0)));
await tester.pumpWidget(buildTestApp(alignment: AlignmentDirectional.center));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(400.0, 38.0, 674.0, 150.0)));
await tester.pumpWidget(buildTestApp(alignment: AlignmentDirectional.bottomEnd));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(472.0, 62.0, 746.0, 174.0)));
await tester.pumpWidget(buildTestApp(alignment: AlignmentDirectional.topStart));
await tester.pump();
final Rect menuRect = tester.getRect(findMenuScope);
await tester.pumpWidget(
buildTestApp(
alignment: AlignmentDirectional.topStart,
alignmentOffset: const Offset(10, 20),
),
);
await tester.pump();
final Rect offsetMenuRect = tester.getRect(findMenuScope);
expect(
offsetMenuRect.topLeft - menuRect.topLeft,
equals(const Offset(10, 20)),
);
});
testWidgets('menu alignment and offset in RTL', (WidgetTester tester) async {
await tester.pumpWidget(buildTestApp(textDirection: TextDirection.rtl));
final Rect buttonRect = tester.getRect(find.byType(ElevatedButton));
expect(buttonRect, equals(const Rect.fromLTRB(328.0, 14.0, 472.0, 62.0)));
final Finder findMenuScope =
find.ancestor(of: find.text(TestMenu.subMenu00.label), matching: find.byType(FocusScope)).first;
// Open the menu and make sure things are the right size, in the right place.
await tester.tap(find.text('Press Me'));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(198.0, 62.0, 472.0, 174.0)));
await tester.pumpWidget(buildTestApp(textDirection: TextDirection.rtl, alignment: AlignmentDirectional.topStart));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(198.0, 14.0, 472.0, 126.0)));
await tester.pumpWidget(buildTestApp(textDirection: TextDirection.rtl, alignment: AlignmentDirectional.center));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(126.0, 38.0, 400.0, 150.0)));
await tester
.pumpWidget(buildTestApp(textDirection: TextDirection.rtl, alignment: AlignmentDirectional.bottomEnd));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(54.0, 62.0, 328.0, 174.0)));
await tester.pumpWidget(buildTestApp(textDirection: TextDirection.rtl, alignment: AlignmentDirectional.topStart));
await tester.pump();
final Rect menuRect = tester.getRect(findMenuScope);
await tester.pumpWidget(
buildTestApp(
textDirection: TextDirection.rtl,
alignment: AlignmentDirectional.topStart,
alignmentOffset: const Offset(10, 20),
),
);
await tester.pump();
expect(tester.getRect(findMenuScope).topLeft - menuRect.topLeft, equals(const Offset(-10, 20)));
});
testWidgets('menu position in LTR', (WidgetTester tester) async {
await tester.pumpWidget(buildTestApp(alignmentOffset: const Offset(100, 50)));
final Rect buttonRect = tester.getRect(find.byType(ElevatedButton));
expect(buttonRect, equals(const Rect.fromLTRB(328.0, 14.0, 472.0, 62.0)));
final Finder findMenuScope =
find.ancestor(of: find.text(TestMenu.subMenu00.label), matching: find.byType(FocusScope)).first;
// Open the menu and make sure things are the right size, in the right place.
await tester.tap(find.text('Press Me'));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(428.0, 112.0, 702.0, 224.0)));
// Now move the menu by calling open() again with a local position on the
// anchor.
controller.open(position: const Offset(200, 200));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(526.0, 214.0, 800.0, 326.0)));
});
testWidgets('menu position in RTL', (WidgetTester tester) async {
await tester.pumpWidget(buildTestApp(
alignmentOffset: const Offset(100, 50),
textDirection: TextDirection.rtl,
));
final Rect buttonRect = tester.getRect(find.byType(ElevatedButton));
expect(buttonRect, equals(const Rect.fromLTRB(328.0, 14.0, 472.0, 62.0)));
expect(buttonRect, equals(const Rect.fromLTRB(328.0, 14.0, 472.0, 62.0)));
final Finder findMenuScope =
find.ancestor(of: find.text(TestMenu.subMenu00.label), matching: find.byType(FocusScope)).first;
// Open the menu and make sure things are the right size, in the right place.
await tester.tap(find.text('Press Me'));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(98.0, 112.0, 372.0, 224.0)));
// Now move the menu by calling open() again with a local position on the
// anchor.
controller.open(position: const Offset(400, 200));
await tester.pump();
expect(tester.getRect(findMenuScope), equals(const Rect.fromLTRB(526.0, 214.0, 800.0, 326.0)));
});
testWidgets('works with Padding around menu and overlay', (WidgetTester tester) async {
await tester.pumpWidget(
Padding(
padding: const EdgeInsets.all(10.0),
child: MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
children: <Widget>[
Expanded(
child: MenuBar(
children: createTestMenus(onPressed: onPressed),
),
),
],
),
),
const Expanded(child: Placeholder()),
],
),
),
),
),
);
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(22.0, 22.0, 778.0, 70.0)));
// Open and make sure things are the right size.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(22.0, 22.0, 778.0, 70.0)));
expect(
tester.getRect(find.text(TestMenu.subMenu10.label)),
equals(const Rect.fromLTRB(146.0, 95.0, 300.0, 109.0)),
);
expect(
tester.getRect(find.ancestor(of: find.text(TestMenu.subMenu10.label), matching: find.byType(Material)).at(1)),
equals(const Rect.fromLTRB(134.0, 70.0, 348.0, 230.0)),
);
// Close and make sure it goes back where it was.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(22.0, 22.0, 778.0, 70.0)));
});
testWidgets('works with Padding around menu and overlay with RTL direction', (WidgetTester tester) async {
await tester.pumpWidget(
Padding(
padding: const EdgeInsets.all(10.0),
child: MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.rtl,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
children: <Widget>[
Expanded(
child: MenuBar(
children: createTestMenus(onPressed: onPressed),
),
),
],
),
),
const Expanded(child: Placeholder()),
],
),
),
),
),
),
);
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(22.0, 22.0, 778.0, 70.0)));
// Open and make sure things are the right size.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(22.0, 22.0, 778.0, 70.0)));
expect(
tester.getRect(find.text(TestMenu.subMenu10.label)),
equals(const Rect.fromLTRB(500.0, 95.0, 654.0, 109.0)),
);
expect(
tester.getRect(find.ancestor(of: find.text(TestMenu.subMenu10.label), matching: find.byType(Material)).at(1)),
equals(const Rect.fromLTRB(452.0, 70.0, 666.0, 230.0)),
);
// Close and make sure it goes back where it was.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(22.0, 22.0, 778.0, 70.0)));
});
testWidgets('visual attributes can be set', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: MenuBar(
style: MenuStyle(
elevation: MaterialStateProperty.all<double?>(10),
backgroundColor: const MaterialStatePropertyAll<Color>(Colors.red),
),
children: createTestMenus(onPressed: onPressed),
),
),
],
),
const Expanded(child: Placeholder()),
],
),
),
),
);
expect(tester.getRect(findMenuPanels()), equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 48.0)));
final Material material = getMenuBarMaterial(tester);
expect(material.elevation, equals(10));
expect(material.color, equals(Colors.red));
});
testWidgets('MenuAnchor clip behavior', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: MenuAnchor(
menuChildren: const <Widget>[
MenuItemButton(
child: Text('Button 1'),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return FilledButton(
onPressed: () {
controller.open();
},
child: const Text('Tap me'),
);
},
),
),
),
),
);
await tester.tap(find.text('Tap me'));
await tester.pump();
// Test default clip behavior.
expect(getMenuBarMaterial(tester).clipBehavior, equals(Clip.hardEdge));
// Close the menu.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: MenuAnchor(
clipBehavior: Clip.antiAlias,
menuChildren: const <Widget>[
MenuItemButton(
child: Text('Button 1'),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return FilledButton(
onPressed: () {
controller.open();
},
child: const Text('Tap me'),
);
},
),
),
),
),
);
await tester.tap(find.text('Tap me'));
await tester.pump();
// Test custom clip behavior.
expect(getMenuBarMaterial(tester).clipBehavior, equals(Clip.antiAlias));
});
testWidgets('open and close works', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
);
expect(opened, isEmpty);
expect(closed, isEmpty);
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.mainMenu1]));
expect(closed, isEmpty);
opened.clear();
closed.clear();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.subMenu11]));
expect(closed, isEmpty);
opened.clear();
closed.clear();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(opened, isEmpty);
expect(closed, equals(<TestMenu>[TestMenu.subMenu11]));
opened.clear();
closed.clear();
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.mainMenu0]));
expect(closed, equals(<TestMenu>[TestMenu.mainMenu1]));
});
testWidgets('Menus close and consume tap when open and tapped outside', (WidgetTester tester) async {
await tester.pumpWidget(
buildTestApp(consumesOutsideTap: true, onPressed: onPressed, onOpen: onOpen, onClose: onClose),
);
expect(opened, isEmpty);
expect(closed, isEmpty);
// Doesn't consume tap when the menu is closed.
await tester.tap(find.text(TestMenu.outsideButton.label));
await tester.pump();
expect(selected, equals(<TestMenu>[TestMenu.outsideButton]));
selected.clear();
await tester.tap(find.text(TestMenu.anchorButton.label));
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.anchorButton]));
expect(closed, isEmpty);
expect(selected, equals(<TestMenu>[TestMenu.anchorButton]));
opened.clear();
closed.clear();
selected.clear();
await tester.tap(find.text(TestMenu.outsideButton.label));
await tester.pump();
expect(opened, isEmpty);
expect(closed, equals(<TestMenu>[TestMenu.anchorButton]));
// When the menu is open, don't expect the outside button to be selected:
// it's supposed to consume the key down.
expect(selected, isEmpty);
selected.clear();
opened.clear();
closed.clear();
});
testWidgets("Menus close and don't consume tap when open and tapped outside", (WidgetTester tester) async {
await tester.pumpWidget(
buildTestApp(onPressed: onPressed, onOpen: onOpen, onClose: onClose),
);
expect(opened, isEmpty);
expect(closed, isEmpty);
// Doesn't consume tap when the menu is closed.
await tester.tap(find.text(TestMenu.outsideButton.label));
await tester.pump();
expect(selected, equals(<TestMenu>[TestMenu.outsideButton]));
selected.clear();
await tester.tap(find.text(TestMenu.anchorButton.label));
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.anchorButton]));
expect(closed, isEmpty);
expect(selected, equals(<TestMenu>[TestMenu.anchorButton]));
opened.clear();
closed.clear();
selected.clear();
await tester.tap(find.text(TestMenu.outsideButton.label));
await tester.pump();
expect(opened, isEmpty);
expect(closed, equals(<TestMenu>[TestMenu.anchorButton]));
// Because consumesOutsideTap is false, this is expected to receive its
// tap.
expect(selected, equals(<TestMenu>[TestMenu.outsideButton]));
selected.clear();
opened.clear();
closed.clear();
});
testWidgets('select works', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
);
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.mainMenu1, TestMenu.subMenu11]));
opened.clear();
await tester.tap(find.text(TestMenu.subSubMenu110.label));
await tester.pump();
expect(selected, equals(<TestMenu>[TestMenu.subSubMenu110]));
// Selecting a non-submenu item should close all the menus.
expect(opened, isEmpty);
expect(find.text(TestMenu.subSubMenu110.label), findsNothing);
expect(find.text(TestMenu.subMenu11.label), findsNothing);
});
testWidgets('diagnostics', (WidgetTester tester) async {
const MenuItemButton item = MenuItemButton(
shortcut: SingleActivator(LogicalKeyboardKey.keyA),
child: Text('label2'),
);
final MenuBar menuBar = MenuBar(
controller: controller,
style: const MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color>(Colors.red),
elevation: MaterialStatePropertyAll<double?>(10.0),
),
children: const <Widget>[item],
);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: menuBar,
),
),
);
await tester.pump();
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
menuBar.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(
description.join('\n'),
equalsIgnoringHashCodes(
'style: MenuStyle#00000(backgroundColor: WidgetStatePropertyAll(MaterialColor(primary value: Color(0xfff44336))), elevation: WidgetStatePropertyAll(10.0))\n'
'clipBehavior: Clip.none'),
);
});
testWidgets('keyboard tab traversal works', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
const Expanded(child: Placeholder()),
],
),
),
),
);
listenForFocusChanges();
// Have to open a menu initially to start things going.
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pumpAndSettle();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 0"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 1"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 2"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 0"))'));
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 2"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 1"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 0"))'));
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
opened.clear();
closed.clear();
// Test closing a menu with enter.
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(opened, isEmpty);
expect(closed, <TestMenu>[TestMenu.mainMenu0]);
});
testWidgets('keyboard directional traversal works', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
);
listenForFocusChanges();
// Have to open a menu initially to start things going.
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 1"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 10"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('SubmenuButton(Text("Sub Menu 11"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 12"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 12"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Sub Menu 11"))'));
// Open the next submenu
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 110"))'));
// Go back, close the submenu.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Sub Menu 11"))'));
// Move up, should close the submenu.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 10"))'));
// Move down, should reopen the submenu.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Sub Menu 11"))'));
// Open the next submenu again.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 110"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 111"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 112"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 113"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 113"))'));
});
testWidgets('keyboard directional traversal works in RTL mode', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
),
);
listenForFocusChanges();
// Have to open a menu initially to start things going.
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
expect(focusedMenu, equals('SubmenuButton(Text("Menu 1"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 1"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 10"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('SubmenuButton(Text("Sub Menu 11"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 12"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 12"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Sub Menu 11"))'));
// Open the next submenu
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pump();
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 110"))'));
// Go back, close the submenu.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Sub Menu 11"))'));
// Move up, should close the submenu.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 10"))'));
// Move down, should reopen the submenu.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Sub Menu 11"))'));
// Open the next submenu again.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pump();
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 110"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 111"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 112"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 113"))'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 113"))'));
});
testWidgets('hover traversal works', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
);
listenForFocusChanges();
// Hovering when the menu is not yet open does nothing.
await hoverOver(tester, find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(focusedMenu, isNull);
// Have to open a menu initially to start things going.
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 0"))'));
// Hovering when the menu is already open does nothing.
await hoverOver(tester, find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 0"))'));
// Hovering over the other main menu items opens them now.
await hoverOver(tester, find.text(TestMenu.mainMenu2.label));
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 2"))'));
await hoverOver(tester, find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Menu 1"))'));
// Hovering over the menu items focuses them.
await hoverOver(tester, find.text(TestMenu.subMenu10.label));
await tester.pump();
expect(focusedMenu, equals('MenuItemButton(Text("Sub Menu 10"))'));
await hoverOver(tester, find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(focusedMenu, equals('SubmenuButton(Text("Sub Menu 11"))'));
await hoverOver(tester, find.text(TestMenu.subSubMenu110.label));
await tester.pump();
expect(focusedMenu, equals('MenuItemButton(Text("Sub Sub Menu 110"))'));
});
testWidgets('menus close on ancestor scroll', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: SingleChildScrollView(
controller: scrollController,
child: Container(
height: 1000,
alignment: Alignment.center,
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
),
),
);
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(opened, isNotEmpty);
expect(closed, isEmpty);
opened.clear();
scrollController.jumpTo(1000);
await tester.pump();
expect(opened, isEmpty);
expect(closed, isNotEmpty);
});
testWidgets('menus do not close on root menu internal scroll', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/122168.
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
bool rootOpened = false;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
menuButtonTheme: MenuButtonThemeData(
// Increase menu items height to make root menu scrollable.
style: TextButton.styleFrom(minimumSize: const Size.fromHeight(200)),
),
),
home: Material(
child: SingleChildScrollView(
controller: scrollController,
child: Container(
height: 1000,
alignment: Alignment.topLeft,
child: MenuAnchor(
controller: controller,
alignmentOffset: const Offset(0, 10),
builder: (BuildContext context, MenuController controller, Widget? child) {
return FilledButton.tonal(
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
child: const Text('Show menu'),
);
},
onOpen: () {
rootOpened = true;
},
onClose: () {
rootOpened = false;
},
menuChildren: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
includeExtraGroups: true,
),
),
),
),
),
),
);
await tester.tap(find.text('Show menu'));
await tester.pump();
expect(rootOpened, true);
// Hover the first item.
final TestPointer pointer = TestPointer(1, PointerDeviceKind.mouse);
await tester.sendEventToBinding(pointer.hover(tester.getCenter(find.text(TestMenu.mainMenu0.label))));
await tester.pump();
expect(opened, isNotEmpty);
// Menus do not close on internal scroll.
await tester.sendEventToBinding(pointer.scroll(const Offset(0.0, 30.0)));
await tester.pump();
expect(rootOpened, true);
expect(closed, isEmpty);
// Menus close on external scroll.
scrollController.jumpTo(1000);
await tester.pump();
expect(rootOpened, false);
expect(closed, isNotEmpty);
});
testWidgets('menus close on view size change', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
final MediaQueryData mediaQueryData = MediaQueryData.fromView(tester.view);
Widget build(Size size) {
return MaterialApp(
home: Material(
child: MediaQuery(
data: mediaQueryData.copyWith(size: size),
child: SingleChildScrollView(
controller: scrollController,
child: Container(
height: 1000,
alignment: Alignment.center,
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
),
),
);
}
await tester.pumpWidget(build(mediaQueryData.size));
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(opened, isNotEmpty);
expect(closed, isEmpty);
opened.clear();
const Size smallSize = Size(200, 200);
await changeSurfaceSize(tester, smallSize);
await tester.pumpWidget(build(smallSize));
await tester.pump();
expect(opened, isEmpty);
expect(closed, isNotEmpty);
});
});
group('Accelerators', () {
const Set<TargetPlatform> apple = <TargetPlatform>{TargetPlatform.macOS, TargetPlatform.iOS};
final Set<TargetPlatform> nonApple = TargetPlatform.values.toSet().difference(apple);
test('Accelerator markers are stripped properly', () {
const Map<String, String> expected = <String, String>{
'Plain String': 'Plain String',
'&Simple Accelerator': 'Simple Accelerator',
'&Multiple &Accelerators': 'Multiple Accelerators',
'Whitespace & Accelerators': 'Whitespace Accelerators',
'&Quoted && Ampersand': 'Quoted & Ampersand',
'Ampersand at End &': 'Ampersand at End ',
'&&Multiple Ampersands &&& &&&A &&&&B &&&&': '&Multiple Ampersands & &A &&B &&',
'Bohrium 𨨏 Code point U+28A0F': 'Bohrium 𨨏 Code point U+28A0F',
};
const List<int> expectedIndices = <int>[-1, 0, 0, -1, 0, -1, 24, -1];
const List<bool> expectedHasAccelerator = <bool>[false, true, true, false, true, false, true, false];
int acceleratorIndex = -1;
int count = 0;
for (final String key in expected.keys) {
expect(
MenuAcceleratorLabel.stripAcceleratorMarkers(key, setIndex: (int index) {
acceleratorIndex = index;
}),
equals(expected[key]),
reason: "'$key' label doesn't match ${expected[key]}",
);
expect(
acceleratorIndex,
equals(expectedIndices[count]),
reason: "'$key' index doesn't match ${expectedIndices[count]}",
);
expect(
MenuAcceleratorLabel(key).hasAccelerator,
equals(expectedHasAccelerator[count]),
reason: "'$key' hasAccelerator isn't ${expectedHasAccelerator[count]}",
);
count += 1;
}
});
testWidgets('can invoke menu items', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
key: UniqueKey(),
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
accelerators: true,
),
),
),
),
);
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: 'm');
await tester.pump();
// Makes sure that identical accelerators in parent menu items don't
// shadow the ones in the children.
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: 'm');
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.mainMenu0]));
expect(closed, equals(<TestMenu>[TestMenu.mainMenu0]));
expect(selected, equals(<TestMenu>[TestMenu.subMenu00]));
// Selecting a non-submenu item should close all the menus.
expect(find.text(TestMenu.subMenu00.label), findsNothing);
opened.clear();
closed.clear();
selected.clear();
// Invoking several levels deep.
await tester.sendKeyDownEvent(LogicalKeyboardKey.altRight);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: 'e');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: '1');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: '1');
await tester.sendKeyUpEvent(LogicalKeyboardKey.altRight);
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.mainMenu1, TestMenu.subMenu11]));
expect(closed, equals(<TestMenu>[TestMenu.subMenu11, TestMenu.mainMenu1]));
expect(selected, equals(<TestMenu>[TestMenu.subSubMenu111]));
opened.clear();
closed.clear();
selected.clear();
}, variant: TargetPlatformVariant(nonApple));
testWidgets('can combine with regular keyboard navigation', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
key: UniqueKey(),
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
accelerators: true,
),
),
),
),
);
// Combining accelerators and regular keyboard navigation works.
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: 'e');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: '1');
await tester.pump();
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.mainMenu1, TestMenu.subMenu11]));
expect(closed, equals(<TestMenu>[TestMenu.subMenu11, TestMenu.mainMenu1]));
expect(selected, equals(<TestMenu>[TestMenu.subSubMenu110]));
}, variant: TargetPlatformVariant(nonApple));
testWidgets('can combine with mouse', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
key: UniqueKey(),
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
accelerators: true,
),
),
),
),
);
// Combining accelerators and regular keyboard navigation works.
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: 'e');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: '1');
await tester.pump();
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
await tester.tap(find.text(TestMenu.subSubMenu112.label));
await tester.pump();
expect(opened, equals(<TestMenu>[TestMenu.mainMenu1, TestMenu.subMenu11]));
expect(closed, equals(<TestMenu>[TestMenu.subMenu11, TestMenu.mainMenu1]));
expect(selected, equals(<TestMenu>[TestMenu.subSubMenu112]));
}, variant: TargetPlatformVariant(nonApple));
testWidgets("disabled items don't respond to accelerators", (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
key: UniqueKey(),
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
accelerators: true,
),
),
),
),
);
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: '5');
await tester.pump();
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
expect(opened, isEmpty);
expect(closed, isEmpty);
expect(selected, isEmpty);
// Selecting a non-submenu item should close all the menus.
expect(find.text(TestMenu.subMenu00.label), findsNothing);
}, variant: TargetPlatformVariant(nonApple));
testWidgets("Apple platforms don't react to accelerators", (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
key: UniqueKey(),
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
accelerators: true,
),
),
),
),
);
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: 'm');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: 'm');
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
expect(opened, isEmpty);
expect(closed, isEmpty);
expect(selected, isEmpty);
// Or with the option key equivalents.
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: 'µ');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyM, character: 'µ');
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
expect(opened, isEmpty);
expect(closed, isEmpty);
expect(selected, isEmpty);
}, variant: const TargetPlatformVariant(apple));
});
group('MenuController', () {
testWidgets('Moving a controller to a new instance works', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
key: UniqueKey(),
controller: controller,
children: createTestMenus(),
),
),
),
);
// Open a menu initially.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
// Now pump a new menu with a different UniqueKey to dispose of the opened
// menu's node, but keep the existing controller.
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
key: UniqueKey(),
controller: controller,
children: createTestMenus(
includeExtraGroups: true,
),
),
),
),
);
await tester.pumpAndSettle();
});
testWidgets('closing via controller works', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
shortcuts: <TestMenu, MenuSerializableShortcut>{
TestMenu.subSubMenu110: const SingleActivator(
LogicalKeyboardKey.keyA,
control: true,
)
},
),
),
),
),
);
// Open a menu initially.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(opened, unorderedEquals(<TestMenu>[TestMenu.mainMenu1, TestMenu.subMenu11]));
opened.clear();
closed.clear();
// Close menus using the controller
controller.close();
await tester.pump();
// The menu should go away,
expect(closed, unorderedEquals(<TestMenu>[TestMenu.mainMenu1, TestMenu.subMenu11]));
expect(opened, isEmpty);
});
});
group('MenuItemButton', () {
testWidgets('Shortcut mnemonics are displayed', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
shortcuts: <TestMenu, MenuSerializableShortcut>{
TestMenu.subSubMenu110: const SingleActivator(LogicalKeyboardKey.keyA, control: true),
TestMenu.subSubMenu111: const SingleActivator(LogicalKeyboardKey.keyB, shift: true),
TestMenu.subSubMenu112: const SingleActivator(LogicalKeyboardKey.keyC, alt: true),
TestMenu.subSubMenu113: const SingleActivator(LogicalKeyboardKey.keyD, meta: true),
},
),
),
),
),
);
// Open a menu initially.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
Text mnemonic0;
Text mnemonic1;
Text mnemonic2;
Text mnemonic3;
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
mnemonic0 = tester.widget(findMnemonic(TestMenu.subSubMenu110.label));
expect(mnemonic0.data, equals('Ctrl+A'));
mnemonic1 = tester.widget(findMnemonic(TestMenu.subSubMenu111.label));
expect(mnemonic1.data, equals('Shift+B'));
mnemonic2 = tester.widget(findMnemonic(TestMenu.subSubMenu112.label));
expect(mnemonic2.data, equals('Alt+C'));
mnemonic3 = tester.widget(findMnemonic(TestMenu.subSubMenu113.label));
expect(mnemonic3.data, equals('Meta+D'));
case TargetPlatform.windows:
mnemonic0 = tester.widget(findMnemonic(TestMenu.subSubMenu110.label));
expect(mnemonic0.data, equals('Ctrl+A'));
mnemonic1 = tester.widget(findMnemonic(TestMenu.subSubMenu111.label));
expect(mnemonic1.data, equals('Shift+B'));
mnemonic2 = tester.widget(findMnemonic(TestMenu.subSubMenu112.label));
expect(mnemonic2.data, equals('Alt+C'));
mnemonic3 = tester.widget(findMnemonic(TestMenu.subSubMenu113.label));
expect(mnemonic3.data, equals('Win+D'));
case TargetPlatform.iOS:
case TargetPlatform.macOS:
mnemonic0 = tester.widget(findMnemonic(TestMenu.subSubMenu110.label));
expect(mnemonic0.data, equals('⌃ A'));
mnemonic1 = tester.widget(findMnemonic(TestMenu.subSubMenu111.label));
expect(mnemonic1.data, equals('⇧ B'));
mnemonic2 = tester.widget(findMnemonic(TestMenu.subSubMenu112.label));
expect(mnemonic2.data, equals('⌥ C'));
mnemonic3 = tester.widget(findMnemonic(TestMenu.subSubMenu113.label));
expect(mnemonic3.data, equals('⌘ D'));
}
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
includeExtraGroups: true,
shortcuts: <TestMenu, MenuSerializableShortcut>{
TestMenu.subSubMenu110: const SingleActivator(LogicalKeyboardKey.arrowRight),
TestMenu.subSubMenu111: const SingleActivator(LogicalKeyboardKey.arrowLeft),
TestMenu.subSubMenu112: const SingleActivator(LogicalKeyboardKey.arrowUp),
TestMenu.subSubMenu113: const SingleActivator(LogicalKeyboardKey.arrowDown),
},
),
),
),
),
);
await tester.pumpAndSettle();
mnemonic0 = tester.widget(findMnemonic(TestMenu.subSubMenu110.label));
expect(mnemonic0.data, equals('→'));
mnemonic1 = tester.widget(findMnemonic(TestMenu.subSubMenu111.label));
expect(mnemonic1.data, equals('←'));
mnemonic2 = tester.widget(findMnemonic(TestMenu.subSubMenu112.label));
expect(mnemonic2.data, equals('↑'));
mnemonic3 = tester.widget(findMnemonic(TestMenu.subSubMenu113.label));
expect(mnemonic3.data, equals('↓'));
// Try some weirder ones.
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
shortcuts: <TestMenu, MenuSerializableShortcut>{
TestMenu.subSubMenu110: const SingleActivator(LogicalKeyboardKey.escape),
TestMenu.subSubMenu111: const SingleActivator(LogicalKeyboardKey.fn),
TestMenu.subSubMenu112: const SingleActivator(LogicalKeyboardKey.enter),
},
),
),
),
),
);
await tester.pumpAndSettle();
mnemonic0 = tester.widget(findMnemonic(TestMenu.subSubMenu110.label));
expect(mnemonic0.data, equals('Esc'));
mnemonic1 = tester.widget(findMnemonic(TestMenu.subSubMenu111.label));
expect(mnemonic1.data, equals('Fn'));
mnemonic2 = tester.widget(findMnemonic(TestMenu.subSubMenu112.label));
expect(mnemonic2.data, equals('↵'));
}, variant: TargetPlatformVariant.all());
testWidgets('leadingIcon is used when set', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
leadingIcon: const Text('leadingIcon'),
child: Text(TestMenu.subMenu00.label),
),
],
child: Text(TestMenu.mainMenu0.label),
),
],
),
),
),
);
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(find.text('leadingIcon'), findsOneWidget);
});
testWidgets('trailingIcon is used when set', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
trailingIcon: const Text('trailingIcon'),
child: Text(TestMenu.subMenu00.label),
),
],
child: Text(TestMenu.mainMenu0.label),
),
],
),
),
),
);
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(find.text('trailingIcon'), findsOneWidget);
});
testWidgets('SubmenuButton uses supplied controller', (WidgetTester tester) async {
final MenuController submenuController = MenuController();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: <Widget>[
SubmenuButton(
controller: submenuController,
menuChildren: <Widget>[
MenuItemButton(
child: Text(TestMenu.subMenu00.label),
),
],
child: Text(TestMenu.mainMenu0.label),
),
],
),
),
),
);
submenuController.open();
await tester.pump();
expect(find.text(TestMenu.subMenu00.label), findsOneWidget);
submenuController.close();
await tester.pump();
expect(find.text(TestMenu.subMenu00.label), findsNothing);
// Now remove the controller and try to control it.
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
child: Text(TestMenu.subMenu00.label),
),
],
child: Text(TestMenu.mainMenu0.label),
),
],
),
),
),
);
await expectLater(() => submenuController.open(), throwsAssertionError);
await tester.pump();
expect(find.text(TestMenu.subMenu00.label), findsNothing);
});
testWidgets('diagnostics', (WidgetTester tester) async {
final ButtonStyle style = ButtonStyle(
shape: MaterialStateProperty.all<OutlinedBorder?>(const StadiumBorder()),
elevation: MaterialStateProperty.all<double?>(10.0),
backgroundColor: const MaterialStatePropertyAll<Color>(Colors.red),
);
final MenuStyle menuStyle = MenuStyle(
shape: MaterialStateProperty.all<OutlinedBorder?>(const RoundedRectangleBorder()),
elevation: MaterialStateProperty.all<double?>(20.0),
backgroundColor: const MaterialStatePropertyAll<Color>(Colors.green),
);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: <Widget>[
SubmenuButton(
style: style,
menuStyle: menuStyle,
menuChildren: <Widget>[
MenuItemButton(
style: style,
child: Text(TestMenu.subMenu00.label),
),
],
child: Text(TestMenu.mainMenu0.label),
),
],
),
),
),
);
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
final SubmenuButton submenu = tester.widget(find.byType(SubmenuButton));
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
submenu.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(
description,
equalsIgnoringHashCodes(
<String>[
'focusNode: null',
'menuStyle: MenuStyle#00000(backgroundColor: WidgetStatePropertyAll(MaterialColor(primary value: Color(0xff4caf50))), elevation: WidgetStatePropertyAll(20.0), shape: WidgetStatePropertyAll(RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.zero)))',
'alignmentOffset: null',
'clipBehavior: hardEdge',
],
),
);
});
testWidgets('MenuItemButton respects closeOnActivate property', (WidgetTester tester) async {
final MenuController controller = MenuController();
await tester.pumpWidget(MaterialApp(
home: Material(
child: Center(
child: MenuAnchor(
controller: controller,
menuChildren: <Widget>[
MenuItemButton(
onPressed: () {},
child: const Text('Button 1'),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return FilledButton(
onPressed: () {
controller.open();
},
child: const Text('Tap me'),
);
},
),
),
),
));
await tester.tap(find.text('Tap me'));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(1));
// Taps the MenuItemButton which should close the menu
await tester.tap(find.text('Button 1'));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(0));
await tester.pumpAndSettle();
await tester.pumpWidget(MaterialApp(
home: Material(
child: Center(
child: MenuAnchor(
controller: controller,
menuChildren: <Widget>[
MenuItemButton(
closeOnActivate: false,
onPressed: () {},
child: const Text('Button 1'),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return FilledButton(
onPressed: () {
controller.open();
},
child: const Text('Tap me'),
);
},
),
),
),
));
await tester.tap(find.text('Tap me'));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(1));
// Taps the MenuItemButton which shouldn't close the menu
await tester.tap(find.text('Button 1'));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(1));
});
});
group('Layout', () {
List<Rect> collectMenuItemRects() {
final List<Rect> menuRects = <Rect>[];
final List<Element> candidates = find.byType(SubmenuButton).evaluate().toList();
for (final Element candidate in candidates) {
final RenderBox box = candidate.renderObject! as RenderBox;
final Offset topLeft = box.localToGlobal(box.size.topLeft(Offset.zero));
final Offset bottomRight = box.localToGlobal(box.size.bottomRight(Offset.zero));
menuRects.add(Rect.fromPoints(topLeft, bottomRight));
}
return menuRects;
}
List<Rect> collectSubmenuRects() {
final List<Rect> menuRects = <Rect>[];
final List<Element> candidates = findMenuPanels().evaluate().toList();
for (final Element candidate in candidates) {
final RenderBox box = candidate.renderObject! as RenderBox;
final Offset topLeft = box.localToGlobal(box.size.topLeft(Offset.zero));
final Offset bottomRight = box.localToGlobal(box.size.bottomRight(Offset.zero));
menuRects.add(Rect.fromPoints(topLeft, bottomRight));
}
return menuRects;
}
testWidgets('unconstrained menus show up in the right place in LTR', (WidgetTester tester) async {
await changeSurfaceSize(tester, const Size(800, 600));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: MenuBar(
children: createTestMenus(onPressed: onPressed),
),
),
],
),
const Expanded(child: Placeholder()),
],
),
),
),
);
await tester.pump();
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(6));
expect(find.byType(SubmenuButton), findsNWidgets(5));
expect(
collectMenuItemRects(),
equals(const <Rect>[
Rect.fromLTRB(4.0, 0.0, 112.0, 48.0),
Rect.fromLTRB(112.0, 0.0, 220.0, 48.0),
Rect.fromLTRB(112.0, 104.0, 326.0, 152.0),
Rect.fromLTRB(220.0, 0.0, 328.0, 48.0),
Rect.fromLTRB(328.0, 0.0, 506.0, 48.0)
]),
);
});
testWidgets('unconstrained menus show up in the right place in RTL', (WidgetTester tester) async {
await changeSurfaceSize(tester, const Size(800, 600));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: MenuBar(
children: createTestMenus(onPressed: onPressed),
),
),
],
),
const Expanded(child: Placeholder()),
],
),
),
),
),
);
await tester.pump();
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(6));
expect(find.byType(SubmenuButton), findsNWidgets(5));
expect(
collectMenuItemRects(),
equals(const <Rect>[
Rect.fromLTRB(688.0, 0.0, 796.0, 48.0),
Rect.fromLTRB(580.0, 0.0, 688.0, 48.0),
Rect.fromLTRB(474.0, 104.0, 688.0, 152.0),
Rect.fromLTRB(472.0, 0.0, 580.0, 48.0),
Rect.fromLTRB(294.0, 0.0, 472.0, 48.0)
]),
);
});
testWidgets('constrained menus show up in the right place in LTR', (WidgetTester tester) async {
await changeSurfaceSize(tester, const Size(300, 300));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Column(
children: <Widget>[
MenuBar(
children: createTestMenus(onPressed: onPressed),
),
const Expanded(child: Placeholder()),
],
),
),
);
},
),
),
);
await tester.pump();
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(6));
expect(find.byType(SubmenuButton), findsNWidgets(5));
expect(
collectMenuItemRects(),
equals(const <Rect>[
Rect.fromLTRB(4.0, 0.0, 112.0, 48.0),
Rect.fromLTRB(112.0, 0.0, 220.0, 48.0),
Rect.fromLTRB(86.0, 104.0, 300.0, 152.0),
Rect.fromLTRB(220.0, 0.0, 328.0, 48.0),
Rect.fromLTRB(328.0, 0.0, 506.0, 48.0)
]),
);
});
testWidgets('tapping MenuItemButton with null focus node', (WidgetTester tester) async {
FocusNode? buttonFocusNode = FocusNode();
// Build our app and trigger a frame.
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MenuAnchor(
menuChildren: <Widget>[
MenuItemButton(
focusNode: buttonFocusNode,
closeOnActivate: false,
child: const Text('Set focus to null'),
onPressed: () {
setState((){
buttonFocusNode?.dispose();
buttonFocusNode = null;
});
},
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return TextButton(
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
child: const Text('OPEN MENU'),
);
},
);
}
),
),
);
await tester.tap(find.text('OPEN MENU'));
await tester.pump();
expect(find.text('Set focus to null'), findsOneWidget);
await tester.tap(find.text('Set focus to null'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
});
testWidgets('constrained menus show up in the right place in RTL', (WidgetTester tester) async {
await changeSurfaceSize(tester, const Size(300, 300));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Material(
child: Column(
children: <Widget>[
MenuBar(
children: createTestMenus(onPressed: onPressed),
),
const Expanded(child: Placeholder()),
],
),
),
);
},
),
),
);
await tester.pump();
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(6));
expect(find.byType(SubmenuButton), findsNWidgets(5));
expect(
collectMenuItemRects(),
equals(const <Rect>[
Rect.fromLTRB(188.0, 0.0, 296.0, 48.0),
Rect.fromLTRB(80.0, 0.0, 188.0, 48.0),
Rect.fromLTRB(0.0, 104.0, 214.0, 152.0),
Rect.fromLTRB(-28.0, 0.0, 80.0, 48.0),
Rect.fromLTRB(-206.0, 0.0, -28.0, 48.0)
]),
);
});
testWidgets('constrained menus show up in the right place with offset in LTR', (WidgetTester tester) async {
await changeSurfaceSize(tester, const Size(800, 600));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: MenuAnchor(
menuChildren: const <Widget>[
SubmenuButton(
alignmentOffset: Offset(10, 0),
menuChildren: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
SubmenuButton(
alignmentOffset: Offset(10, 0),
menuChildren: <Widget>[
SubmenuButton(
menuChildren: <Widget>[],
child: Text('SubMenuButton4'),
),
],
child: Text('SubMenuButton3'),
),
],
child: Text('SubMenuButton2'),
),
],
child: Text('SubMenuButton1'),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return FilledButton(
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
child: const Text('Tap me'),
);
},
),
),
);
},
),
),
);
await tester.pump();
await tester.tap(find.text('Tap me'));
await tester.pump();
await tester.tap(find.text('SubMenuButton1'));
await tester.pump();
await tester.tap(find.text('SubMenuButton2'));
await tester.pump();
await tester.tap(find.text('SubMenuButton3'));
await tester.pump();
expect(find.byType(SubmenuButton), findsNWidgets(4));
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(0.0, 48.0, 256.0, 112.0),
Rect.fromLTRB(266.0, 48.0, 522.0, 112.0),
Rect.fromLTRB(522.0, 48.0, 778.0, 112.0),
Rect.fromLTRB(256.0, 48.0, 512.0, 112.0),
]),
);
});
testWidgets('constrained menus show up in the right place with offset in RTL', (WidgetTester tester) async {
await changeSurfaceSize(tester, const Size(800, 600));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Align(
alignment: Alignment.topRight,
child: MenuAnchor(
menuChildren: const <Widget>[
SubmenuButton(
alignmentOffset: Offset(10, 0),
menuChildren: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
SubmenuButton(
alignmentOffset: Offset(10, 0),
menuChildren: <Widget>[
SubmenuButton(
menuChildren: <Widget>[],
child: Text('SubMenuButton4'),
),
],
child: Text('SubMenuButton3'),
),
],
child: Text('SubMenuButton2'),
),
],
child: Text('SubMenuButton1'),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return FilledButton(
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
child: const Text('Tap me'),
);
},
),
),
);
},
),
),
);
await tester.pump();
await tester.tap(find.text('Tap me'));
await tester.pump();
await tester.tap(find.text('SubMenuButton1'));
await tester.pump();
await tester.tap(find.text('SubMenuButton2'));
await tester.pump();
await tester.tap(find.text('SubMenuButton3'));
await tester.pump();
expect(find.byType(SubmenuButton), findsNWidgets(4));
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(544.0, 48.0, 800.0, 112.0),
Rect.fromLTRB(278.0, 48.0, 534.0, 112.0),
Rect.fromLTRB(22.0, 48.0, 278.0, 112.0),
Rect.fromLTRB(288.0, 48.0, 544.0, 112.0),
]),
);
});
testWidgets('vertically constrained menus are positioned above the anchor by default', (WidgetTester tester) async {
await changeSurfaceSize(tester, const Size(800, 600));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.bottomLeft,
child: MenuAnchor(
menuChildren: const <Widget>[
MenuItemButton(
child: Text('Button1'),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return FilledButton(
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
child: const Text('Tap me'),
);
},
),
),
);
},
),
),
);
await tester.pump();
await tester.tap(find.text('Tap me'));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(1));
// Test the default offset (0, 0) vertical position.
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(0.0, 488.0, 122.0, 552.0),
]),
);
});
testWidgets('vertically constrained menus are positioned above the anchor with the provided offset',
(WidgetTester tester) async {
await changeSurfaceSize(tester, const Size(800, 600));
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Builder(
builder: (BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.bottomLeft,
child: MenuAnchor(
alignmentOffset: const Offset(0, 50),
menuChildren: const <Widget>[
MenuItemButton(
child: Text('Button1'),
),
],
builder: (BuildContext context, MenuController controller, Widget? child) {
return FilledButton(
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
child: const Text('Tap me'),
);
},
),
),
);
},
),
),
);
await tester.pump();
await tester.tap(find.text('Tap me'));
await tester.pump();
expect(find.byType(MenuItemButton), findsNWidgets(1));
// Test the offset (0, 50) vertical position.
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(0.0, 438.0, 122.0, 502.0),
]),
);
});
Future<void> buildDensityPaddingApp(
WidgetTester tester, {
required TextDirection textDirection,
VisualDensity visualDensity = VisualDensity.standard,
EdgeInsetsGeometry? menuPadding,
}) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.light(useMaterial3: false).copyWith(visualDensity: visualDensity),
home: Directionality(
textDirection: textDirection,
child: Material(
child: Column(
children: <Widget>[
MenuBar(
style: menuPadding != null
? MenuStyle(padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(menuPadding))
: null,
children: createTestMenus(onPressed: onPressed),
),
const Expanded(child: Placeholder()),
],
),
),
),
),
);
await tester.pump();
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
await tester.tap(find.text(TestMenu.subMenu11.label));
await tester.pump();
}
testWidgets('submenus account for density in LTR', (WidgetTester tester) async {
await buildDensityPaddingApp(
tester,
textDirection: TextDirection.ltr,
);
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(145.0, 0.0, 655.0, 48.0),
Rect.fromLTRB(257.0, 48.0, 471.0, 208.0),
Rect.fromLTRB(471.0, 96.0, 719.0, 304.0),
]),
);
});
testWidgets('submenus account for menu density in RTL', (WidgetTester tester) async {
await buildDensityPaddingApp(
tester,
textDirection: TextDirection.rtl,
);
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(145.0, 0.0, 655.0, 48.0),
Rect.fromLTRB(329.0, 48.0, 543.0, 208.0),
Rect.fromLTRB(81.0, 96.0, 329.0, 304.0),
]),
);
});
testWidgets('submenus account for compact menu density in LTR', (WidgetTester tester) async {
await buildDensityPaddingApp(
tester,
visualDensity: VisualDensity.compact,
textDirection: TextDirection.ltr,
);
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(161.0, 0.0, 639.0, 40.0),
Rect.fromLTRB(265.0, 40.0, 467.0, 160.0),
Rect.fromLTRB(467.0, 72.0, 707.0, 232.0),
]),
);
});
testWidgets('submenus account for compact menu density in RTL', (WidgetTester tester) async {
await buildDensityPaddingApp(
tester,
visualDensity: VisualDensity.compact,
textDirection: TextDirection.rtl,
);
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(161.0, 0.0, 639.0, 40.0),
Rect.fromLTRB(333.0, 40.0, 535.0, 160.0),
Rect.fromLTRB(93.0, 72.0, 333.0, 232.0),
]),
);
});
testWidgets('submenus account for padding in LTR', (WidgetTester tester) async {
await buildDensityPaddingApp(
tester,
menuPadding: const EdgeInsetsDirectional.only(start: 10, end: 11, top: 12, bottom: 13),
textDirection: TextDirection.ltr,
);
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(138.5, 0.0, 661.5, 73.0),
Rect.fromLTRB(256.5, 60.0, 470.5, 220.0),
Rect.fromLTRB(470.5, 108.0, 718.5, 316.0),
]),
);
});
testWidgets('submenus account for padding in RTL', (WidgetTester tester) async {
await buildDensityPaddingApp(
tester,
menuPadding: const EdgeInsetsDirectional.only(start: 10, end: 11, top: 12, bottom: 13),
textDirection: TextDirection.rtl,
);
expect(
collectSubmenuRects(),
equals(const <Rect>[
Rect.fromLTRB(138.5, 0.0, 661.5, 73.0),
Rect.fromLTRB(329.5, 60.0, 543.5, 220.0),
Rect.fromLTRB(81.5, 108.0, 329.5, 316.0),
]),
);
});
});
group('LocalizedShortcutLabeler', () {
testWidgets('getShortcutLabel returns the right labels', (WidgetTester tester) async {
String expectedMeta;
String expectedCtrl;
String expectedAlt;
String expectedSeparator;
String expectedShift;
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expectedCtrl = 'Ctrl';
expectedMeta = defaultTargetPlatform == TargetPlatform.windows ? 'Win' : 'Meta';
expectedAlt = 'Alt';
expectedShift = 'Shift';
expectedSeparator = '+';
case TargetPlatform.iOS:
case TargetPlatform.macOS:
expectedCtrl = '⌃';
expectedMeta = '⌘';
expectedAlt = '⌥';
expectedShift = '⇧';
expectedSeparator = ' ';
}
const SingleActivator allModifiers = SingleActivator(
LogicalKeyboardKey.keyA,
control: true,
meta: true,
shift: true,
alt: true,
);
late String allExpected;
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
allExpected = <String>[expectedAlt, expectedCtrl, expectedMeta, expectedShift, 'A'].join(expectedSeparator);
case TargetPlatform.iOS:
case TargetPlatform.macOS:
allExpected = <String>[expectedCtrl, expectedAlt, expectedShift, expectedMeta, 'A'].join(expectedSeparator);
}
const CharacterActivator charShortcuts = CharacterActivator('ñ');
const String charExpected = 'ñ';
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MenuBar(
controller: controller,
children: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
shortcut: allModifiers,
child: Text(TestMenu.subMenu10.label),
),
MenuItemButton(
shortcut: charShortcuts,
child: Text(TestMenu.subMenu11.label),
),
],
child: Text(TestMenu.mainMenu0.label),
),
],
),
),
),
);
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
expect(find.text(allExpected), findsOneWidget);
expect(find.text(charExpected), findsOneWidget);
}, variant: TargetPlatformVariant.all());
});
group('CheckboxMenuButton', () {
testWidgets('tapping toggles checkbox', (WidgetTester tester) async {
bool? checkBoxValue;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MenuBar(
children: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
CheckboxMenuButton(
value: checkBoxValue,
onChanged: (bool? value) {
setState(() {
checkBoxValue = value;
});
},
tristate: true,
child: const Text('checkbox'),
)
],
child: const Text('submenu'),
),
],
);
},
),
),
);
await tester.tap(find.byType(SubmenuButton));
await tester.pump();
expect(tester.widget<CheckboxMenuButton>(find.byType(CheckboxMenuButton)).value, null);
await tester.tap(find.byType(CheckboxMenuButton));
await tester.pumpAndSettle();
expect(checkBoxValue, false);
await tester.tap(find.byType(SubmenuButton));
await tester.pump();
await tester.tap(find.byType(CheckboxMenuButton));
await tester.pumpAndSettle();
expect(checkBoxValue, true);
await tester.tap(find.byType(SubmenuButton));
await tester.pump();
await tester.tap(find.byType(CheckboxMenuButton));
await tester.pumpAndSettle();
expect(checkBoxValue, null);
});
});
group('RadioMenuButton', () {
testWidgets('tapping toggles radio button', (WidgetTester tester) async {
int? radioValue;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MenuBar(
children: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
RadioMenuButton<int>(
value: 0,
groupValue: radioValue,
onChanged: (int? value) {
setState(() {
radioValue = value;
});
},
toggleable: true,
child: const Text('radio 0'),
),
RadioMenuButton<int>(
value: 1,
groupValue: radioValue,
onChanged: (int? value) {
setState(() {
radioValue = value;
});
},
toggleable: true,
child: const Text('radio 1'),
)
],
child: const Text('submenu'),
),
],
);
},
),
),
);
await tester.tap(find.byType(SubmenuButton));
await tester.pump();
expect(
tester.widget<RadioMenuButton<int>>(find.byType(RadioMenuButton<int>).first).groupValue,
null,
);
await tester.tap(find.byType(RadioMenuButton<int>).first);
await tester.pumpAndSettle();
expect(radioValue, 0);
await tester.tap(find.byType(SubmenuButton));
await tester.pump();
await tester.tap(find.byType(RadioMenuButton<int>).first);
await tester.pumpAndSettle();
expect(radioValue, null);
await tester.tap(find.byType(SubmenuButton));
await tester.pump();
await tester.tap(find.byType(RadioMenuButton<int>).last);
await tester.pumpAndSettle();
expect(radioValue, 1);
});
});
group('Semantics', () {
testWidgets('MenuItemButton is not a semantic button', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: MenuItemButton(
style: MenuItemButton.styleFrom(fixedSize: const Size(88.0, 36.0)),
onPressed: () {},
child: const Text('ABC'),
),
),
),
);
// The flags should not have SemanticsFlag.isButton
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.isEnabled,
SemanticsFlag.isFocusable,
],
textDirection: TextDirection.ltr,
),
],
),
ignoreId: true,
),
);
semantics.dispose();
});
testWidgets('SubMenuButton is not a semantic button', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SubmenuButton(
onHover: (bool value) {},
style: SubmenuButton.styleFrom(fixedSize: const Size(88.0, 36.0)),
menuChildren: const <Widget>[],
child: const Text('ABC'),
),
),
),
);
// The flags should not have SemanticsFlag.isButton
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0),
flags: <SemanticsFlag>[SemanticsFlag.hasEnabledState, SemanticsFlag.hasExpandedState],
label: 'ABC',
textDirection: TextDirection.ltr,
),
],
),
ignoreTransform: true,
ignoreId: true,
),
);
semantics.dispose();
});
testWidgets('SubmenuButton expanded/collapsed state', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
MaterialApp(
home: Center(
child: SubmenuButton(
style: SubmenuButton.styleFrom(fixedSize: const Size(88.0, 36.0)),
menuChildren: <Widget>[
MenuItemButton(
style: MenuItemButton.styleFrom(fixedSize: const Size(120.0, 36.0)),
child: const Text('Item 0'),
onPressed: () {},
),
],
child: const Text('ABC'),
),
),
),
);
// Test expanded state.
await tester.tap(find.text('ABC'));
await tester.pumpAndSettle();
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
id: 1,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
children: <TestSemantics>[
TestSemantics(
id: 2,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
children: <TestSemantics>[
TestSemantics(
id: 3,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
id: 4,
flags: <SemanticsFlag>[
SemanticsFlag.isFocused,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
SemanticsFlag.hasExpandedState,
SemanticsFlag.isExpanded,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'ABC',
rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0),
),
TestSemantics(
id: 6,
rect: const Rect.fromLTRB(0.0, 0.0, 120.0, 64.0),
children: <TestSemantics>[
TestSemantics(
id: 7,
rect: const Rect.fromLTRB(0.0, 0.0, 120.0, 48.0),
flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling],
children: <TestSemantics>[
TestSemantics(
id: 8,
label: 'Item 0',
rect: const Rect.fromLTRB(0.0, 0.0, 120.0, 48.0),
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
),
],
),
],
),
],
),
],
),
],
),
],
),
ignoreTransform: true,
),
);
// Test collapsed state.
await tester.tap(find.text('ABC'));
await tester.pumpAndSettle();
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
id: 1,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
children: <TestSemantics>[
TestSemantics(
id: 2,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
children: <TestSemantics>[
TestSemantics(
id: 3,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
id: 4,
flags: <SemanticsFlag>[
SemanticsFlag.hasExpandedState,
SemanticsFlag.isFocused,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'ABC',
rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0),
),
],
),
],
),
],
),
],
),
ignoreTransform: true,
),
);
semantics.dispose();
});
});
// This is a regression test for https://github.com/flutter/flutter/issues/131676.
testWidgets('Material3 - Menu uses correct text styles', (WidgetTester tester) async {
const TextStyle menuTextStyle = TextStyle(
fontSize: 18.5,
fontStyle: FontStyle.italic,
wordSpacing: 1.2,
decoration: TextDecoration.lineThrough,
);
final ThemeData themeData = ThemeData(
textTheme: const TextTheme(
labelLarge: menuTextStyle,
),
);
await tester.pumpWidget(
MaterialApp(
theme: themeData,
home: Material(
child: MenuBar(
controller: controller,
children: createTestMenus(
onPressed: onPressed,
onOpen: onOpen,
onClose: onClose,
),
),
),
),
);
// Test menu button text style uses the TextTheme.labelLarge.
Finder buttonMaterial = find
.descendant(
of: find.byType(TextButton),
matching: find.byType(Material),
)
.first;
Material material = tester.widget<Material>(buttonMaterial);
expect(material.textStyle?.fontSize, menuTextStyle.fontSize);
expect(material.textStyle?.fontStyle, menuTextStyle.fontStyle);
expect(material.textStyle?.wordSpacing, menuTextStyle.wordSpacing);
expect(material.textStyle?.decoration, menuTextStyle.decoration);
// Open the menu.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
// Test menu item text style uses the TextTheme.labelLarge.
buttonMaterial = find
.descendant(
of: find.widgetWithText(TextButton, TestMenu.subMenu10.label),
matching: find.byType(Material),
)
.first;
material = tester.widget<Material>(buttonMaterial);
expect(material.textStyle?.fontSize, menuTextStyle.fontSize);
expect(material.textStyle?.fontStyle, menuTextStyle.fontStyle);
expect(material.textStyle?.wordSpacing, menuTextStyle.wordSpacing);
expect(material.textStyle?.decoration, menuTextStyle.decoration);
});
testWidgets('SubmenuButton.onFocusChange is respected', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
int onFocusChangeCalled = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SubmenuButton(
focusNode: focusNode,
onFocusChange: (bool value) {
setState(() {
onFocusChangeCalled += 1;
});
},
menuChildren: const <Widget>[
MenuItemButton(child: Text('item 0'))
],
child: const Text('Submenu 0'),
);
}
),
),
),
);
focusNode.requestFocus();
await tester.pump();
expect(focusNode.hasFocus, true);
expect(onFocusChangeCalled, 1);
focusNode.unfocus();
await tester.pump();
expect(focusNode.hasFocus, false);
expect(onFocusChangeCalled, 2);
});
}
List<Widget> createTestMenus({
void Function(TestMenu)? onPressed,
void Function(TestMenu)? onOpen,
void Function(TestMenu)? onClose,
Map<TestMenu, MenuSerializableShortcut> shortcuts = const <TestMenu, MenuSerializableShortcut>{},
bool includeExtraGroups = false,
bool accelerators = false,
}) {
Widget submenuButton(
TestMenu menu, {
required List<Widget> menuChildren,
}) {
return SubmenuButton(
onOpen: onOpen != null ? () => onOpen(menu) : null,
onClose: onClose != null ? () => onClose(menu) : null,
menuChildren: menuChildren,
child: accelerators ? MenuAcceleratorLabel(menu.acceleratorLabel) : Text(menu.label),
);
}
Widget menuItemButton(
TestMenu menu, {
bool enabled = true,
Widget? leadingIcon,
Widget? trailingIcon,
Key? key,
}) {
return MenuItemButton(
key: key,
onPressed: enabled && onPressed != null ? () => onPressed(menu) : null,
shortcut: shortcuts[menu],
leadingIcon: leadingIcon,
trailingIcon: trailingIcon,
child: accelerators ? MenuAcceleratorLabel(menu.acceleratorLabel) : Text(menu.label),
);
}
final List<Widget> result = <Widget>[
submenuButton(
TestMenu.mainMenu0,
menuChildren: <Widget>[
menuItemButton(TestMenu.subMenu00, leadingIcon: const Icon(Icons.add)),
menuItemButton(TestMenu.subMenu01),
menuItemButton(TestMenu.subMenu02),
],
),
submenuButton(
TestMenu.mainMenu1,
menuChildren: <Widget>[
menuItemButton(TestMenu.subMenu10),
submenuButton(
TestMenu.subMenu11,
menuChildren: <Widget>[
menuItemButton(TestMenu.subSubMenu110, key: UniqueKey()),
menuItemButton(TestMenu.subSubMenu111),
menuItemButton(TestMenu.subSubMenu112),
menuItemButton(TestMenu.subSubMenu113),
],
),
menuItemButton(TestMenu.subMenu12),
],
),
submenuButton(
TestMenu.mainMenu2,
menuChildren: <Widget>[
menuItemButton(
TestMenu.subMenu20,
leadingIcon: const Icon(Icons.ac_unit),
enabled: false,
),
],
),
if (includeExtraGroups)
submenuButton(
TestMenu.mainMenu3,
menuChildren: <Widget>[
menuItemButton(TestMenu.subMenu30, enabled: false),
],
),
if (includeExtraGroups)
submenuButton(
TestMenu.mainMenu4,
menuChildren: <Widget>[
menuItemButton(TestMenu.subMenu40, enabled: false),
menuItemButton(TestMenu.subMenu41, enabled: false),
menuItemButton(TestMenu.subMenu42, enabled: false),
],
),
submenuButton(TestMenu.mainMenu5, menuChildren: const <Widget>[]),
];
return result;
}
enum TestMenu {
mainMenu0('&Menu 0'),
mainMenu1('M&enu &1'),
mainMenu2('Me&nu 2'),
mainMenu3('Men&u 3'),
mainMenu4('Menu &4'),
mainMenu5('Menu &5 && &6 &'),
subMenu00('Sub &Menu 0&0'),
subMenu01('Sub Menu 0&1'),
subMenu02('Sub Menu 0&2'),
subMenu10('Sub Menu 1&0'),
subMenu11('Sub Menu 1&1'),
subMenu12('Sub Menu 1&2'),
subMenu20('Sub Menu 2&0'),
subMenu30('Sub Menu 3&0'),
subMenu40('Sub Menu 4&0'),
subMenu41('Sub Menu 4&1'),
subMenu42('Sub Menu 4&2'),
subSubMenu110('Sub Sub Menu 11&0'),
subSubMenu111('Sub Sub Menu 11&1'),
subSubMenu112('Sub Sub Menu 11&2'),
subSubMenu113('Sub Sub Menu 11&3'),
anchorButton('Press Me'),
outsideButton('Outside');
const TestMenu(this.acceleratorLabel);
final String acceleratorLabel;
// Strip the accelerator markers.
String get label => MenuAcceleratorLabel.stripAcceleratorMarkers(acceleratorLabel);
}
| flutter/packages/flutter/test/material/menu_anchor_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/menu_anchor_test.dart",
"repo_id": "flutter",
"token_count": 64260
} | 674 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/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() {
testWidgets('Default PageTransitionsTheme platform', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Text('home')));
final PageTransitionsTheme theme = Theme.of(tester.element(find.text('home'))).pageTransitionsTheme;
expect(theme.builders, isNotNull);
for (final TargetPlatform platform in TargetPlatform.values) {
switch (platform) {
case TargetPlatform.android:
case TargetPlatform.iOS:
case TargetPlatform.macOS:
expect(
theme.builders[platform],
isNotNull,
reason: 'theme builder for $platform is null',
);
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(
theme.builders[platform],
isNull,
reason: 'theme builder for $platform is not null',
);
}
}
});
testWidgets('Default PageTransitionsTheme builds a CupertinoPageTransition', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => Material(
child: TextButton(
child: const Text('push'),
onPressed: () { Navigator.of(context).pushNamed('/b'); },
),
),
'/b': (BuildContext context) => const Text('page b'),
};
await tester.pumpWidget(
MaterialApp(
routes: routes,
),
);
expect(Theme.of(tester.element(find.text('push'))).platform, debugDefaultTargetPlatformOverride);
expect(find.byType(CupertinoPageTransition), findsOneWidget);
await tester.tap(find.text('push'));
await tester.pumpAndSettle();
expect(find.text('page b'), findsOneWidget);
expect(find.byType(CupertinoPageTransition), findsOneWidget);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Default PageTransitionsTheme builds a _ZoomPageTransition for android', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => Material(
child: TextButton(
child: const Text('push'),
onPressed: () { Navigator.of(context).pushNamed('/b'); },
),
),
'/b': (BuildContext context) => const Text('page b'),
};
await tester.pumpWidget(
MaterialApp(
routes: routes,
),
);
Finder findZoomPageTransition() {
return find.descendant(
of: find.byType(MaterialApp),
matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_ZoomPageTransition'),
);
}
expect(Theme.of(tester.element(find.text('push'))).platform, debugDefaultTargetPlatformOverride);
expect(findZoomPageTransition(), findsOneWidget);
await tester.tap(find.text('push'));
await tester.pumpAndSettle();
expect(find.text('page b'), findsOneWidget);
expect(findZoomPageTransition(), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
testWidgets('PageTransitionsTheme override builds a _OpenUpwardsPageTransition', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => Material(
child: TextButton(
child: const Text('push'),
onPressed: () { Navigator.of(context).pushNamed('/b'); },
),
),
'/b': (BuildContext context) => const Text('page b'),
};
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: OpenUpwardsPageTransitionsBuilder(), // creates a _OpenUpwardsPageTransition
},
),
),
routes: routes,
),
);
Finder findOpenUpwardsPageTransition() {
return find.descendant(
of: find.byType(MaterialApp),
matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_OpenUpwardsPageTransition'),
);
}
expect(Theme.of(tester.element(find.text('push'))).platform, debugDefaultTargetPlatformOverride);
expect(findOpenUpwardsPageTransition(), findsOneWidget);
await tester.tap(find.text('push'));
await tester.pumpAndSettle();
expect(find.text('page b'), findsOneWidget);
expect(findOpenUpwardsPageTransition(), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
testWidgets('PageTransitionsTheme override builds a CupertinoPageTransition on android', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => Material(
child: TextButton(
child: const Text('push'),
onPressed: () { Navigator.of(context).pushNamed('/b'); },
),
),
'/b': (BuildContext context) => const Text('page b'),
};
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: CupertinoPageTransitionsBuilder(),
},
),
),
routes: routes,
),
);
expect(Theme.of(tester.element(find.text('push'))).platform, debugDefaultTargetPlatformOverride);
expect(find.byType(CupertinoPageTransition), findsOneWidget);
await tester.tap(find.text('push'));
await tester.pumpAndSettle();
expect(find.text('page b'), findsOneWidget);
expect(find.byType(CupertinoPageTransition), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
testWidgets('CupertinoPageTransition on android does not block gestures on backswipe', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => Material(
child: TextButton(
child: const Text('push'),
onPressed: () { Navigator.of(context).pushNamed('/b'); },
),
),
'/b': (BuildContext context) => const Text('page b'),
};
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: CupertinoPageTransitionsBuilder(),
},
),
),
routes: routes,
),
);
expect(Theme.of(tester.element(find.text('push'))).platform, debugDefaultTargetPlatformOverride);
expect(find.byType(CupertinoPageTransition), findsOneWidget);
await tester.tap(find.text('push'));
await tester.pumpAndSettle();
expect(find.text('page b'), findsOneWidget);
expect(find.byType(CupertinoPageTransition), findsOneWidget);
await tester.pumpAndSettle(const Duration(minutes: 1));
final TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0));
await gesture.moveBy(const Offset(400.0, 0.0));
await gesture.up();
await tester.pump();
await tester.pumpAndSettle(const Duration(minutes: 1));
expect(find.text('push'), findsOneWidget);
await tester.tap(find.text('push'));
await tester.pumpAndSettle();
expect(find.text('page b'), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
testWidgets('PageTransitionsTheme override builds a _FadeUpwardsTransition', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => Material(
child: TextButton(
child: const Text('push'),
onPressed: () { Navigator.of(context).pushNamed('/b'); },
),
),
'/b': (BuildContext context) => const Text('page b'),
};
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), // creates a _FadeUpwardsTransition
},
),
),
routes: routes,
),
);
Finder findFadeUpwardsPageTransition() {
return find.descendant(
of: find.byType(MaterialApp),
matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_FadeUpwardsPageTransition'),
);
}
expect(Theme.of(tester.element(find.text('push'))).platform, debugDefaultTargetPlatformOverride);
expect(findFadeUpwardsPageTransition(), findsOneWidget);
await tester.tap(find.text('push'));
await tester.pumpAndSettle();
expect(find.text('page b'), findsOneWidget);
expect(findFadeUpwardsPageTransition(), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
Widget boilerplate({
required bool themeAllowSnapshotting,
bool secondRouteAllowSnapshotting = true,
}) {
return MaterialApp(
theme: ThemeData(
useMaterial3: true,
pageTransitionsTheme: PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: ZoomPageTransitionsBuilder(
allowSnapshotting: themeAllowSnapshotting,
),
},
),
),
onGenerateRoute: (RouteSettings settings) {
if (settings.name == '/') {
return MaterialPageRoute<Widget>(
builder: (_) => const Material(child: Text('Page 1')),
);
}
return MaterialPageRoute<Widget>(
builder: (_) => const Material(child: Text('Page 2')),
allowSnapshotting: secondRouteAllowSnapshotting,
);
},
);
}
bool isTransitioningWithSnapshotting(WidgetTester tester, Finder of) {
final Iterable<Layer> layers = tester.layerListOf(
find.ancestor(of: of, matching: find.byType(SnapshotWidget)).first,
);
final bool hasOneOpacityLayer = layers.whereType<OpacityLayer>().length == 1;
final bool hasOneTransformLayer = layers.whereType<TransformLayer>().length == 1;
// When snapshotting is on, the OpacityLayer and TransformLayer will not be
// applied directly.
return !(hasOneOpacityLayer && hasOneTransformLayer);
}
testWidgets('ZoomPageTransitionsBuilder default route snapshotting behavior', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(themeAllowSnapshotting: true),
);
final Finder page1 = find.text('Page 1');
final Finder page2 = find.text('Page 2');
// Transitioning from page 1 to page 2.
tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/2');
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Exiting route should be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page1), isTrue);
// Entering route should be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page2), isTrue);
await tester.pumpAndSettle();
// Transitioning back from page 2 to page 1.
tester.state<NavigatorState>(find.byType(Navigator)).pop();
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Exiting route should be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page2), isTrue);
// Entering route should be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page1), isTrue);
}, variant: TargetPlatformVariant.only(TargetPlatform.android), skip: kIsWeb); // [intended] rasterization is not used on the web.
testWidgets('ZoomPageTransitionsBuilder.allowSnapshotting can disable route snapshotting', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(themeAllowSnapshotting: false),
);
final Finder page1 = find.text('Page 1');
final Finder page2 = find.text('Page 2');
// Transitioning from page 1 to page 2.
tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/2');
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Exiting route should not be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page1), isFalse);
// Entering route should not be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page2), isFalse);
await tester.pumpAndSettle();
// Transitioning back from page 2 to page 1.
tester.state<NavigatorState>(find.byType(Navigator)).pop();
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// Exiting route should not be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page2), isFalse);
// Entering route should not be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page1), isFalse);
}, variant: TargetPlatformVariant.only(TargetPlatform.android), skip: kIsWeb); // [intended] rasterization is not used on the web.
testWidgets('Setting PageRoute.allowSnapshotting to false overrides ZoomPageTransitionsBuilder.allowSnapshotting = true', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
themeAllowSnapshotting: true,
secondRouteAllowSnapshotting: false,
),
);
final Finder page1 = find.text('Page 1');
final Finder page2 = find.text('Page 2');
// Transitioning from page 1 to page 2.
tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/2');
await tester.pump();
await tester.pump(const Duration(milliseconds: 50));
// First route should be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page1), isTrue);
// Second route should not be snapshotted.
expect(isTransitioningWithSnapshotting(tester, page2), isFalse);
await tester.pumpAndSettle();
}, variant: TargetPlatformVariant.only(TargetPlatform.android), skip: kIsWeb); // [intended] rasterization is not used on the web.
testWidgets('_ZoomPageTransition only causes child widget built once', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/58345
int builtCount = 0;
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => Material(
child: TextButton(
child: const Text('push'),
onPressed: () { Navigator.of(context).pushNamed('/b'); },
),
),
'/b': (BuildContext context) => StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
builtCount++; // Increase [builtCount] each time the widget build
return TextButton(
child: const Text('pop'),
onPressed: () { Navigator.pop(context); },
);
},
),
};
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: ZoomPageTransitionsBuilder(), // creates a _ZoomPageTransition
},
),
),
routes: routes,
),
);
// No matter push or pop was called, the child widget should built only once.
await tester.tap(find.text('push'));
await tester.pumpAndSettle();
expect(builtCount, 1);
await tester.tap(find.text('pop'));
await tester.pumpAndSettle();
expect(builtCount, 1);
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
}
| flutter/packages/flutter/test/material/page_transitions_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/page_transitions_theme_test.dart",
"repo_id": "flutter",
"token_count": 6021
} | 675 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(gspencergoog): Remove this tag once this test's state leaks/test
// dependencies have been fixed.
// https://github.com/flutter/flutter/issues/85160
// Fails with "flutter test --test-randomize-ordering-seed=20230313"
@Tags(<String>['no-shuffle'])
library;
import 'dart:ui' as ui;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_test/flutter_test.dart';
const Duration _kScrollbarFadeDuration = Duration(milliseconds: 300);
const Duration _kScrollbarTimeToFade = Duration(milliseconds: 600);
const Color _kAndroidThumbIdleColor = Color(0xffbcbcbc);
const Rect _kAndroidTrackDimensions = Rect.fromLTRB(796.0, 0.0, 800.0, 600.0);
const Radius _kDefaultThumbRadius = Radius.circular(8.0);
const Color _kDefaultIdleThumbColor = Color(0x1a000000);
const Offset _kTrackBorderPoint1 = Offset(796.0, 0.0);
const Offset _kTrackBorderPoint2 = Offset(796.0, 600.0);
Rect getStartingThumbRect({ required bool isAndroid }) {
return isAndroid
// On Android the thumb is slightly different. The thumb is only 4 pixels wide,
// and has no margin along the side of the viewport.
? const Rect.fromLTRB(796.0, 0.0, 800.0, 90.0)
// The Material Design thumb is 8 pixels wide, with a 2
// pixel margin to the right edge of the viewport.
: const Rect.fromLTRB(790.0, 0.0, 798.0, 90.0);
}
class TestCanvas implements Canvas {
final List<Invocation> invocations = <Invocation>[];
@override
void noSuchMethod(Invocation invocation) {
invocations.add(invocation);
}
}
Widget _buildBoilerplate({
TextDirection textDirection = TextDirection.ltr,
EdgeInsets padding = EdgeInsets.zero,
required Widget child,
}) {
return Directionality(
textDirection: textDirection,
child: MediaQuery(
data: MediaQueryData(padding: padding),
child: ScrollConfiguration(
behavior: const NoScrollbarBehavior(),
child: child,
),
),
);
}
class NoScrollbarBehavior extends MaterialScrollBehavior {
const NoScrollbarBehavior();
@override
Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) => child;
}
void main() {
testWidgets("Scrollbar doesn't show when tapping list", (WidgetTester tester) async {
await tester.pumpWidget(
_buildBoilerplate(
child: Center(
child: Container(
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFFFFF00)),
),
height: 200.0,
width: 300.0,
child: Scrollbar(
child: ListView(
children: const <Widget>[
SizedBox(height: 40.0, child: Text('0')),
SizedBox(height: 40.0, child: Text('1')),
SizedBox(height: 40.0, child: Text('2')),
SizedBox(height: 40.0, child: Text('3')),
SizedBox(height: 40.0, child: Text('4')),
SizedBox(height: 40.0, child: Text('5')),
SizedBox(height: 40.0, child: Text('6')),
SizedBox(height: 40.0, child: Text('7')),
],
),
),
),
),
),
);
SchedulerBinding.instance.debugAssertNoTransientCallbacks('Building a list with a scrollbar triggered an animation.');
await tester.tap(find.byType(ListView));
SchedulerBinding.instance.debugAssertNoTransientCallbacks('Tapping a block with a scrollbar triggered an animation.');
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 200));
await tester.drag(find.byType(ListView), const Offset(0.0, -10.0));
expect(SchedulerBinding.instance.transientCallbackCount, greaterThan(0));
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 200));
});
testWidgets('ScrollbarPainter does not divide by zero', (WidgetTester tester) async {
await tester.pumpWidget(
_buildBoilerplate(child: SizedBox(
height: 200.0,
width: 300.0,
child: Scrollbar(
child: ListView(
children: const <Widget>[
SizedBox(height: 40.0, child: Text('0')),
],
),
),
)),
);
final CustomPaint custom = tester.widget(find.descendant(
of: find.byType(Scrollbar),
matching: find.byType(CustomPaint),
).first);
final ScrollbarPainter? scrollPainter = custom.foregroundPainter as ScrollbarPainter?;
// Dragging makes the scrollbar first appear.
await tester.drag(find.text('0'), const Offset(0.0, -10.0));
await tester.pump(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 200));
final ScrollMetrics metrics = FixedScrollMetrics(
minScrollExtent: 0.0,
maxScrollExtent: 0.0,
pixels: 0.0,
viewportDimension: 100.0,
axisDirection: AxisDirection.down,
devicePixelRatio: tester.view.devicePixelRatio,
);
scrollPainter!.update(metrics, AxisDirection.down);
final TestCanvas canvas = TestCanvas();
scrollPainter.paint(canvas, const Size(10.0, 100.0));
// Scrollbar is not supposed to draw anything if there isn't enough content.
expect(canvas.invocations.isEmpty, isTrue);
});
testWidgets('When thumbVisibility is true, must pass a controller or find PrimaryScrollController', (WidgetTester tester) async {
Widget viewWithScroll() {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: const Scrollbar(
thumbVisibility: true,
child: SingleChildScrollView(
child: SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
}
await tester.pumpWidget(viewWithScroll());
final AssertionError exception = tester.takeException() as AssertionError;
expect(exception, isAssertionError);
});
testWidgets('When thumbVisibility is true, must pass a controller that is attached to a scroll view or find PrimaryScrollController', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
Widget viewWithScroll() {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: Scrollbar(
thumbVisibility: true,
controller: controller,
child: const SingleChildScrollView(
child: SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
}
await tester.pumpWidget(viewWithScroll());
final AssertionError exception = tester.takeException() as AssertionError;
expect(exception, isAssertionError);
controller.dispose();
});
testWidgets('On first render with thumbVisibility: true, the thumb shows', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
Widget viewWithScroll() {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: Scrollbar(
thumbVisibility: true,
controller: controller,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
}
await tester.pumpWidget(viewWithScroll());
await tester.pumpAndSettle();
expect(find.byType(Scrollbar), paints..rect());
controller.dispose();
});
testWidgets('On first render with thumbVisibility: true, the thumb shows with PrimaryScrollController', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
Widget viewWithScroll() {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: PrimaryScrollController(
controller: controller,
child: Builder(
builder: (BuildContext context) {
return const Scrollbar(
thumbVisibility: true,
child: SingleChildScrollView(
primary: true,
child: SizedBox(
width: 4000.0,
height: 4000.0,
),
),
);
},
),
),
),
);
}
await tester.pumpWidget(viewWithScroll());
await tester.pumpAndSettle();
expect(find.byType(Scrollbar), paints..rect());
controller.dispose();
});
testWidgets(
'When thumbVisibility is true, must pass a controller or find PrimaryScrollController',
(WidgetTester tester) async {
Widget viewWithScroll() {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: const Scrollbar(
thumbVisibility: true,
child: SingleChildScrollView(
child: SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
}
await tester.pumpWidget(viewWithScroll());
final AssertionError exception = tester.takeException() as AssertionError;
expect(exception, isAssertionError);
},
);
testWidgets(
'When thumbVisibility is true, must pass a controller that is attached to a scroll view or find PrimaryScrollController',
(WidgetTester tester) async {
final ScrollController controller = ScrollController();
Widget viewWithScroll() {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: Scrollbar(
thumbVisibility: true,
controller: controller,
child: const SingleChildScrollView(
child: SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
}
await tester.pumpWidget(viewWithScroll());
final AssertionError exception = tester.takeException() as AssertionError;
expect(exception, isAssertionError);
controller.dispose();
},
);
testWidgets('On first render with thumbVisibility: true, the thumb shows', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
Widget viewWithScroll() {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: Scrollbar(
thumbVisibility: true,
controller: controller,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
}
await tester.pumpWidget(viewWithScroll());
await tester.pumpAndSettle();
expect(find.byType(Scrollbar), paints..rect());
controller.dispose();
});
testWidgets('On first render with thumbVisibility: true, the thumb shows with PrimaryScrollController', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
Widget viewWithScroll() {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: PrimaryScrollController(
controller: controller,
child: Builder(
builder: (BuildContext context) {
return const Scrollbar(
thumbVisibility: true,
child: SingleChildScrollView(
primary: true,
child: SizedBox(
width: 4000.0,
height: 4000.0,
),
),
);
},
),
),
),
);
}
await tester.pumpWidget(viewWithScroll());
await tester.pumpAndSettle();
expect(find.byType(Scrollbar), paints..rect());
controller.dispose();
});
testWidgets('On first render with thumbVisibility: false, the thumb is hidden', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
Widget viewWithScroll() {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: Scrollbar(
thumbVisibility: false,
controller: controller,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
}
await tester.pumpWidget(viewWithScroll());
await tester.pumpAndSettle();
expect(find.byType(Scrollbar), isNot(paints..rect()));
controller.dispose();
});
testWidgets(
'With thumbVisibility: true, fling a scroll. While it is still scrolling, set thumbVisibility: false. The thumb should not fade out until the scrolling stops.',
(WidgetTester tester) async {
final ScrollController controller = ScrollController();
bool thumbVisibility = true;
Widget viewWithScroll() {
return _buildBoilerplate(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Theme(
data: ThemeData(),
child: Scaffold(
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.threed_rotation),
onPressed: () {
setState(() {
thumbVisibility = !thumbVisibility;
});
},
),
body: Scrollbar(
thumbVisibility: thumbVisibility,
controller: controller,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
},
),
);
}
await tester.pumpWidget(viewWithScroll());
await tester.pumpAndSettle();
await tester.fling(
find.byType(SingleChildScrollView),
const Offset(0.0, -10.0),
10,
);
expect(find.byType(Scrollbar), paints..rect());
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
// Scrollbar is not showing after scroll finishes
expect(find.byType(Scrollbar), isNot(paints..rect()));
controller.dispose();
},
);
testWidgets(
'With thumbVisibility: false, set thumbVisibility: true. The thumb should be always shown directly',
(WidgetTester tester) async {
final ScrollController controller = ScrollController();
bool thumbVisibility = false;
Widget viewWithScroll() {
return _buildBoilerplate(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Theme(
data: ThemeData(),
child: Scaffold(
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.threed_rotation),
onPressed: () {
setState(() {
thumbVisibility = !thumbVisibility;
});
},
),
body: Scrollbar(
thumbVisibility: thumbVisibility,
controller: controller,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
},
),
);
}
await tester.pumpWidget(viewWithScroll());
await tester.pumpAndSettle();
expect(find.byType(Scrollbar), isNot(paints..rect()));
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
// Scrollbar is not showing after scroll finishes
expect(find.byType(Scrollbar), paints..rect());
controller.dispose();
},
);
testWidgets(
'With thumbVisibility: false, fling a scroll. While it is still scrolling, set thumbVisibility: true. The thumb should not fade even after the scrolling stops',
(WidgetTester tester) async {
final ScrollController controller = ScrollController();
bool thumbVisibility = false;
Widget viewWithScroll() {
return _buildBoilerplate(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Theme(
data: ThemeData(),
child: Scaffold(
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.threed_rotation),
onPressed: () {
setState(() {
thumbVisibility = !thumbVisibility;
});
},
),
body: Scrollbar(
thumbVisibility: thumbVisibility,
controller: controller,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
},
),
);
}
await tester.pumpWidget(viewWithScroll());
await tester.pumpAndSettle();
expect(find.byType(Scrollbar), isNot(paints..rect()));
await tester.fling(
find.byType(SingleChildScrollView),
const Offset(0.0, -10.0),
10,
);
expect(find.byType(Scrollbar), paints..rect());
await tester.tap(find.byType(FloatingActionButton));
await tester.pump();
expect(find.byType(Scrollbar), paints..rect());
// Wait for the timer delay to expire.
await tester.pump(const Duration(milliseconds: 600)); // _kScrollbarTimeToFade
await tester.pumpAndSettle();
// Scrollbar thumb is showing after scroll finishes and timer ends.
expect(find.byType(Scrollbar), paints..rect());
controller.dispose();
},
);
testWidgets(
'Toggling thumbVisibility while not scrolling fades the thumb in/out. This works even when you have never scrolled at all yet',
(WidgetTester tester) async {
final ScrollController controller = ScrollController();
bool thumbVisibility = true;
Widget viewWithScroll() {
return _buildBoilerplate(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Theme(
data: ThemeData(),
child: Scaffold(
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.threed_rotation),
onPressed: () {
setState(() {
thumbVisibility = !thumbVisibility;
});
},
),
body: Scrollbar(
thumbVisibility: thumbVisibility,
controller: controller,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
);
},
),
);
}
await tester.pumpWidget(viewWithScroll());
await tester.pumpAndSettle();
final Finder materialScrollbar = find.byType(Scrollbar);
expect(materialScrollbar, paints..rect());
await tester.tap(find.byType(FloatingActionButton));
await tester.pumpAndSettle();
expect(materialScrollbar, isNot(paints..rect()));
controller.dispose();
},
);
testWidgets('Scrollbar respects thickness and radius', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
Widget viewWithScroll({Radius? radius}) {
return _buildBoilerplate(
child: Theme(
data: ThemeData(),
child: Scrollbar(
controller: controller,
thickness: 20,
radius: radius,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(
width: 1600.0,
height: 1200.0,
),
),
),
),
);
}
// Scroll a bit to cause the scrollbar thumb to be shown;
// undo the scroll to put the thumb back at the top.
await tester.pumpWidget(viewWithScroll());
const double scrollAmount = 10.0;
final TestGesture scrollGesture = await tester.startGesture(tester.getCenter(find.byType(SingleChildScrollView)));
await scrollGesture.moveBy(const Offset(0.0, -scrollAmount));
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
await scrollGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pump();
await scrollGesture.up();
await tester.pump();
// Long press on the scrollbar thumb and expect it to grow
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(780.0, 0.0, 800.0, 600.0),
color: Colors.transparent,
)
..line(
p1: const Offset(780.0, 0.0),
p2: const Offset(780.0, 600.0),
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(780.0, 0.0, 800.0, 300.0),
color: _kAndroidThumbIdleColor,
),
);
await tester.pumpWidget(viewWithScroll(radius: const Radius.circular(10)));
expect(find.byType(Scrollbar), paints..rrect(
rrect: RRect.fromRectAndRadius(const Rect.fromLTRB(780, 0.0, 800.0, 300.0), const Radius.circular(10)),
));
await tester.pumpAndSettle();
controller.dispose();
});
testWidgets('Tapping the track area pages the Scroll View', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: Scrollbar(
interactive: true,
thumbVisibility: true,
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
child: const SizedBox(width: 1000.0, height: 1000.0),
),
),
),
),
);
await tester.pumpAndSettle();
expect(scrollController.offset, 0.0);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 0.0, 800.0, 360.0),
color: _kAndroidThumbIdleColor,
),
);
// Tap on the track area below the thumb.
await tester.tapAt(const Offset(796.0, 550.0));
await tester.pumpAndSettle();
expect(scrollController.offset, 400.0);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 240.0, 800.0, 600.0),
color: _kAndroidThumbIdleColor,
),
);
// Tap on the track area above the thumb.
await tester.tapAt(const Offset(796.0, 50.0));
await tester.pumpAndSettle();
expect(scrollController.offset, 0.0);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 0.0, 800.0, 360.0),
color: _kAndroidThumbIdleColor,
),
);
scrollController.dispose();
});
testWidgets('Scrollbar never goes away until finger lift', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scrollbar(
child: SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
),
);
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(SingleChildScrollView)));
await gesture.moveBy(const Offset(0.0, -20.0));
await tester.pump();
// Scrollbar fully showing
await tester.pump(const Duration(milliseconds: 500));
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 3.0, 800.0, 93.0),
color: _kAndroidThumbIdleColor,
),
);
await tester.pump(const Duration(seconds: 3));
await tester.pump(const Duration(seconds: 3));
// Still there.
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 3.0, 800.0, 93.0),
color: _kAndroidThumbIdleColor,
),
);
await gesture.up();
await tester.pump(_kScrollbarTimeToFade);
await tester.pump(_kScrollbarFadeDuration * 0.5);
// Opacity going down now.
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 3.0, 800.0, 93.0),
color: const Color(0xc6bcbcbc),
),
);
});
testWidgets('Scrollbar thumb can be dragged', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: PrimaryScrollController(
controller: scrollController,
child: Scrollbar(
interactive: true,
thumbVisibility: true,
controller: scrollController,
child: const SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
),
),
);
await tester.pumpAndSettle();
expect(scrollController.offset, 0.0);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: getStartingThumbRect(isAndroid: true),
color: _kAndroidThumbIdleColor,
),
);
// Drag the thumb down to scroll down.
const double scrollAmount = 10.0;
final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: getStartingThumbRect(isAndroid: true),
// Drag color
color: const Color(0x99000000),
),
);
await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
await dragScrollbarGesture.up();
await tester.pumpAndSettle();
// The view has scrolled more than it would have by a swipe pointer of the
// same distance.
expect(scrollController.offset, greaterThan(scrollAmount * 2));
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 10.0, 800.0, 100.0),
color: _kAndroidThumbIdleColor,
),
);
scrollController.dispose();
});
testWidgets('Scrollbar thumb color completes a hover animation', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: false,
scrollbarTheme: ScrollbarThemeData(thumbVisibility: MaterialStateProperty.all(true)),
),
home: const SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
);
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
getStartingThumbRect(isAndroid: false),
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
final TestGesture gesture = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(const Offset(794.0, 5.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
getStartingThumbRect(isAndroid: false),
_kDefaultThumbRadius,
),
// Hover color
color: const Color(0x80000000),
),
);
},
variant: const TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows,
}),
);
testWidgets('Hover animation is not triggered by tap gestures', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: false,
scrollbarTheme: ScrollbarThemeData(
thumbVisibility: MaterialStateProperty.all(true),
trackVisibility: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return true;
}
return false;
})
),
),
home: const SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
);
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
getStartingThumbRect(isAndroid: false),
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
await tester.tapAt(const Offset(794.0, 5.0));
await tester.pumpAndSettle();
// Tapping triggers a hover enter event. In this case, the Scrollbar should
// be unchanged since it ignores hover events that aren't from a mouse.
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
getStartingThumbRect(isAndroid: false),
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
// Now trigger hover with a mouse.
final TestGesture gesture = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(const Offset(794.0, 5.0));
await tester.pump();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(784.0, 0.0, 800.0, 600.0),
color: const Color(0x08000000),
)
..line(
p1: const Offset(784.0, 0.0),
p2: const Offset(784.0, 600.0),
strokeWidth: 1.0,
color: _kDefaultIdleThumbColor,
)
..rrect(
rrect: RRect.fromRectAndRadius(
// Scrollbar thumb is larger
const Rect.fromLTRB(786.0, 0.0, 798.0, 90.0),
_kDefaultThumbRadius,
),
// Hover color
color: const Color(0x80000000),
),
);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.linux }),
);
testWidgets('ScrollbarThemeData.thickness replaces hoverThickness', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: false,
scrollbarTheme: ScrollbarThemeData(
thumbVisibility: MaterialStateProperty.resolveWith((Set<MaterialState> states) => true),
trackVisibility: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
return states.contains(MaterialState.hovered);
}),
thickness: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return 40.0;
}
// Default thickness
return 8.0;
}),
),
),
home: const SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
);
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
getStartingThumbRect(isAndroid: false),
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
final TestGesture gesture = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(const Offset(794.0, 5.0));
await tester.pump();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(756.0, 0.0, 800.0, 600.0),
color: const Color(0x08000000),
)
..line(
p1: const Offset(756.0, 0.0),
p2: const Offset(756.0, 600.0),
strokeWidth: 1.0,
color: _kDefaultIdleThumbColor,
)
..rrect(
rrect: RRect.fromRectAndRadius(
// Scrollbar thumb is larger
const Rect.fromLTRB(758.0, 0.0, 798.0, 90.0),
_kDefaultThumbRadius,
),
// Hover color
color: const Color(0x80000000),
),
);
},
variant: const TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows,
}),
);
testWidgets('ScrollbarThemeData.trackVisibility', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: false,
scrollbarTheme: ScrollbarThemeData(
thumbVisibility: MaterialStateProperty.all(true),
trackVisibility: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return true;
}
return false;
}),
),
),
home: const SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
);
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
getStartingThumbRect(isAndroid: false),
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
final TestGesture gesture = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(const Offset(794.0, 5.0));
await tester.pump();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(784.0, 0.0, 800.0, 600.0),
color: const Color(0x08000000),
)
..line(
p1: const Offset(784.0, 0.0),
p2: const Offset(784.0, 600.0),
strokeWidth: 1.0,
color: _kDefaultIdleThumbColor,
)
..rrect(
rrect: RRect.fromRectAndRadius(
// Scrollbar thumb is larger
const Rect.fromLTRB(786.0, 0.0, 798.0, 90.0),
_kDefaultThumbRadius,
),
// Hover color
color: const Color(0x80000000),
),
);
},
variant: const TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows,
}),
);
testWidgets('Scrollbar trackVisibility on hovered', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: false,
scrollbarTheme: ScrollbarThemeData(
thumbVisibility: MaterialStateProperty.all(true),
trackVisibility: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return true;
}
return false;
}),
),
),
home: const SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
);
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints..rrect(
rrect: RRect.fromRectAndRadius(
getStartingThumbRect(isAndroid: false),
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
final TestGesture gesture = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(const Offset(794.0, 5.0));
await tester.pump();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(784.0, 0.0, 800.0, 600.0),
color: const Color(0x08000000),
)
..line(
p1: const Offset(784.0, 0.0),
p2: const Offset(784.0, 600.0),
strokeWidth: 1.0,
color: _kDefaultIdleThumbColor,
)
..rrect(
rrect: RRect.fromRectAndRadius(
// Scrollbar thumb is larger
const Rect.fromLTRB(786.0, 0.0, 798.0, 90.0),
_kDefaultThumbRadius,
),
// Hover color
color: const Color(0x80000000),
),
);
},
variant: const TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.macOS,
TargetPlatform.windows,
}),
);
testWidgets('Adaptive scrollbar', (WidgetTester tester) async {
Widget viewWithScroll(TargetPlatform platform) {
return _buildBoilerplate(
child: Theme(
data: ThemeData(
platform: platform,
),
child: const Scrollbar(
child: SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
),
);
}
await tester.pumpWidget(viewWithScroll(TargetPlatform.android));
await tester.drag(find.byType(SingleChildScrollView), const Offset(0.0, -10.0));
await tester.pump();
// Scrollbar fully showing
await tester.pump(const Duration(milliseconds: 500));
expect(find.byType(Scrollbar), paints..rect());
await tester.pumpWidget(viewWithScroll(TargetPlatform.iOS));
final TestGesture gesture = await tester.startGesture(
tester.getCenter(find.byType(SingleChildScrollView)),
);
await gesture.moveBy(const Offset(0.0, -10.0));
await tester.drag(find.byType(SingleChildScrollView), const Offset(0.0, -10.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(find.byType(Scrollbar), paints..rrect());
expect(find.byType(CupertinoScrollbar), paints..rrect());
await gesture.up();
await tester.pumpAndSettle();
});
testWidgets('Scrollbar passes controller to CupertinoScrollbar', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
Widget viewWithScroll(TargetPlatform? platform) {
return _buildBoilerplate(
child: Theme(
data: ThemeData(
platform: platform,
),
child: Scrollbar(
controller: controller,
child: SingleChildScrollView(
controller: controller,
child: const SizedBox(width: 4000.0, height: 4000.0),
),
),
),
);
}
await tester.pumpWidget(viewWithScroll(debugDefaultTargetPlatformOverride));
final TestGesture gesture = await tester.startGesture(
tester.getCenter(find.byType(SingleChildScrollView)),
);
await gesture.moveBy(const Offset(0.0, -10.0));
await tester.drag(find.byType(SingleChildScrollView), const Offset(0.0, -10.0));
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(find.byType(CupertinoScrollbar), paints..rrect());
final CupertinoScrollbar scrollbar = tester.widget<CupertinoScrollbar>(find.byType(CupertinoScrollbar));
expect(scrollbar.controller, isNotNull);
controller.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }));
testWidgets("Scrollbar doesn't show when scroll the inner scrollable widget", (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey();
final GlobalKey key2 = GlobalKey();
final GlobalKey outerKey = GlobalKey();
final GlobalKey innerKey = GlobalKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: ScrollConfiguration(
behavior: const NoScrollbarBehavior(),
child: Scrollbar(
key: key2,
child: SingleChildScrollView(
key: outerKey,
child: SizedBox(
height: 1000.0,
width: double.infinity,
child: Column(
children: <Widget>[
Scrollbar(
key: key1,
child: SizedBox(
height: 300.0,
width: double.infinity,
child: SingleChildScrollView(
key: innerKey,
child: const SizedBox(
key: Key('Inner scrollable'),
height: 1000.0,
width: double.infinity,
),
),
),
),
],
),
),
),
),
),
),
),
);
// Drag the inner scrollable widget.
await tester.drag(find.byKey(innerKey), const Offset(0.0, -25.0));
await tester.pump();
// Scrollbar fully showing.
await tester.pump(const Duration(milliseconds: 500));
expect(
tester.renderObject(find.byKey(key2)),
paintsExactlyCountTimes(#drawRect, 2), // Each bar will call [drawRect] twice.
);
expect(
tester.renderObject(find.byKey(key1)),
paintsExactlyCountTimes(#drawRect, 2),
);
}, variant: TargetPlatformVariant.all());
testWidgets('Scrollbar dragging can be disabled', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: PrimaryScrollController(
controller: scrollController,
child: Scrollbar(
interactive: false,
thumbVisibility: true,
controller: scrollController,
child: const SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
),
),
);
await tester.pumpAndSettle();
expect(scrollController.offset, 0.0);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(788.0, 0.0, 800.0, 600.0),
color: Colors.transparent,
)
..line(
p1: const Offset(788.0, 0.0),
p2: const Offset(788.0, 600.0),
strokeWidth: 1.0,
color: Colors.transparent,
)
..rrect(
rrect: RRect.fromRectAndRadius(
getStartingThumbRect(isAndroid: false),
_kDefaultThumbRadius,
),
color: _kDefaultIdleThumbColor,
),
);
// Try to drag the thumb down.
const double scrollAmount = 10.0;
final TestGesture dragScrollbarThumbGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
await dragScrollbarThumbGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
await dragScrollbarThumbGesture.up();
await tester.pumpAndSettle();
// Dragging on the thumb does not change the offset.
expect(scrollController.offset, 0.0);
// Drag in the track area to validate pass through to scrollable.
final TestGesture dragPassThroughTrack = await tester.startGesture(const Offset(797.0, 250.0));
await dragPassThroughTrack.moveBy(const Offset(0.0, -scrollAmount));
await tester.pumpAndSettle();
await dragPassThroughTrack.up();
await tester.pumpAndSettle();
// The scroll view received the drag.
expect(scrollController.offset, scrollAmount);
// Tap on the track to validate the scroll view will not page.
await tester.tapAt(const Offset(797.0, 200.0));
await tester.pumpAndSettle();
// The offset should not have changed.
expect(scrollController.offset, scrollAmount);
scrollController.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.fuchsia }));
testWidgets('Scrollbar dragging is disabled by default on Android', (WidgetTester tester) async {
int tapCount = 0;
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
home: PrimaryScrollController(
controller: scrollController,
child: Scrollbar(
thumbVisibility: true,
controller: scrollController,
child: SingleChildScrollView(
dragStartBehavior: DragStartBehavior.down,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
tapCount += 1;
},
child: const SizedBox(
width: 4000.0,
height: 4000.0,
),
),
),
),
),
),
);
await tester.pumpAndSettle();
expect(scrollController.offset, 0.0);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: getStartingThumbRect(isAndroid: true),
color: _kAndroidThumbIdleColor,
),
);
// Try to drag the thumb down.
const double scrollAmount = 50.0;
await tester.dragFrom(
const Offset(797.0, 45.0),
const Offset(0.0, scrollAmount),
touchSlopY: 0.0,
);
await tester.pumpAndSettle();
// Dragging on the thumb does not change the offset.
expect(scrollController.offset, 0.0);
expect(tapCount, 0);
// Try to drag up in the thumb area to validate pass through to scrollable.
await tester.dragFrom(
const Offset(797.0, 45.0),
const Offset(0.0, -scrollAmount),
);
await tester.pumpAndSettle();
// The scroll view received the drag.
expect(scrollController.offset, scrollAmount);
expect(tapCount, 0);
// Drag in the track area to validate pass through to scrollable.
await tester.dragFrom(
const Offset(797.0, 45.0),
const Offset(0.0, -scrollAmount),
touchSlopY: 0.0,
);
await tester.pumpAndSettle();
// The scroll view received the drag.
expect(scrollController.offset, scrollAmount * 2);
expect(tapCount, 0);
// Tap on the thumb to validate the scroll view receives a click.
await tester.tapAt(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
expect(tapCount, 1);
// Tap on the track to validate the scroll view will not page and receives a click.
await tester.tapAt(const Offset(797.0, 400.0));
await tester.pumpAndSettle();
// The offset should not have changed.
expect(scrollController.offset, scrollAmount * 2);
expect(tapCount, 2);
scrollController.dispose();
});
testWidgets('Simultaneous dragging and pointer scrolling does not cause a crash', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/70105
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: PrimaryScrollController(
controller: scrollController,
child: Scrollbar(
interactive: true,
thumbVisibility: true,
controller: scrollController,
child: const SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0),
),
),
),
),
);
await tester.pumpAndSettle();
expect(scrollController.offset, 0.0);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: getStartingThumbRect(isAndroid: true),
color: _kAndroidThumbIdleColor,
),
);
// Drag the thumb down to scroll down.
const double scrollAmount = 10.0;
final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: _kAndroidTrackDimensions,
color: Colors.transparent,
)
..line(
p1: _kTrackBorderPoint1,
p2: _kTrackBorderPoint2,
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: getStartingThumbRect(isAndroid: true),
// Drag color
color: const Color(0x99000000),
),
);
await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount));
await tester.pumpAndSettle();
expect(scrollController.offset, greaterThan(10.0));
final double previousOffset = scrollController.offset;
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(796.0, 0.0, 800.0, 600.0),
color: Colors.transparent,
)
..line(
p1: const Offset(796.0, 0.0),
p2: const Offset(796.0, 600.0),
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 10.0, 800.0, 100.0),
color: const Color(0x99000000),
),
);
// Execute a pointer scroll while dragging (drag gesture has not come up yet)
final TestPointer pointer = TestPointer(1, ui.PointerDeviceKind.mouse);
pointer.hover(const Offset(798.0, 15.0));
await tester.sendEventToBinding(pointer.scroll(const Offset(0.0, 20.0)));
await tester.pumpAndSettle();
if (!kIsWeb) {
// Scrolling while holding the drag on the scrollbar and still hovered over
// the scrollbar should not have changed the scroll offset.
expect(pointer.location, const Offset(798.0, 15.0));
expect(scrollController.offset, previousOffset);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(796.0, 0.0, 800.0, 600.0),
color: Colors.transparent,
)
..line(
p1: const Offset(796.0, 0.0),
p2: const Offset(796.0, 600.0),
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 10.0, 800.0, 100.0),
color: const Color(0x99000000),
),
);
} else {
expect(pointer.location, const Offset(798.0, 15.0));
expect(scrollController.offset, previousOffset + 20.0);
}
// Drag is still being held, move pointer to be hovering over another area
// of the scrollable (not over the scrollbar) and execute another pointer scroll
pointer.hover(tester.getCenter(find.byType(SingleChildScrollView)));
await tester.sendEventToBinding(pointer.scroll(const Offset(0.0, -90.0)));
await tester.pumpAndSettle();
// Scrolling while holding the drag on the scrollbar changed the offset
expect(pointer.location, const Offset(400.0, 300.0));
expect(scrollController.offset, 0.0);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(796.0, 0.0, 800.0, 600.0),
color: Colors.transparent,
)
..line(
p1: const Offset(796.0, 0.0),
p2: const Offset(796.0, 600.0),
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 0.0, 800.0, 90.0),
color: const Color(0x99000000),
),
);
await dragScrollbarGesture.up();
await tester.pumpAndSettle();
expect(scrollController.offset, 0.0);
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(796.0, 0.0, 800.0, 600.0),
color: Colors.transparent,
)
..line(
p1: const Offset(796.0, 0.0),
p2: const Offset(796.0, 600.0),
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(796.0, 0.0, 800.0, 90.0),
color: const Color(0xffbcbcbc),
),
);
scrollController.dispose();
});
testWidgets('Scrollbar.thumbVisibility triggers assertion when multiple ScrollPositions are attached.', (WidgetTester tester) async {
Widget getTabContent({ ScrollController? scrollController }) {
return Scrollbar(
thumbVisibility: true,
controller: scrollController,
child: ListView.builder(
controller: scrollController,
itemCount: 200,
itemBuilder: (BuildContext context, int index) => const Text('Test'),
),
);
}
Widget buildApp({
required String id,
ScrollController? scrollController,
}) {
return MaterialApp(
key: ValueKey<String>(id),
home: DefaultTabController(
length: 2,
child: Scaffold(
body: TabBarView(
children: <Widget>[
getTabContent(scrollController: scrollController),
getTabContent(scrollController: scrollController),
],
),
),
),
);
}
// Asserts when using the PrimaryScrollController.
await tester.pumpWidget(buildApp(id: 'PrimaryScrollController'));
// Swipe to the second tab, resulting in two attached ScrollPositions during
// the transition.
await tester.drag(find.text('Test').first, const Offset(-100.0, 0.0));
await tester.pump();
FlutterError error = tester.takeException() as FlutterError;
expect(
error.message,
'''
The PrimaryScrollController is attached to more than one ScrollPosition.
The Scrollbar requires a single ScrollPosition in order to be painted.
When Scrollbar.thumbVisibility is true, the associated ScrollController must only have one ScrollPosition attached.
If a ScrollController has not been provided, the PrimaryScrollController is used by default on mobile platforms for ScrollViews with an Axis.vertical scroll direction.
More than one ScrollView may have tried to use the PrimaryScrollController of the current context. ScrollView.primary can override this behavior.''',
);
// Asserts when using the ScrollController provided by the user.
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
buildApp(
id: 'Provided ScrollController',
scrollController: scrollController,
),
);
// Swipe to the second tab, resulting in two attached ScrollPositions during
// the transition.
await tester.drag(find.text('Test').first, const Offset(-100.0, 0.0));
await tester.pump();
error = tester.takeException() as FlutterError;
expect(
error.message,
'''
The provided ScrollController is attached to more than one ScrollPosition.
The Scrollbar requires a single ScrollPosition in order to be painted.
When Scrollbar.thumbVisibility is true, the associated ScrollController must only have one ScrollPosition attached.
The provided ScrollController cannot be shared by multiple ScrollView widgets.''',
);
scrollController.dispose();
});
testWidgets('Scrollbar scrollOrientation works correctly', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
Widget buildScrollWithOrientation(ScrollbarOrientation orientation) {
return _buildBoilerplate(
child: Theme(
data: ThemeData(
platform: TargetPlatform.android,
),
child: PrimaryScrollController(
controller: scrollController,
child: Scrollbar(
interactive: true,
thumbVisibility: true,
scrollbarOrientation: orientation,
controller: scrollController,
child: const SingleChildScrollView(
child: SizedBox(width: 4000.0, height: 4000.0)
),
),
),
)
);
}
await tester.pumpWidget(buildScrollWithOrientation(ScrollbarOrientation.left));
await tester.pumpAndSettle();
expect(
find.byType(Scrollbar),
paints
..rect(
rect: const Rect.fromLTRB(0.0, 0.0, 4.0, 600.0),
color: Colors.transparent,
)
..line(
p1: const Offset(4.0, 0.0),
p2: const Offset(4.0, 600.0),
strokeWidth: 1.0,
color: Colors.transparent,
)
..rect(
rect: const Rect.fromLTRB(0.0, 0.0, 4.0, 90.0),
color: _kAndroidThumbIdleColor,
),
);
scrollController.dispose();
});
}
| flutter/packages/flutter/test/material/scrollbar_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/scrollbar_test.dart",
"repo_id": "flutter",
"token_count": 28297
} | 676 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
import 'feedback_tester.dart';
Widget wrap({ required Widget child }) {
return MediaQuery(
data: const MediaQueryData(),
child: Directionality(
textDirection: TextDirection.ltr,
child: Material(child: child),
),
);
}
void main() {
testWidgets('SwitchListTile control test', (WidgetTester tester) async {
final List<dynamic> log = <dynamic>[];
await tester.pumpWidget(wrap(
child: SwitchListTile(
value: true,
onChanged: (bool value) { log.add(value); },
title: const Text('Hello'),
),
));
await tester.tap(find.text('Hello'));
log.add('-');
await tester.tap(find.byType(Switch));
expect(log, equals(<dynamic>[false, '-', false]));
});
testWidgets('SwitchListTile semantics test', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(wrap(
child: Column(
children: <Widget>[
SwitchListTile(
value: true,
onChanged: (bool value) { },
title: const Text('AAA'),
secondary: const Text('aaa'),
),
CheckboxListTile(
value: true,
onChanged: (bool? value) { },
title: const Text('BBB'),
secondary: const Text('bbb'),
),
RadioListTile<bool>(
value: true,
groupValue: false,
onChanged: (bool? value) { },
title: const Text('CCC'),
secondary: const Text('ccc'),
),
],
),
));
// This test verifies that the label and the control get merged.
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 56.0),
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.hasToggledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
SemanticsFlag.isToggled,
],
actions: SemanticsAction.tap.index,
label: 'aaa\nAAA',
),
TestSemantics.rootChild(
id: 3,
rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 56.0),
transform: Matrix4.translationValues(0.0, 56.0, 0.0),
flags: <SemanticsFlag>[
SemanticsFlag.hasCheckedState,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isChecked,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: SemanticsAction.tap.index,
label: 'bbb\nBBB',
),
TestSemantics.rootChild(
id: 5,
rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 56.0),
transform: Matrix4.translationValues(0.0, 112.0, 0.0),
flags: <SemanticsFlag>[
SemanticsFlag.hasCheckedState,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
SemanticsFlag.isInMutuallyExclusiveGroup,
],
actions: SemanticsAction.tap.index,
label: 'CCC\nccc',
),
],
)));
semantics.dispose();
});
testWidgets('Material2 - SwitchListTile has the right colors', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(padding: EdgeInsets.all(8.0)),
child: Theme(
data: ThemeData(useMaterial3: false),
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: SwitchListTile(
value: value,
onChanged: (bool newValue) {
setState(() { value = newValue; });
},
activeColor: Colors.red[500],
activeTrackColor: Colors.green[500],
inactiveThumbColor: Colors.yellow[500],
inactiveTrackColor: Colors.blue[500],
),
);
},
),
),
),
),
);
expect(
find.byType(Switch),
paints
..rrect(color: Colors.blue[500])
..rrect()
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: Colors.yellow[500]),
);
await tester.tap(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(color: Colors.green[500])
..rrect()
..rrect(color: const Color(0x33000000))
..rrect(color: const Color(0x24000000))
..rrect(color: const Color(0x1f000000))
..rrect(color: Colors.red[500]),
);
});
testWidgets('Material3 - SwitchListTile has the right colors', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(padding: EdgeInsets.all(8.0)),
child: Theme(
data: ThemeData(useMaterial3: true),
child: Directionality(
textDirection: TextDirection.ltr,
child:
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: SwitchListTile(
value: value,
onChanged: (bool newValue) {
setState(() { value = newValue; });
},
activeColor: Colors.red[500],
activeTrackColor: Colors.green[500],
inactiveThumbColor: Colors.yellow[500],
inactiveTrackColor: Colors.blue[500],
),
);
},
),
),
),
),
);
expect(
find.byType(Switch),
paints
..rrect(color: Colors.blue[500])
..rrect()
..rrect(color: Colors.yellow[500])
);
await tester.tap(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect(color: Colors.green[500])
..rrect()
..rrect(color: Colors.red[500])
);
});
testWidgets('SwitchListTile.adaptive only uses material switch', (WidgetTester tester) async {
bool value = false;
Widget buildFrame(TargetPlatform platform) {
return MaterialApp(
theme: ThemeData(platform: platform),
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: SwitchListTile.adaptive(
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
);
}
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS,
TargetPlatform.macOS, TargetPlatform.android, TargetPlatform.fuchsia,
TargetPlatform.linux, TargetPlatform.windows ]) {
value = false;
await tester.pumpWidget(buildFrame(platform));
expect(find.byType(CupertinoSwitch), findsNothing);
expect(find.byType(Switch), findsOneWidget);
expect(value, isFalse, reason: 'on ${platform.name}');
await tester.tap(find.byType(SwitchListTile));
expect(value, isTrue, reason: 'on ${platform.name}');
}
});
testWidgets('SwitchListTile contentPadding', (WidgetTester tester) async {
Widget buildFrame(TextDirection textDirection) {
return MediaQuery(
data: const MediaQueryData(),
child: Directionality(
textDirection: textDirection,
child: Material(
child: Container(
alignment: Alignment.topLeft,
child: SwitchListTile(
contentPadding: const EdgeInsetsDirectional.only(
start: 10.0,
end: 20.0,
top: 30.0,
bottom: 40.0,
),
secondary: const Text('L'),
title: const Text('title'),
value: true,
onChanged: (bool selected) {},
),
),
),
),
);
}
await tester.pumpWidget(buildFrame(TextDirection.ltr));
expect(tester.getTopLeft(find.text('L')).dx, 10.0); // contentPadding.start = 10
expect(tester.getTopRight(find.byType(Switch)).dx, 780.0); // 800 - contentPadding.end
await tester.pumpWidget(buildFrame(TextDirection.rtl));
expect(tester.getTopLeft(find.byType(Switch)).dx, 20.0); // contentPadding.end = 20
expect(tester.getTopRight(find.text('L')).dx, 790.0); // 800 - contentPadding.start
});
testWidgets('SwitchListTile can autofocus unless disabled.', (WidgetTester tester) async {
final GlobalKey childKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: ListView(
children: <Widget>[
SwitchListTile(
value: true,
onChanged: (_) {},
title: Text('A', key: childKey),
autofocus: true,
),
],
),
),
),
);
await tester.pump();
expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isTrue);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: ListView(
children: <Widget>[
SwitchListTile(
value: true,
onChanged: null,
title: Text('A', key: childKey),
autofocus: true,
),
],
),
),
),
);
await tester.pump();
expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isFalse);
});
testWidgets('SwitchListTile controlAffinity test', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Material(
child: SwitchListTile(
value: true,
onChanged: null,
secondary: Icon(Icons.info),
title: Text('Title'),
controlAffinity: ListTileControlAffinity.leading,
),
),
));
final ListTile listTile = tester.widget(find.byType(ListTile));
// When controlAffinity is ListTileControlAffinity.leading, the position of
// Switch is at leading edge and SwitchListTile.secondary at trailing edge.
// Find the ExcludeFocus widget within the ListTile's leading
final ExcludeFocus excludeFocusWidget = tester.widget(
find.byWidgetPredicate((Widget widget) => listTile.leading == widget && widget is ExcludeFocus),
);
// Assert that the ExcludeFocus widget is not null
expect(excludeFocusWidget, isNotNull);
// Assert that the child of ExcludeFocus is Switch
expect(excludeFocusWidget.child.runtimeType, Switch);
// Assert that the trailing is Icon
expect(listTile.trailing.runtimeType, Icon);
});
testWidgets('SwitchListTile controlAffinity default value test', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: Material(
child: SwitchListTile(
value: true,
onChanged: null,
secondary: Icon(Icons.info),
title: Text('Title'),
),
),
));
final ListTile listTile = tester.widget(find.byType(ListTile));
// By default, value of controlAffinity is ListTileControlAffinity.platform,
// where the position of SwitchListTile.secondary is at leading edge and Switch
// at trailing edge. This also covers test for ListTileControlAffinity.trailing.
// Find the ExcludeFocus widget within the ListTile's trailing
final ExcludeFocus excludeFocusWidget = tester.widget(
find.byWidgetPredicate((Widget widget) => listTile.trailing == widget && widget is ExcludeFocus),
);
// Assert that the ExcludeFocus widget is not null
expect(excludeFocusWidget, isNotNull);
// Assert that the child of ExcludeFocus is Switch
expect(excludeFocusWidget.child.runtimeType, Switch);
// Assert that the leading is Icon
expect(listTile.leading.runtimeType, Icon);
});
testWidgets('SwitchListTile respects shape', (WidgetTester tester) async {
const ShapeBorder shapeBorder = RoundedRectangleBorder(
borderRadius: BorderRadius.horizontal(right: Radius.circular(100)),
);
await tester.pumpWidget(const MaterialApp(
home: Material(
child: SwitchListTile(
value: true,
onChanged: null,
title: Text('Title'),
shape: shapeBorder,
),
),
));
expect(tester.widget<InkWell>(find.byType(InkWell)).customBorder, shapeBorder);
});
testWidgets('SwitchListTile respects tileColor', (WidgetTester tester) async {
final Color tileColor = Colors.red.shade500;
await tester.pumpWidget(
wrap(
child: Center(
child: SwitchListTile(
value: false,
onChanged: null,
title: const Text('Title'),
tileColor: tileColor,
),
),
),
);
expect(find.byType(Material), paints..rect(color: tileColor));
});
testWidgets('SwitchListTile respects selectedTileColor', (WidgetTester tester) async {
final Color selectedTileColor = Colors.green.shade500;
await tester.pumpWidget(
wrap(
child: Center(
child: SwitchListTile(
value: false,
onChanged: null,
title: const Text('Title'),
selected: true,
selectedTileColor: selectedTileColor,
),
),
),
);
expect(find.byType(Material), paints..rect(color: selectedTileColor));
});
testWidgets('SwitchListTile selected item text Color', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/pull/76909
const Color activeColor = Color(0xff00ff00);
Widget buildFrame({ Color? activeColor, Color? thumbColor }) {
return MaterialApp(
theme: ThemeData.light().copyWith(
switchTheme: SwitchThemeData(
thumbColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
return states.contains(MaterialState.selected) ? thumbColor : null;
}),
),
),
home: Scaffold(
body: Center(
child: SwitchListTile(
activeColor: activeColor,
selected: true,
title: const Text('title'),
value: true,
onChanged: (bool? value) { },
),
),
),
);
}
Color? textColor(String text) {
return tester.renderObject<RenderParagraph>(find.text(text)).text.style?.color;
}
await tester.pumpWidget(buildFrame(activeColor: activeColor));
expect(textColor('title'), activeColor);
await tester.pumpWidget(buildFrame(activeColor: activeColor));
expect(textColor('title'), activeColor);
});
testWidgets('SwitchListTile respects visualDensity', (WidgetTester tester) async {
const Key key = Key('test');
Future<void> buildTest(VisualDensity visualDensity) async {
return tester.pumpWidget(
wrap(
child: Center(
child: SwitchListTile(
key: key,
value: false,
onChanged: (bool? value) {},
autofocus: true,
visualDensity: visualDensity,
),
),
),
);
}
await buildTest(VisualDensity.standard);
final RenderBox box = tester.renderObject(find.byKey(key));
await tester.pumpAndSettle();
expect(box.size, equals(const Size(800, 56)));
});
testWidgets('SwitchListTile respects focusNode', (WidgetTester tester) async {
final GlobalKey childKey = GlobalKey();
await tester.pumpWidget(
wrap(
child: Center(
child: SwitchListTile(
value: false,
title: Text('A', key: childKey),
onChanged: (bool? value) {},
),
),
),
);
await tester.pump();
final FocusNode tileNode = Focus.of(childKey.currentContext!);
tileNode.requestFocus();
await tester.pump(); // Let the focus take effect.
expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isTrue);
expect(tileNode.hasPrimaryFocus, isTrue);
});
testWidgets('SwitchListTile onFocusChange callback', (WidgetTester tester) async {
final FocusNode node = FocusNode(debugLabel: 'SwitchListTile onFocusChange');
bool gotFocus = false;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: SwitchListTile(
value: true,
focusNode: node,
onFocusChange: (bool focused) {
gotFocus = focused;
},
onChanged: (bool value) {},
),
),
),
);
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('SwitchListTile.adaptive onFocusChange Callback', (WidgetTester tester) async {
final FocusNode node = FocusNode(debugLabel: 'SwitchListTile.adaptive onFocusChange');
bool gotFocus = false;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: SwitchListTile.adaptive(
value: true,
focusNode: node,
onFocusChange: (bool focused) {
gotFocus = focused;
},
onChanged: (bool value) {},
),
),
),
);
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();
});
group('feedback', () {
late FeedbackTester feedback;
setUp(() {
feedback = FeedbackTester();
});
tearDown(() {
feedback.dispose();
});
testWidgets('SwitchListTile respects enableFeedback', (WidgetTester tester) async {
Future<void> buildTest(bool enableFeedback) async {
return tester.pumpWidget(
wrap(
child: Center(
child: SwitchListTile(
value: false,
onChanged: (bool? value) {},
enableFeedback: enableFeedback,
),
),
),
);
}
await buildTest(false);
await tester.tap(find.byType(SwitchListTile));
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 0);
expect(feedback.hapticCount, 0);
await buildTest(true);
await tester.tap(find.byType(SwitchListTile));
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
});
});
testWidgets('SwitchListTile respects hoverColor', (WidgetTester tester) async {
const Key key = Key('test');
await tester.pumpWidget(
wrap(
child: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Container(
width: 500,
height: 100,
color: Colors.white,
child: SwitchListTile(
value: false,
key: key,
hoverColor: Colors.orange[500],
title: const Text('A'),
onChanged: (bool? value) {},
),
);
}),
),
),
);
// Start hovering
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byKey(key)));
await tester.pump();
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byKey(key))),
paints..rect()..rect(
color: Colors.orange[500],
rect: const Rect.fromLTRB(150.0, 250.0, 650.0, 350.0),
)
);
});
testWidgets('Material2 - SwitchListTile respects thumbColor in active/enabled states', (WidgetTester tester) async {
const Color activeEnabledThumbColor = Color(0xFF000001);
const Color activeDisabledThumbColor = Color(0xFF000002);
const Color inactiveEnabledThumbColor = Color(0xFF000003);
const Color inactiveDisabledThumbColor = Color(0xFF000004);
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledThumbColor;
}
return inactiveDisabledThumbColor;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledThumbColor;
}
return inactiveEnabledThumbColor;
}
final MaterialStateProperty<Color> thumbColor = MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitchListTile({required bool enabled, required bool selected}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
value: selected,
thumbColor: thumbColor,
onChanged: enabled ? (_) { } : null,
);
}),
),
);
}
await tester.pumpWidget(buildSwitchListTile(enabled: false, selected: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect()..rrect()..rrect()..rrect(color: inactiveDisabledThumbColor)
);
await tester.pumpWidget(buildSwitchListTile(enabled: false, selected: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect()..rrect()..rrect()..rrect(color: activeDisabledThumbColor)
);
await tester.pumpWidget(buildSwitchListTile(enabled: true, selected: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect()..rrect()..rrect()..rrect(color: inactiveEnabledThumbColor)
);
await tester.pumpWidget(buildSwitchListTile(enabled: true, selected: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect()..rrect()..rrect()..rrect(color: activeEnabledThumbColor)
);
});
testWidgets('Material3 - SwitchListTile respects thumbColor in active/enabled states', (WidgetTester tester) async {
const Color activeEnabledThumbColor = Color(0xFF000001);
const Color activeDisabledThumbColor = Color(0xFF000002);
const Color inactiveEnabledThumbColor = Color(0xFF000003);
const Color inactiveDisabledThumbColor = Color(0xFF000004);
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledThumbColor;
}
return inactiveDisabledThumbColor;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledThumbColor;
}
return inactiveEnabledThumbColor;
}
final MaterialStateProperty<Color> thumbColor = MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitchListTile({required bool enabled, required bool selected}) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
value: selected,
thumbColor: thumbColor,
onChanged: enabled ? (_) { } : null,
);
}),
),
);
}
await tester.pumpWidget(buildSwitchListTile(enabled: false, selected: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect(color: inactiveDisabledThumbColor),
);
await tester.pumpWidget(buildSwitchListTile(enabled: false, selected: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect(color: activeDisabledThumbColor),
);
await tester.pumpWidget(buildSwitchListTile(enabled: true, selected: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect(color: inactiveEnabledThumbColor),
);
await tester.pumpWidget(buildSwitchListTile(enabled: true, selected: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect(color: activeEnabledThumbColor),
);
});
testWidgets('Material2 - SwitchListTile respects thumbColor in hovered/pressed states', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredThumbColor = Color(0xFF4caf50);
const Color pressedThumbColor = Color(0xFFF44336);
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedThumbColor;
}
if (states.contains(MaterialState.hovered)) {
return hoveredThumbColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> thumbColor = MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitchListTile() {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
value: false,
thumbColor: thumbColor,
onChanged: (_) { },
);
}),
),
);
}
await tester.pumpWidget(buildSwitchListTile());
await tester.pumpAndSettle();
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect()..rrect()..rrect()..rrect(color: hoveredThumbColor),
);
// On pressed state
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect()..rrect()..rrect()..rrect(color: pressedThumbColor),
);
});
testWidgets('Material3 - SwitchListTile respects thumbColor in hovered/pressed states', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredThumbColor = Color(0xFF4caf50);
const Color pressedThumbColor = Color(0xFFF44336);
Color getThumbColor(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedThumbColor;
}
if (states.contains(MaterialState.hovered)) {
return hoveredThumbColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> thumbColor = MaterialStateColor.resolveWith(getThumbColor);
Widget buildSwitchListTile() {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
value: false,
thumbColor: thumbColor,
onChanged: (_) { },
);
}),
),
);
}
await tester.pumpWidget(buildSwitchListTile());
await tester.pumpAndSettle();
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect(color: hoveredThumbColor),
);
// On pressed state
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect()..rrect(color: pressedThumbColor),
);
});
testWidgets('SwitchListTile respects trackColor in active/enabled states', (WidgetTester tester) async {
const Color activeEnabledTrackColor = Color(0xFF000001);
const Color activeDisabledTrackColor = Color(0xFF000002);
const Color inactiveEnabledTrackColor = Color(0xFF000003);
const Color inactiveDisabledTrackColor = Color(0xFF000004);
Color getTrackColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledTrackColor;
}
return inactiveDisabledTrackColor;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledTrackColor;
}
return inactiveEnabledTrackColor;
}
final MaterialStateProperty<Color> trackColor = MaterialStateColor.resolveWith(getTrackColor);
Widget buildSwitchListTile({required bool enabled, required bool selected}) {
return wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
value: selected,
trackColor: trackColor,
onChanged: enabled ? (_) { } : null,
);
}),
);
}
await tester.pumpWidget(buildSwitchListTile(enabled: false, selected: false));
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(color: inactiveDisabledTrackColor),
);
await tester.pumpWidget(buildSwitchListTile(enabled: false, selected: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(color: activeDisabledTrackColor),
);
await tester.pumpWidget(buildSwitchListTile(enabled: true, selected: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(color: inactiveEnabledTrackColor),
);
await tester.pumpWidget(buildSwitchListTile(enabled: true, selected: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(color: activeEnabledTrackColor),
);
});
testWidgets('SwitchListTile respects trackColor in hovered states', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredTrackColor = Color(0xFF4caf50);
Color getTrackColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoveredTrackColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> trackColor = MaterialStateColor.resolveWith(getTrackColor);
Widget buildSwitchListTile() {
return wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
value: false,
trackColor: trackColor,
onChanged: (_) { },
);
}),
);
}
await tester.pumpWidget(buildSwitchListTile());
await tester.pumpAndSettle();
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(color: hoveredTrackColor),
);
});
testWidgets('SwitchListTile respects thumbIcon - M3', (WidgetTester tester) async {
const Icon activeIcon = Icon(Icons.check);
const Icon inactiveIcon = Icon(Icons.close);
MaterialStateProperty<Icon?> thumbIcon(Icon? activeIcon, Icon? inactiveIcon) {
return MaterialStateProperty.resolveWith<Icon?>((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return activeIcon;
}
return inactiveIcon;
});
}
Widget buildSwitchListTile({required bool enabled, required bool active, Icon? activeIcon, Icon? inactiveIcon}) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
thumbIcon: thumbIcon(activeIcon, inactiveIcon),
value: active,
onChanged: enabled ? (_) {} : null,
);
}),
),
);
}
// active icon shows when switch is on.
await tester.pumpWidget(buildSwitchListTile(enabled: true, active: true, activeIcon: activeIcon));
await tester.pumpAndSettle();
final Switch switchWidget0 = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget0.thumbIcon?.resolve(<MaterialState>{MaterialState.selected}), activeIcon);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()
..paragraph(offset: const Offset(32.0, 12.0)),
);
// inactive icon shows when switch is off.
await tester.pumpWidget(buildSwitchListTile(enabled: true, active: false, inactiveIcon: inactiveIcon));
await tester.pumpAndSettle();
final Switch switchWidget1 = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget1.thumbIcon?.resolve(<MaterialState>{}), inactiveIcon);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()
..rrect()
..paragraph(offset: const Offset(12.0, 12.0)),
);
// active icon doesn't show when switch is off.
await tester.pumpWidget(buildSwitchListTile(enabled: true, active: false, activeIcon: activeIcon));
await tester.pumpAndSettle();
final Switch switchWidget2 = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget2.thumbIcon?.resolve(<MaterialState>{MaterialState.selected}), activeIcon);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()..rrect()
);
// inactive icon doesn't show when switch is on.
await tester.pumpWidget(buildSwitchListTile(enabled: true, active: true, inactiveIcon: inactiveIcon));
await tester.pumpAndSettle();
final Switch switchWidget3 = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget3.thumbIcon?.resolve(<MaterialState>{}), inactiveIcon);
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()..restore(),
);
// without icon
await tester.pumpWidget(buildSwitchListTile(enabled: true, active: false));
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()..rrect()..rrect()..restore(),
);
});
testWidgets('Material2 - SwitchListTile respects materialTapTargetSize', (WidgetTester tester) async {
Widget buildSwitchListTile(MaterialTapTargetSize materialTapTargetSize) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
materialTapTargetSize: materialTapTargetSize,
value: false,
onChanged: (_) {},
);
}),
),
);
}
await tester.pumpWidget(buildSwitchListTile(MaterialTapTargetSize.padded));
final Switch switchWidget = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget.materialTapTargetSize, MaterialTapTargetSize.padded);
expect(tester.getSize(find.byType(Switch)), const Size(59.0, 48.0));
await tester.pumpWidget(buildSwitchListTile(MaterialTapTargetSize.shrinkWrap));
final Switch switchWidget1 = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget1.materialTapTargetSize, MaterialTapTargetSize.shrinkWrap);
expect(tester.getSize(find.byType(Switch)), const Size(59.0, 40.0));
});
testWidgets('Material3 - SwitchListTile respects materialTapTargetSize', (WidgetTester tester) async {
Widget buildSwitchListTile(MaterialTapTargetSize materialTapTargetSize) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
materialTapTargetSize: materialTapTargetSize,
value: false,
onChanged: (_) {},
);
}),
),
);
}
await tester.pumpWidget(buildSwitchListTile(MaterialTapTargetSize.padded));
final Switch switchWidget = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget.materialTapTargetSize, MaterialTapTargetSize.padded);
expect(tester.getSize(find.byType(Switch)), const Size(60.0, 48.0));
await tester.pumpWidget(buildSwitchListTile(MaterialTapTargetSize.shrinkWrap));
final Switch switchWidget1 = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget1.materialTapTargetSize, MaterialTapTargetSize.shrinkWrap);
expect(tester.getSize(find.byType(Switch)), const Size(60.0, 40.0));
});
testWidgets('Material2 - SwitchListTile.adaptive respects applyCupertinoTheme', (WidgetTester tester) async {
Widget buildSwitchListTile(bool applyCupertinoTheme, TargetPlatform platform) {
return MaterialApp(
theme: ThemeData(useMaterial3: false, platform: platform),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile.adaptive(
applyCupertinoTheme: applyCupertinoTheme,
value: true,
onChanged: (_) {},
);
}),
),
);
}
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
await tester.pumpWidget(buildSwitchListTile(true, platform));
await tester.pumpAndSettle();
expect(find.byType(Switch), findsOneWidget);
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(color: const Color(0xFF2196F3)),
);
await tester.pumpWidget(buildSwitchListTile(false, platform));
await tester.pumpAndSettle();
expect(find.byType(Switch), findsOneWidget);
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(color: const Color(0xFF34C759)),
);
}
});
testWidgets('Material3 - SwitchListTile.adaptive respects applyCupertinoTheme', (WidgetTester tester) async {
Widget buildSwitchListTile(bool applyCupertinoTheme, TargetPlatform platform) {
return MaterialApp(
theme: ThemeData(useMaterial3: true, platform: platform),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile.adaptive(
applyCupertinoTheme: applyCupertinoTheme,
value: true,
onChanged: (_) {},
);
}),
),
);
}
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
await tester.pumpWidget(buildSwitchListTile(true, platform));
await tester.pumpAndSettle();
expect(find.byType(Switch), findsOneWidget);
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(color: const Color(0xFF6750A4)),
);
await tester.pumpWidget(buildSwitchListTile(false, platform));
await tester.pumpAndSettle();
expect(find.byType(Switch), findsOneWidget);
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(color: const Color(0xFF34C759)),
);
}
});
testWidgets('Material2 - SwitchListTile respects materialTapTargetSize', (WidgetTester tester) async {
Widget buildSwitchListTile(MaterialTapTargetSize materialTapTargetSize) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
materialTapTargetSize: materialTapTargetSize,
value: false,
onChanged: (_) {},
);
}),
),
);
}
await tester.pumpWidget(buildSwitchListTile(MaterialTapTargetSize.padded));
final Switch switchWidget = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget.materialTapTargetSize, MaterialTapTargetSize.padded);
expect(tester.getSize(find.byType(Switch)), const Size(59.0, 48.0));
await tester.pumpWidget(buildSwitchListTile(MaterialTapTargetSize.shrinkWrap));
final Switch switchWidget1 = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget1.materialTapTargetSize, MaterialTapTargetSize.shrinkWrap);
expect(tester.getSize(find.byType(Switch)), const Size(59.0, 40.0));
});
testWidgets('Material3 - SwitchListTile respects materialTapTargetSize', (WidgetTester tester) async {
Widget buildSwitchListTile(MaterialTapTargetSize materialTapTargetSize) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Material(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
materialTapTargetSize: materialTapTargetSize,
value: false,
onChanged: (_) {},
);
}),
),
);
}
await tester.pumpWidget(buildSwitchListTile(MaterialTapTargetSize.padded));
final Switch switchWidget = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget.materialTapTargetSize, MaterialTapTargetSize.padded);
expect(tester.getSize(find.byType(Switch)), const Size(60.0, 48.0));
await tester.pumpWidget(buildSwitchListTile(MaterialTapTargetSize.shrinkWrap));
final Switch switchWidget1 = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget1.materialTapTargetSize, MaterialTapTargetSize.shrinkWrap);
expect(tester.getSize(find.byType(Switch)), const Size(60.0, 40.0));
});
testWidgets('SwitchListTile passes the value of dragStartBehavior to Switch', (WidgetTester tester) async {
Widget buildSwitchListTile(DragStartBehavior dragStartBehavior) {
return wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
dragStartBehavior: dragStartBehavior,
value: false,
onChanged: (_) {},
);
}),
);
}
await tester.pumpWidget(buildSwitchListTile(DragStartBehavior.start));
final Switch switchWidget = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget.dragStartBehavior, DragStartBehavior.start);
await tester.pumpWidget(buildSwitchListTile(DragStartBehavior.down));
final Switch switchWidget1 = tester.widget<Switch>(find.byType(Switch));
expect(switchWidget1.dragStartBehavior, DragStartBehavior.down);
});
testWidgets('Switch on SwitchListTile changes mouse cursor when hovered', (WidgetTester tester) async {
// Test SwitchListTile.adaptive() constructor
await tester.pumpWidget(wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile.adaptive(
mouseCursor: SystemMouseCursors.text,
value: false,
onChanged: (_) {},
);
}),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(Switch)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test SwitchListTile() constructor
await tester.pumpWidget(wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
mouseCursor: SystemMouseCursors.forbidden,
value: false,
onChanged: (_) {},
);
}),
));
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden);
// Test default cursor
await tester.pumpWidget(wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
value: false,
onChanged: (_) {},
);
}),
));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test default cursor when disabled
await tester.pumpWidget(wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return const SwitchListTile(
value: false,
onChanged: null,
);
}),
));
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('Switch with splash radius set', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const double splashRadius = 35;
await tester.pumpWidget(wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
splashRadius: splashRadius,
value: false,
onChanged: (_) {},
);
}),
));
await tester.pumpAndSettle();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..circle(radius: splashRadius),
);
});
testWidgets('The overlay color for the thumb of the switch resolves in active/pressed/hovered states', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color activeThumbColor = Color(0xFF000000);
const Color inactiveThumbColor = Color(0xFF000010);
const Color activePressedOverlayColor = Color(0xFF000001);
const Color inactivePressedOverlayColor = Color(0xFF000002);
const Color hoverOverlayColor = Color(0xFF000003);
const Color hoverColor = Color(0xFF000005);
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;
}
return null;
}
Widget buildSwitch({bool active = false, bool focused = false, bool useOverlay = true}) {
return MaterialApp(
home: Scaffold(
body: SwitchListTile(
value: active,
onChanged: (_) { },
thumbColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return activeThumbColor;
}
return inactiveThumbColor;
}),
overlayColor: useOverlay ? MaterialStateProperty.resolveWith(getOverlayColor) : null,
hoverColor: hoverColor,
),
),
);
}
// test inactive Switch, and overlayColor is set to null.
await tester.pumpWidget(buildSwitch(useOverlay: false));
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: inactiveThumbColor.withAlpha(kRadialReactionAlpha),
),
reason: 'Default inactive pressed Switch should have overlay color from thumbColor',
);
// test active Switch, and overlayColor is set to null.
await tester.pumpWidget(buildSwitch(active: true, useOverlay: false));
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: activeThumbColor.withAlpha(kRadialReactionAlpha),
),
reason: 'Default active pressed Switch should have overlay color from thumbColor',
);
// test inactive Switch with an overlayColor
await tester.pumpWidget(buildSwitch());
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: inactivePressedOverlayColor,
),
reason: 'Inactive pressed Switch should have overlay color: $inactivePressedOverlayColor',
);
// test active Switch with an overlayColor
await tester.pumpWidget(buildSwitch(active: true));
await tester.press(find.byType(Switch));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: activePressedOverlayColor,
),
reason: 'Active pressed Switch should have overlay color: $activePressedOverlayColor',
);
await tester.pumpWidget(buildSwitch(focused: true));
await tester.pumpAndSettle();
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints
..rrect()
..circle(
color: hoverOverlayColor,
),
reason: 'Hovered Switch should use overlay color $hoverOverlayColor over $hoverColor',
);
});
testWidgets('SwitchListTile respects trackOutlineColor in active/enabled states', (WidgetTester tester) async {
const Color activeEnabledTrackOutlineColor = Color(0xFF000001);
const Color activeDisabledTrackOutlineColor = Color(0xFF000002);
const Color inactiveEnabledTrackOutlineColor = Color(0xFF000003);
const Color inactiveDisabledTrackOutlineColor = Color(0xFF000004);
Color getOutlineColor(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
if (states.contains(MaterialState.selected)) {
return activeDisabledTrackOutlineColor;
}
return inactiveDisabledTrackOutlineColor;
}
if (states.contains(MaterialState.selected)) {
return activeEnabledTrackOutlineColor;
}
return inactiveEnabledTrackOutlineColor;
}
final MaterialStateProperty<Color> trackOutlineColor = MaterialStateColor.resolveWith(getOutlineColor);
Widget buildSwitchListTile({required bool enabled, required bool selected}) {
return wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
value: selected,
trackOutlineColor: trackOutlineColor,
onChanged: enabled ? (_) { } : null,
);
}),
);
}
await tester.pumpWidget(buildSwitchListTile(enabled: false, selected: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: inactiveDisabledTrackOutlineColor, style: PaintingStyle.stroke),
);
await tester.pumpWidget(buildSwitchListTile(enabled: false, selected: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: activeDisabledTrackOutlineColor, style: PaintingStyle.stroke),
);
await tester.pumpWidget(buildSwitchListTile(enabled: true, selected: false));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: inactiveEnabledTrackOutlineColor, style: PaintingStyle.stroke),
);
await tester.pumpWidget(buildSwitchListTile(enabled: true, selected: true));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect(style: PaintingStyle.fill)
..rrect(color: activeEnabledTrackOutlineColor, style: PaintingStyle.stroke),
);
});
testWidgets('SwitchListTile respects trackOutlineColor in hovered state', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
const Color hoveredTrackColor = Color(0xFF4caf50);
Color getTrackOutlineColor(Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return hoveredTrackColor;
}
return Colors.transparent;
}
final MaterialStateProperty<Color> outlineColor = MaterialStateColor.resolveWith(getTrackOutlineColor);
Widget buildSwitchListTile() {
return MaterialApp(
theme: ThemeData(),
home: wrap(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return SwitchListTile(
value: false,
trackOutlineColor: outlineColor,
onChanged: (_) { },
);
}),
),
);
}
await tester.pumpWidget(buildSwitchListTile());
await tester.pumpAndSettle();
// Start hovering
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.byType(Switch)));
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.byType(Switch))),
paints..rrect()..rrect(color: hoveredTrackColor, style: PaintingStyle.stroke)
);
});
testWidgets('SwitchListTile.control widget should not request focus on traversal', (WidgetTester tester) async {
final GlobalKey firstChildKey = GlobalKey();
final GlobalKey secondChildKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
SwitchListTile(
value: true,
onChanged: (bool? value) {},
title: Text('Hey', key: firstChildKey),
),
SwitchListTile(
value: true,
onChanged: (bool? value) {},
title: Text('There', key: secondChildKey),
),
],
),
),
),
);
await tester.pump();
Focus.of(firstChildKey.currentContext!).requestFocus();
await tester.pump();
expect(Focus.of(firstChildKey.currentContext!).hasPrimaryFocus, isTrue);
Focus.of(firstChildKey.currentContext!).nextFocus();
await tester.pump();
expect(Focus.of(firstChildKey.currentContext!).hasPrimaryFocus, isFalse);
expect(Focus.of(secondChildKey.currentContext!).hasPrimaryFocus, isTrue);
});
}
| flutter/packages/flutter/test/material/switch_list_tile_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/switch_list_tile_test.dart",
"repo_id": "flutter",
"token_count": 24214
} | 677 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/clipboard_utils.dart';
import '../widgets/editable_text_utils.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final MockClipboard mockClipboard = MockClipboard();
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
setUp(() async {
// Fill the clipboard so that the Paste option is available in the text
// selection menu.
await Clipboard.setData(const ClipboardData(text: 'Clipboard data'));
});
testWidgets('can use the desktop cut/copy/paste buttons on Mac', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(
text: 'blah1 blah2',
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
controller: controller,
),
),
),
),
);
// Initially, the menu is not shown and there is no selection.
expect(find.byType(CupertinoButton), findsNothing);
expect(controller.selection, const TextSelection(baseOffset: -1, extentOffset: -1));
final Offset midBlah1 = textOffsetToPosition(tester, 2);
// Right clicking shows the menu.
final TestGesture gesture = await tester.startGesture(
midBlah1,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5));
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
// Copy the first word.
await tester.tap(find.text('Copy'));
await tester.pumpAndSettle();
expect(controller.text, 'blah1 blah2');
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5));
expect(find.byType(CupertinoButton), findsNothing);
// Paste it at the end.
await gesture.down(textOffsetToPosition(tester, controller.text.length));
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(controller.selection, const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream));
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
await tester.tap(find.text('Paste'));
await tester.pumpAndSettle();
expect(controller.text, 'blah1 blah2blah1');
expect(controller.selection, const TextSelection.collapsed(offset: 16));
// Cut the first word.
await gesture.down(midBlah1);
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5));
await tester.tap(find.text('Cut'));
await tester.pumpAndSettle();
expect(controller.text, ' blah2blah1');
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 0));
expect(find.byType(CupertinoButton), findsNothing);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }),
skip: kIsWeb, // [intended] we don't supply the cut/copy/paste buttons on the web.
);
testWidgets('can use the desktop cut/copy/paste buttons on Windows and Linux', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(
text: 'blah1 blah2',
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
controller: controller,
),
),
),
),
);
// Initially, the menu is not shown and there is no selection.
expect(find.byType(CupertinoButton), findsNothing);
expect(controller.selection, const TextSelection(baseOffset: -1, extentOffset: -1));
final Offset midBlah1 = textOffsetToPosition(tester, 2);
// Right clicking shows the menu.
TestGesture gesture = await tester.startGesture(
midBlah1,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
expect(controller.selection, const TextSelection.collapsed(offset: 2));
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
// Double tap to select the first word, then right click to show the menu.
final Offset startBlah1 = textOffsetToPosition(tester, 0);
gesture = await tester.startGesture(
startBlah1,
kind: PointerDeviceKind.mouse,
);
await tester.pump();
await gesture.up();
await tester.pump(const Duration(milliseconds: 100));
await gesture.down(startBlah1);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5));
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
gesture = await tester.startGesture(
midBlah1,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
// Copy the first word.
await tester.tap(find.text('Copy'));
await tester.pumpAndSettle();
expect(controller.text, 'blah1 blah2');
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5));
expect(find.byType(CupertinoButton), findsNothing);
// Paste it at the end.
gesture = await tester.startGesture(
textOffsetToPosition(tester, controller.text.length),
kind: PointerDeviceKind.mouse,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
expect(controller.selection, const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream));
gesture = await tester.startGesture(
textOffsetToPosition(tester, controller.text.length),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
expect(controller.selection, const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream));
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
await tester.tap(find.text('Paste'));
await tester.pumpAndSettle();
expect(controller.text, 'blah1 blah2blah1');
expect(controller.selection, const TextSelection.collapsed(offset: 16));
// Cut the first word.
gesture = await tester.startGesture(
midBlah1,
kind: PointerDeviceKind.mouse,
);
await tester.pump();
await gesture.up();
await tester.pump(const Duration(milliseconds: 100));
await gesture.down(startBlah1);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5));
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
gesture = await tester.startGesture(
textOffsetToPosition(tester, controller.text.length),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
await tester.tap(find.text('Cut'));
await tester.pumpAndSettle();
expect(controller.text, ' blah2blah1');
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 0));
expect(find.byType(CupertinoButton), findsNothing);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.linux, TargetPlatform.windows }),
skip: kIsWeb, // [intended] we don't supply the cut/copy/paste buttons on the web.
);
testWidgets(
'$SelectionOverlay is not leaking',
(WidgetTester tester) async {
final TextEditingController controller = TextEditingController(
text: 'blah1 blah2',
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextField(
controller: controller,
),
),
),
),
);
final Offset startBlah1 = textOffsetToPosition(tester, 0);
await tester.tapAt(startBlah1);
await tester.pump(const Duration(milliseconds: 100));
await tester.tapAt(startBlah1);
await tester.pumpAndSettle();
await tester.pump();
},
skip: kIsWeb, // [intended] we don't supply the cut/copy/paste buttons on the web.
);
testWidgets('the desktop cut/copy/paste buttons are disabled for read-only obscured form fields', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(
text: 'blah1 blah2',
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
readOnly: true,
obscureText: true,
controller: controller,
),
),
),
),
);
// Initially, the menu is not shown and there is no selection.
expect(find.byType(CupertinoButton), findsNothing);
const TextSelection invalidSelection = TextSelection(baseOffset: -1, extentOffset: -1);
expect(controller.selection, invalidSelection);
final Offset midBlah1 = textOffsetToPosition(tester, 2);
// Right clicking shows the menu.
final TestGesture gesture = await tester.startGesture(
midBlah1,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(controller.selection, invalidSelection);
expect(find.text('Copy'), findsNothing);
expect(find.text('Cut'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.byType(CupertinoButton), findsNothing);
},
variant: TargetPlatformVariant.desktop(),
skip: kIsWeb, // [intended] we don't supply the cut/copy/paste buttons on the web.
);
testWidgets('the desktop cut/copy buttons are disabled for obscured form fields', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(
text: 'blah1 blah2',
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
obscureText: true,
controller: controller,
),
),
),
),
);
// Initially, the menu is not shown and there is no selection.
expect(find.byType(CupertinoButton), findsNothing);
const TextSelection invalidSelection = TextSelection(baseOffset: -1, extentOffset: -1);
expect(controller.selection, invalidSelection);
final Offset midBlah1 = textOffsetToPosition(tester, 2);
// Make a selection.
await tester.tapAt(midBlah1);
await tester.pump();
await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
await tester.pump();
expect(controller.selection, const TextSelection(baseOffset: 2, extentOffset: 0));
// Right clicking shows the menu.
final TestGesture gesture = await tester.startGesture(
midBlah1,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
expect(find.text('Copy'), findsNothing);
expect(find.text('Cut'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
},
variant: TargetPlatformVariant.desktop(),
skip: kIsWeb, // [intended] we don't supply the cut/copy/paste buttons on the web.
);
testWidgets('TextFormField accepts TextField.noMaxLength as value to maxLength parameter', (WidgetTester tester) async {
bool asserted;
try {
TextFormField(
maxLength: TextField.noMaxLength,
);
asserted = false;
} catch (e) {
asserted = true;
}
expect(asserted, false);
});
testWidgets('Passes textAlign to underlying TextField', (WidgetTester tester) async {
const TextAlign alignment = TextAlign.center;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
textAlign: alignment,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.textAlign, alignment);
});
testWidgets('Passes scrollPhysics to underlying TextField', (WidgetTester tester) async {
const ScrollPhysics scrollPhysics = ScrollPhysics();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
scrollPhysics: scrollPhysics,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.scrollPhysics, scrollPhysics);
});
testWidgets('Passes textAlignVertical to underlying TextField', (WidgetTester tester) async {
const TextAlignVertical textAlignVertical = TextAlignVertical.bottom;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
textAlignVertical: textAlignVertical,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.textAlignVertical, textAlignVertical);
});
testWidgets('Passes textInputAction to underlying TextField', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
textInputAction: TextInputAction.next,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.textInputAction, TextInputAction.next);
});
testWidgets('Passes onEditingComplete to underlying TextField', (WidgetTester tester) async {
void onEditingComplete() { }
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
onEditingComplete: onEditingComplete,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.onEditingComplete, onEditingComplete);
});
testWidgets('Passes cursor attributes to underlying TextField', (WidgetTester tester) async {
const double cursorWidth = 3.14;
const double cursorHeight = 6.28;
const Radius cursorRadius = Radius.circular(4);
const Color cursorColor = Colors.purple;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
cursorWidth: cursorWidth,
cursorHeight: cursorHeight,
cursorRadius: cursorRadius,
cursorColor: cursorColor,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.cursorWidth, cursorWidth);
expect(textFieldWidget.cursorHeight, cursorHeight);
expect(textFieldWidget.cursorRadius, cursorRadius);
expect(textFieldWidget.cursorColor, cursorColor);
});
testWidgets('onFieldSubmit callbacks are called', (WidgetTester tester) async {
bool called = false;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
onFieldSubmitted: (String value) { called = true; },
),
),
),
),
);
await tester.showKeyboard(find.byType(TextField));
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pump();
expect(called, true);
});
testWidgets('onChanged callbacks are called', (WidgetTester tester) async {
late String value;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
onChanged: (String v) {
value = v;
},
),
),
),
),
);
await tester.enterText(find.byType(TextField), 'Soup');
await tester.pump();
expect(value, 'Soup');
});
testWidgets('autovalidateMode is passed to super', (WidgetTester tester) async {
int validateCalled = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
autovalidateMode: AutovalidateMode.always,
validator: (String? value) {
validateCalled++;
return null;
},
),
),
),
),
);
expect(validateCalled, 1);
await tester.enterText(find.byType(TextField), 'a');
await tester.pump();
expect(validateCalled, 2);
});
testWidgets('validate is called if widget is enabled', (WidgetTester tester) async {
int validateCalled = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
enabled: true,
autovalidateMode: AutovalidateMode.always,
validator: (String? value) {
validateCalled += 1;
return null;
},
),
),
),
),
);
expect(validateCalled, 1);
await tester.enterText(find.byType(TextField), 'a');
await tester.pump();
expect(validateCalled, 2);
});
testWidgets('Disabled field hides helper and counter in M2', (WidgetTester tester) async {
const String helperText = 'helper text';
const String counterText = 'counter text';
const String errorText = 'error text';
Widget buildFrame(bool enabled, bool hasError) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: TextFormField(
decoration: InputDecoration(
labelText: 'label text',
helperText: helperText,
counterText: counterText,
errorText: hasError ? errorText : null,
enabled: enabled,
),
),
),
),
);
}
// When enabled is true, the helper/error and counter are visible.
await tester.pumpWidget(buildFrame(true, false));
Text helperWidget = tester.widget(find.text(helperText));
Text counterWidget = tester.widget(find.text(counterText));
expect(helperWidget.style!.color, isNot(equals(Colors.transparent)));
expect(counterWidget.style!.color, isNot(equals(Colors.transparent)));
await tester.pumpWidget(buildFrame(true, true));
counterWidget = tester.widget(find.text(counterText));
Text errorWidget = tester.widget(find.text(errorText));
expect(helperWidget.style!.color, isNot(equals(Colors.transparent)));
expect(errorWidget.style!.color, isNot(equals(Colors.transparent)));
// When enabled is false, the helper/error and counter are not visible.
await tester.pumpWidget(buildFrame(false, false));
helperWidget = tester.widget(find.text(helperText));
counterWidget = tester.widget(find.text(counterText));
expect(helperWidget.style!.color, equals(Colors.transparent));
expect(counterWidget.style!.color, equals(Colors.transparent));
await tester.pumpWidget(buildFrame(false, true));
errorWidget = tester.widget(find.text(errorText));
counterWidget = tester.widget(find.text(counterText));
expect(counterWidget.style!.color, equals(Colors.transparent));
expect(errorWidget.style!.color, equals(Colors.transparent));
});
testWidgets('passing a buildCounter shows returned widget', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Material(
child: Center(
child: TextFormField(
buildCounter: (BuildContext context, { int? currentLength, int? maxLength, bool? isFocused }) {
return Text('$currentLength of $maxLength');
},
maxLength: 10,
),
),
),
),
);
expect(find.text('0 of 10'), findsOneWidget);
await tester.enterText(find.byType(TextField), '01234');
await tester.pump();
expect(find.text('5 of 10'), findsOneWidget);
});
testWidgets('readonly text form field will hide cursor by default', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
initialValue: 'readonly',
readOnly: true,
),
),
),
),
);
await tester.showKeyboard(find.byType(TextFormField));
expect(tester.testTextInput.hasAnyClients, false);
await tester.tap(find.byType(TextField));
await tester.pump();
expect(tester.testTextInput.hasAnyClients, false);
await tester.longPress(find.byType(TextFormField));
await tester.pump();
// Context menu should not have paste.
expect(find.text('Select all'), findsOneWidget);
expect(find.text('Paste'), findsNothing);
final EditableTextState editableTextState = tester.firstState(find.byType(EditableText));
final RenderEditable renderEditable = editableTextState.renderEditable;
// Make sure it does not paint caret for a period of time.
await tester.pump(const Duration(milliseconds: 200));
expect(renderEditable, paintsExactlyCountTimes(#drawRect, 0));
await tester.pump(const Duration(milliseconds: 200));
expect(renderEditable, paintsExactlyCountTimes(#drawRect, 0));
await tester.pump(const Duration(milliseconds: 200));
expect(renderEditable, paintsExactlyCountTimes(#drawRect, 0));
}, skip: isBrowser); // [intended] We do not use Flutter-rendered context menu on the Web.
testWidgets('onTap is called upon tap', (WidgetTester tester) async {
int tapCount = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
onTap: () {
tapCount += 1;
},
),
),
),
),
);
expect(tapCount, 0);
await tester.tap(find.byType(TextField));
// Wait a bit so they're all single taps and not double taps.
await tester.pump(const Duration(milliseconds: 300));
await tester.tap(find.byType(TextField));
await tester.pump(const Duration(milliseconds: 300));
await tester.tap(find.byType(TextField));
await tester.pump(const Duration(milliseconds: 300));
expect(tapCount, 3);
});
testWidgets('onTapOutside is called upon tap outside', (WidgetTester tester) async {
int tapOutsideCount = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Column(
children: <Widget>[
const Text('Outside'),
TextFormField(
autofocus: true,
onTapOutside: (PointerEvent event) {
tapOutsideCount += 1;
},
),
],
),
),
),
),
);
await tester.pump(); // Wait for autofocus to take effect.
expect(tapOutsideCount, 0);
await tester.tap(find.byType(TextFormField));
await tester.tap(find.text('Outside'));
await tester.tap(find.text('Outside'));
await tester.tap(find.text('Outside'));
expect(tapOutsideCount, 3);
});
// Regression test for https://github.com/flutter/flutter/issues/134341.
testWidgets('onTapOutside is not called upon tap outside when field is not focused', (WidgetTester tester) async {
int tapOutsideCount = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Column(
children: <Widget>[
const Text('Outside'),
TextFormField(
onTapOutside: (PointerEvent event) {
tapOutsideCount += 1;
},
),
],
),
),
),
),
);
await tester.pump();
expect(tapOutsideCount, 0);
await tester.tap(find.byType(TextFormField));
await tester.tap(find.text('Outside'));
await tester.tap(find.text('Outside'));
await tester.tap(find.text('Outside'));
expect(tapOutsideCount, 0);
});
// Regression test for https://github.com/flutter/flutter/issues/54472.
testWidgets('reset resets the text fields value to the initialValue', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
initialValue: 'initialValue',
),
),
),
),
);
await tester.enterText(find.byType(TextFormField), 'changedValue');
final FormFieldState<String> state = tester.state<FormFieldState<String>>(find.byType(TextFormField));
state.reset();
expect(find.text('changedValue'), findsNothing);
expect(find.text('initialValue'), findsOneWidget);
});
testWidgets('reset resets the text fields value to the controller initial value', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(text: 'initialValue');
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
controller: controller,
),
),
),
),
);
await tester.enterText(find.byType(TextFormField), 'changedValue');
final FormFieldState<String> state = tester.state<FormFieldState<String>>(find.byType(TextFormField));
state.reset();
expect(find.text('changedValue'), findsNothing);
expect(find.text('initialValue'), findsOneWidget);
});
// Regression test for https://github.com/flutter/flutter/issues/34847.
testWidgets("didChange resets the text field's value to empty when passed null", (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(),
),
),
),
);
await tester.enterText(find.byType(TextFormField), 'changedValue');
await tester.pump();
expect(find.text('changedValue'), findsOneWidget);
final FormFieldState<String> state = tester.state<FormFieldState<String>>(find.byType(TextFormField));
state.didChange(null);
expect(find.text('changedValue'), findsNothing);
expect(find.text(''), findsOneWidget);
});
// Regression test for https://github.com/flutter/flutter/issues/34847.
testWidgets("reset resets the text field's value to empty when initialValue is null", (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(),
),
),
),
);
await tester.enterText(find.byType(TextFormField), 'changedValue');
await tester.pump();
expect(find.text('changedValue'), findsOneWidget);
final FormFieldState<String> state = tester.state<FormFieldState<String>>(find.byType(TextFormField));
state.reset();
expect(find.text('changedValue'), findsNothing);
expect(find.text(''), findsOneWidget);
});
// Regression test for https://github.com/flutter/flutter/issues/54472.
testWidgets('didChange changes text fields value', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
initialValue: 'initialValue',
),
),
),
),
);
expect(find.text('initialValue'), findsOneWidget);
final FormFieldState<String> state = tester.state<FormFieldState<String>>(find.byType(TextFormField));
state.didChange('changedValue');
expect(find.text('initialValue'), findsNothing);
expect(find.text('changedValue'), findsOneWidget);
});
testWidgets('onChanged callbacks value and FormFieldState.value are sync', (WidgetTester tester) async {
bool called = false;
late FormFieldState<String> state;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
onChanged: (String value) {
called = true;
expect(value, state.value);
},
),
),
),
),
);
state = tester.state<FormFieldState<String>>(find.byType(TextFormField));
await tester.enterText(find.byType(TextField), 'Soup');
expect(called, true);
});
testWidgets('autofillHints is passed to super', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
autofillHints: const <String>[AutofillHints.countryName],
),
),
),
),
);
final TextField widget = tester.widget(find.byType(TextField));
expect(widget.autofillHints, equals(const <String>[AutofillHints.countryName]));
});
testWidgets('autovalidateMode is passed to super', (WidgetTester tester) async {
int validateCalled = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Scaffold(
body: TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (String? value) {
validateCalled++;
return null;
},
),
),
),
),
);
expect(validateCalled, 0);
await tester.enterText(find.byType(TextField), 'a');
await tester.pump();
expect(validateCalled, 1);
});
testWidgets('textSelectionControls is passed to super', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Scaffold(
body: TextFormField(
selectionControls: materialTextSelectionControls,
),
),
),
),
);
final TextField widget = tester.widget(find.byType(TextField));
expect(widget.selectionControls, equals(materialTextSelectionControls));
});
testWidgets('TextFormField respects hintTextDirection', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Material(
child: Directionality(
textDirection: TextDirection.rtl,
child: TextFormField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Some Label',
hintText: 'Some Hint',
hintTextDirection: TextDirection.ltr,
),
),
),
),
));
final Finder hintTextFinder = find.text('Some Hint');
final Text hintText = tester.firstWidget(hintTextFinder);
expect(hintText.textDirection, TextDirection.ltr);
await tester.pumpWidget(MaterialApp(
home: Material(
child: Directionality(
textDirection: TextDirection.rtl,
child: TextFormField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Some Label',
hintText: 'Some Hint',
),
),
),
),
));
final BuildContext context = tester.element(hintTextFinder);
final TextDirection textDirection = Directionality.of(context);
expect(textDirection, TextDirection.rtl);
});
testWidgets('Passes scrollController to underlying TextField', (WidgetTester tester) async {
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
scrollController: scrollController,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.scrollController, scrollController);
});
testWidgets('TextFormField changes mouse cursor when hovered', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: TextFormField(
mouseCursor: SystemMouseCursors.grab,
),
),
),
),
);
// Center, which is within the area
final Offset center = tester.getCenter(find.byType(TextFormField));
// Top left, which is also within the area
final Offset edge = tester.getTopLeft(find.byType(TextFormField)) + const Offset(1, 1);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: center);
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab);
// Test default cursor
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: TextFormField(),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
await gesture.moveTo(edge);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
await gesture.moveTo(center);
// Test default cursor when disabled
await tester.pumpWidget(
MaterialApp(
home: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: TextFormField(
enabled: false,
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
await gesture.moveTo(edge);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
await gesture.moveTo(center);
});
// Regression test for https://github.com/flutter/flutter/issues/101587.
testWidgets('Right clicking menu behavior', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController(
text: 'blah1 blah2',
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
controller: controller,
),
),
),
),
);
// Initially, the menu is not shown and there is no selection.
expect(find.byType(CupertinoButton), findsNothing);
expect(controller.selection, const TextSelection(baseOffset: -1, extentOffset: -1));
final Offset midBlah1 = textOffsetToPosition(tester, 2);
final Offset midBlah2 = textOffsetToPosition(tester, 8);
// Right click the second word.
final TestGesture gesture = await tester.startGesture(
midBlah2,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
expect(controller.selection, const TextSelection(baseOffset: 6, extentOffset: 11));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(controller.selection, const TextSelection.collapsed(offset: 8));
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsOneWidget);
expect(find.text('Select all'), findsOneWidget);
}
// Right click the first word.
await gesture.down(midBlah1);
await tester.pump();
await gesture.up();
await tester.pumpAndSettle();
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5));
expect(find.text('Cut'), findsOneWidget);
expect(find.text('Copy'), findsOneWidget);
expect(find.text('Paste'), findsOneWidget);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(controller.selection, const TextSelection.collapsed(offset: 8));
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
}
},
variant: TargetPlatformVariant.all(),
skip: kIsWeb, // [intended] we don't supply the cut/copy/paste buttons on the web.
);
testWidgets('spellCheckConfiguration passes through to EditableText', (WidgetTester tester) async {
final SpellCheckConfiguration mySpellCheckConfiguration = SpellCheckConfiguration(
spellCheckService: DefaultSpellCheckService(),
misspelledTextStyle: TextField.materialMisspelledTextStyle,
);
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: TextFormField(
spellCheckConfiguration: mySpellCheckConfiguration,
),
),
));
expect(find.byType(EditableText), findsOneWidget);
final EditableText editableText = tester.widget(find.byType(EditableText));
// Can't do equality comparison on spellCheckConfiguration itself because it
// will have been copied.
expect(
editableText.spellCheckConfiguration?.spellCheckService,
equals(mySpellCheckConfiguration.spellCheckService),
);
expect(
editableText.spellCheckConfiguration?.misspelledTextStyle,
equals(mySpellCheckConfiguration.misspelledTextStyle),
);
});
testWidgets('magnifierConfiguration passes through to EditableText', (WidgetTester tester) async {
final TextMagnifierConfiguration myTextMagnifierConfiguration = TextMagnifierConfiguration(
magnifierBuilder: (BuildContext context, MagnifierController controller, ValueNotifier<MagnifierInfo> notifier) {
return const Placeholder();
},
);
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: TextFormField(
magnifierConfiguration: myTextMagnifierConfiguration,
),
),
));
expect(find.byType(EditableText), findsOneWidget);
final EditableText editableText = tester.widget(find.byType(EditableText));
expect(editableText.magnifierConfiguration, equals(myTextMagnifierConfiguration));
});
testWidgets('Passes undoController to undoController TextField', (WidgetTester tester) async {
final UndoHistoryController undoController = UndoHistoryController(value: UndoHistoryValue.empty);
addTearDown(undoController.dispose);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
undoController: undoController,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.undoController, undoController);
});
testWidgets('Passes cursorOpacityAnimates to cursorOpacityAnimates TextField', (WidgetTester tester) async {
const bool cursorOpacityAnimates = true;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
cursorOpacityAnimates: cursorOpacityAnimates,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.cursorOpacityAnimates, cursorOpacityAnimates);
});
testWidgets('Passes contentInsertionConfiguration to contentInsertionConfiguration TextField', (WidgetTester tester) async {
final ContentInsertionConfiguration contentInsertionConfiguration =
ContentInsertionConfiguration(onContentInserted: (KeyboardInsertedContent value) {});
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
contentInsertionConfiguration: contentInsertionConfiguration,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.contentInsertionConfiguration, contentInsertionConfiguration);
});
testWidgets('Passes clipBehavior to clipBehavior TextField', (WidgetTester tester) async {
const Clip clipBehavior = Clip.antiAlias;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
clipBehavior: clipBehavior,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.clipBehavior, clipBehavior);
});
testWidgets('Passes scribbleEnabled to scribbleEnabled TextField', (WidgetTester tester) async {
const bool scribbleEnabled = false;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
scribbleEnabled: scribbleEnabled,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.scribbleEnabled, scribbleEnabled);
});
testWidgets('Passes canRequestFocus to canRequestFocus TextField', (WidgetTester tester) async {
const bool canRequestFocus = false;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
canRequestFocus: canRequestFocus,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.canRequestFocus, canRequestFocus);
});
testWidgets('Passes onAppPrivateCommand to onAppPrivateCommand TextField', (WidgetTester tester) async {
void onAppPrivateCommand(String action, Map<String, dynamic> data) {}
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
onAppPrivateCommand: onAppPrivateCommand,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.onAppPrivateCommand, onAppPrivateCommand);
});
testWidgets('Passes selectionHeightStyle to selectionHeightStyle TextField', (WidgetTester tester) async {
const BoxHeightStyle selectionHeightStyle = BoxHeightStyle.max;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
selectionHeightStyle: selectionHeightStyle,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.selectionHeightStyle, selectionHeightStyle);
});
testWidgets('Passes selectionWidthStyle to selectionWidthStyle TextField', (WidgetTester tester) async {
const BoxWidthStyle selectionWidthStyle = BoxWidthStyle.max;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
selectionWidthStyle: selectionWidthStyle,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.selectionWidthStyle, selectionWidthStyle);
});
testWidgets('Passes dragStartBehavior to dragStartBehavior TextField', (WidgetTester tester) async {
const DragStartBehavior dragStartBehavior = DragStartBehavior.down;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
dragStartBehavior: dragStartBehavior,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.dragStartBehavior, dragStartBehavior);
});
testWidgets('Passes onTapAlwaysCalled to onTapAlwaysCalled TextField', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: TextFormField(
onTapAlwaysCalled: true,
),
),
),
),
);
final Finder textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
final TextField textFieldWidget = tester.widget(textFieldFinder);
expect(textFieldWidget.onTapAlwaysCalled, isTrue);
});
testWidgets('Error color for cursor while validating', (WidgetTester tester) async {
const Color themeErrorColor = Color(0xff111111);
const Color errorStyleColor = Color(0xff777777);
const Color cursorErrorColor = Color(0xffbbbbbb);
Widget buildWidget({Color? errorStyleColor, Color? cursorErrorColor}) {
return MaterialApp(
theme: ThemeData(
colorScheme: const ColorScheme.light(error: themeErrorColor),
),
home: Material(
child: Center(
child: TextFormField(
enabled: true,
autovalidateMode: AutovalidateMode.always,
decoration: InputDecoration(
errorStyle: TextStyle(
color: errorStyleColor,
),
),
cursorErrorColor: cursorErrorColor,
validator: (String? value) {
return 'Please enter value';
},
),
),
),
);
}
Future<void> runTest(Widget widget, {required Color expectedColor}) async {
await tester.pumpWidget(widget);
await tester.enterText(find.byType(TextField), 'a');
final EditableText textField = tester.widget(
find.byType(EditableText).first,
);
await tester.pump();
expect(textField.cursorColor, expectedColor);
}
await runTest(
buildWidget(),
expectedColor: themeErrorColor,
);
await runTest(
buildWidget(errorStyleColor: errorStyleColor),
expectedColor: errorStyleColor,
);
await runTest(
buildWidget(cursorErrorColor: cursorErrorColor),
expectedColor: cursorErrorColor,
);
await runTest(
buildWidget(
errorStyleColor: errorStyleColor,
cursorErrorColor: cursorErrorColor,
),
expectedColor: cursorErrorColor,
);
});
testWidgets('TextFormField onChanged is called when the form is reset', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/123009.
final GlobalKey<FormFieldState<String>> stateKey = GlobalKey<FormFieldState<String>>();
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
String value = 'initialValue';
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Form(
key: formKey,
child: TextFormField(
key: stateKey,
initialValue: value,
onChanged: (String newValue) {
value = newValue;
},
),
),
),
));
// Initial value is 'initialValue'.
expect(stateKey.currentState!.value, 'initialValue');
expect(value, 'initialValue');
// Change value to 'changedValue'.
await tester.enterText(find.byType(TextField), 'changedValue');
expect(stateKey.currentState!.value,'changedValue');
expect(value, 'changedValue');
// Should be back to 'initialValue' when the form is reset.
formKey.currentState!.reset();
await tester.pump();
expect(stateKey.currentState!.value,'initialValue');
expect(value, 'initialValue');
});
}
| flutter/packages/flutter/test/material/text_form_field_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/text_form_field_test.dart",
"repo_id": "flutter",
"token_count": 20922
} | 678 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.