text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [DropdownMenu]. const List<String> list = <String>['One', 'Two', 'Three', 'Four']; void main() => runApp(const DropdownMenuApp()); class DropdownMenuApp extends StatelessWidget { const DropdownMenuApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3:true), home: Scaffold( appBar: AppBar(title: const Text('DropdownMenu Sample')), body: const Center( child: DropdownMenuExample(), ), ), ); } } class DropdownMenuExample extends StatefulWidget { const DropdownMenuExample({super.key}); @override State<DropdownMenuExample> createState() => _DropdownMenuExampleState(); } class _DropdownMenuExampleState extends State<DropdownMenuExample> { String dropdownValue = list.first; @override Widget build(BuildContext context) { return DropdownMenu<String>( initialSelection: list.first, onSelected: (String? value) { // This is called when the user selects an item. setState(() { dropdownValue = value!; }); }, dropdownMenuEntries: list.map<DropdownMenuEntry<String>>((String value) { return DropdownMenuEntry<String>( value: value, label: value ); }).toList(), ); } }
flutter/examples/api/lib/material/dropdown_menu/dropdown_menu.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/dropdown_menu/dropdown_menu.1.dart", "repo_id": "flutter", "token_count": 569 }
612
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [IconButton]. void main() => runApp(const IconButtonExampleApp()); class IconButtonExampleApp extends StatelessWidget { const IconButtonExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('IconButton Sample')), body: const IconButtonExample(), ), ); } } class IconButtonExample extends StatelessWidget { const IconButtonExample({super.key}); @override @override Widget build(BuildContext context) { return Material( color: Colors.white, child: Center( child: Ink( decoration: const ShapeDecoration( color: Colors.lightBlue, shape: CircleBorder(), ), child: IconButton( icon: const Icon(Icons.android), color: Colors.white, onPressed: () {}, ), ), ), ); } }
flutter/examples/api/lib/material/icon_button/icon_button.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/icon_button/icon_button.1.dart", "repo_id": "flutter", "token_count": 457 }
613
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [InputDecoration]. void main() => runApp(const MaterialStateExampleApp()); class MaterialStateExampleApp extends StatelessWidget { const MaterialStateExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( appBar: AppBar(title: const Text('InputDecoration Sample')), body: const MaterialStateExample(), ), ); } } class MaterialStateExample extends StatelessWidget { const MaterialStateExample({super.key}); @override Widget build(BuildContext context) { return TextFormField( initialValue: 'abc', decoration: InputDecoration( prefixIcon: const Icon(Icons.person), prefixIconColor: MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.focused)) { return Colors.green; } if (states.contains(MaterialState.error)) { return Colors.red; } return Colors.grey; }), ), ); } }
flutter/examples/api/lib/material/input_decorator/input_decoration.material_state.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/input_decorator/input_decoration.material_state.0.dart", "repo_id": "flutter", "token_count": 479 }
614
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [MaterialStateOutlinedBorder]. void main() => runApp(const MaterialStateOutlinedBorderExampleApp()); class MaterialStateOutlinedBorderExampleApp extends StatelessWidget { const MaterialStateOutlinedBorderExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: MaterialStateOutlinedBorderExample(), ); } } class SelectedBorder extends RoundedRectangleBorder implements MaterialStateOutlinedBorder { const SelectedBorder(); @override OutlinedBorder? resolve(Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return const RoundedRectangleBorder(); } return null; // Defer to default value on the theme or widget. } } class MaterialStateOutlinedBorderExample extends StatefulWidget { const MaterialStateOutlinedBorderExample({super.key}); @override State<MaterialStateOutlinedBorderExample> createState() => _MaterialStateOutlinedBorderExampleState(); } class _MaterialStateOutlinedBorderExampleState extends State<MaterialStateOutlinedBorderExample> { bool isSelected = true; @override Widget build(BuildContext context) { return Material( child: FilterChip( label: const Text('Select chip'), selected: isSelected, onSelected: (bool value) { setState(() { isSelected = value; }); }, shape: const SelectedBorder(), ), ); } }
flutter/examples/api/lib/material/material_state/material_state_outlined_border.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/material_state/material_state_outlined_border.0.dart", "repo_id": "flutter", "token_count": 528 }
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'; /// Flutter code sample for [OutlinedButton]. void main() => runApp(const OutlinedButtonExampleApp()); class OutlinedButtonExampleApp extends StatelessWidget { const OutlinedButtonExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('OutlinedButton Sample')), body: const Center( child: OutlinedButtonExample(), ), ), ); } } class OutlinedButtonExample extends StatelessWidget { const OutlinedButtonExample({super.key}); @override Widget build(BuildContext context) { return OutlinedButton( onPressed: () { debugPrint('Received click'); }, child: const Text('Click Me'), ); } }
flutter/examples/api/lib/material/outlined_button/outlined_button.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/outlined_button/outlined_button.0.dart", "repo_id": "flutter", "token_count": 334 }
616
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for custom labeled radio. void main() => runApp(const LabeledRadioApp()); class LabeledRadioApp extends StatelessWidget { const LabeledRadioApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( appBar: AppBar(title: const Text('Custom Labeled Radio Sample')), body: const LabeledRadioExample(), ), ); } } class LabeledRadio extends StatelessWidget { const LabeledRadio({ super.key, required this.label, required this.padding, required this.groupValue, required this.value, required this.onChanged, }); final String label; final EdgeInsets padding; final bool groupValue; final bool value; final ValueChanged<bool> onChanged; @override Widget build(BuildContext context) { return InkWell( onTap: () { if (value != groupValue) { onChanged(value); } }, child: Padding( padding: padding, child: Row( children: <Widget>[ Radio<bool>( groupValue: groupValue, value: value, onChanged: (bool? newValue) { onChanged(newValue!); }, ), Text(label), ], ), ), ); } } class LabeledRadioExample extends StatefulWidget { const LabeledRadioExample({super.key}); @override State<LabeledRadioExample> createState() => _LabeledRadioExampleState(); } class _LabeledRadioExampleState extends State<LabeledRadioExample> { bool _isRadioSelected = false; @override Widget build(BuildContext context) { return Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.center, children: <LabeledRadio>[ LabeledRadio( label: 'This is the first label text', padding: const EdgeInsets.symmetric(horizontal: 5.0), value: true, groupValue: _isRadioSelected, onChanged: (bool newValue) { setState(() { _isRadioSelected = newValue; }); }, ), LabeledRadio( label: 'This is the second label text', padding: const EdgeInsets.symmetric(horizontal: 5.0), value: false, groupValue: _isRadioSelected, onChanged: (bool newValue) { setState(() { _isRadioSelected = newValue; }); }, ), ], ), ); } }
flutter/examples/api/lib/material/radio_list_tile/custom_labeled_radio.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/radio_list_tile/custom_labeled_radio.1.dart", "repo_id": "flutter", "token_count": 1238 }
617
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [Scaffold.endDrawer]. void main() => runApp(const EndDrawerExampleApp()); class EndDrawerExampleApp extends StatelessWidget { const EndDrawerExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: EndDrawerExample(), ); } } class EndDrawerExample extends StatefulWidget { const EndDrawerExample({super.key}); @override State<EndDrawerExample> createState() => _EndDrawerExampleState(); } class _EndDrawerExampleState extends State<EndDrawerExample> { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); void _openEndDrawer() { _scaffoldKey.currentState!.openEndDrawer(); } void _closeEndDrawer() { Navigator.of(context).pop(); } @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, appBar: AppBar(title: const Text('Drawer Demo')), body: Center( child: ElevatedButton( onPressed: _openEndDrawer, child: const Text('Open End Drawer'), ), ), endDrawer: Drawer( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('This is the Drawer'), ElevatedButton( onPressed: _closeEndDrawer, child: const Text('Close Drawer'), ), ], ), ), ), // Disable opening the end drawer with a swipe gesture. endDrawerEnableOpenDragGesture: false, ); } }
flutter/examples/api/lib/material/scaffold/scaffold.end_drawer.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/scaffold/scaffold.end_drawer.0.dart", "repo_id": "flutter", "token_count": 729 }
618
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [SearchAnchor]. const Duration fakeAPIDuration = Duration(seconds: 1); void main() => runApp(const SearchAnchorAsyncExampleApp()); class SearchAnchorAsyncExampleApp extends StatelessWidget { const SearchAnchorAsyncExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('SearchAnchor - async'), ), body: const Center( child: _AsyncSearchAnchor(), ), ), ); } } class _AsyncSearchAnchor extends StatefulWidget { const _AsyncSearchAnchor(); @override State<_AsyncSearchAnchor > createState() => _AsyncSearchAnchorState(); } class _AsyncSearchAnchorState extends State<_AsyncSearchAnchor > { // The query currently being searched for. If null, there is no pending // request. String? _searchingWithQuery; // The most recent options received from the API. late Iterable<Widget> _lastOptions = <Widget>[]; @override Widget build(BuildContext context) { return SearchAnchor( builder: (BuildContext context, SearchController controller) { return IconButton( icon: const Icon(Icons.search), onPressed: () { controller.openView(); }, ); }, suggestionsBuilder: (BuildContext context, SearchController controller) async { _searchingWithQuery = controller.text; final List<String> options = (await _FakeAPI.search(_searchingWithQuery!)).toList(); // If another search happened after this one, throw away these options. // Use the previous options instead and wait for the newer request to // finish. if (_searchingWithQuery != controller.text) { return _lastOptions; } _lastOptions = List<ListTile>.generate(options.length, (int index) { final String item = options[index]; return ListTile( title: Text(item), ); }); return _lastOptions; }); } } // Mimics a remote API. class _FakeAPI { static const List<String> _kOptions = <String>[ 'aardvark', 'bobcat', 'chameleon', ]; // Searches the options, but injects a fake "network" delay. static Future<Iterable<String>> search(String query) async { await Future<void>.delayed(fakeAPIDuration); // Fake 1 second delay. if (query == '') { return const Iterable<String>.empty(); } return _kOptions.where((String option) { return option.contains(query.toLowerCase()); }); } }
flutter/examples/api/lib/material/search_anchor/search_anchor.3.dart/0
{ "file_path": "flutter/examples/api/lib/material/search_anchor/search_anchor.3.dart", "repo_id": "flutter", "token_count": 1078 }
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/material.dart'; /// Flutter code sample for [Stepper]. void main() => runApp(const StepperExampleApp()); class StepperExampleApp extends StatelessWidget { const StepperExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Stepper Sample')), body: const Center( child: StepperExample(), ), ), ); } } class StepperExample extends StatefulWidget { const StepperExample({super.key}); @override State<StepperExample> createState() => _StepperExampleState(); } class _StepperExampleState extends State<StepperExample> { int _index = 0; @override Widget build(BuildContext context) { return Stepper( currentStep: _index, onStepCancel: () { if (_index > 0) { setState(() { _index -= 1; }); } }, onStepContinue: () { if (_index <= 0) { setState(() { _index += 1; }); } }, onStepTapped: (int index) { setState(() { _index = index; }); }, steps: <Step>[ Step( title: const Text('Step 1 title'), content: Container( alignment: Alignment.centerLeft, child: const Text('Content for Step 1'), ), ), const Step( title: Text('Step 2 title'), content: Text('Content for Step 2'), ), ], ); } }
flutter/examples/api/lib/material/stepper/stepper.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/stepper/stepper.0.dart", "repo_id": "flutter", "token_count": 751 }
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/material.dart'; /// Flutter code sample for [TextButton]. void main() { runApp(const MaterialApp(home: Home())); } class SelectableButton extends StatefulWidget { const SelectableButton({ super.key, required this.selected, this.style, required this.onPressed, required this.child, }); final bool selected; final ButtonStyle? style; final VoidCallback? onPressed; final Widget child; @override State<SelectableButton> createState() => _SelectableButtonState(); } class _SelectableButtonState extends State<SelectableButton> { late final MaterialStatesController statesController; @override void initState() { super.initState(); statesController = MaterialStatesController(<MaterialState>{if (widget.selected) MaterialState.selected}); } @override void didUpdateWidget(SelectableButton oldWidget) { super.didUpdateWidget(oldWidget); if (widget.selected != oldWidget.selected) { statesController.update(MaterialState.selected, widget.selected); } } @override Widget build(BuildContext context) { return TextButton( statesController: statesController, style: widget.style, onPressed: widget.onPressed, child: widget.child, ); } } class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { bool selected = false; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: SelectableButton( selected: selected, style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith<Color?>( (Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return Colors.white; } return null; // defer to the defaults }, ), backgroundColor: MaterialStateProperty.resolveWith<Color?>( (Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return Colors.indigo; } return null; // defer to the defaults }, ), ), onPressed: () { setState(() { selected = !selected; }); }, child: const Text('toggle selected'), ), ), ); } }
flutter/examples/api/lib/material/text_button/text_button.1.dart/0
{ "file_path": "flutter/examples/api/lib/material/text_button/text_button.1.dart", "repo_id": "flutter", "token_count": 1058 }
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/material.dart'; /// Flutter code sample for [LinearGradient]. void main() => runApp(const LinearGradientExampleApp()); class LinearGradientExampleApp extends StatelessWidget { const LinearGradientExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: MoodyGradient()); } } class MoodyGradient extends StatelessWidget { const MoodyGradient({super.key}); @override Widget build(BuildContext context) { return Material( child: Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment(0.8, 1), colors: <Color>[ Color(0xff1f005c), Color(0xff5b0060), Color(0xff870160), Color(0xffac255e), Color(0xffca485c), Color(0xffe16b5c), Color(0xfff39060), Color(0xffffb56b), ], // Gradient from https://learnui.design/tools/gradient-generator.html tileMode: TileMode.mirror, ), ), child: const Center( child: Text( 'From Night to Day', style: TextStyle(fontSize: 24, color: Colors.white), ), ), ), ); } }
flutter/examples/api/lib/painting/gradient/linear_gradient.0.dart/0
{ "file_path": "flutter/examples/api/lib/painting/gradient/linear_gradient.0.dart", "repo_id": "flutter", "token_count": 657 }
622
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; /// Flutter code sample for [AppBar.systemOverlayStyle]. void main() => runApp(const SystemOverlayStyleApp()); class SystemOverlayStyleApp extends StatelessWidget { const SystemOverlayStyleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( useMaterial3: true, brightness: Brightness.light, ), home: const SystemOverlayStyleExample(), ); } } class SystemOverlayStyleExample extends StatefulWidget { const SystemOverlayStyleExample({super.key}); @override State<SystemOverlayStyleExample> createState() => _SystemOverlayStyleExampleState(); } class _SystemOverlayStyleExampleState extends State<SystemOverlayStyleExample> { final math.Random _random = math.Random(); SystemUiOverlayStyle _currentStyle = SystemUiOverlayStyle.light; void _changeColor() { final Color color = Color.fromRGBO( _random.nextInt(255), _random.nextInt(255), _random.nextInt(255), 1.0, ); setState(() { _currentStyle = SystemUiOverlayStyle.dark.copyWith( statusBarColor: color, systemNavigationBarColor: color, ); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('SystemUiOverlayStyle Sample'), systemOverlayStyle: _currentStyle, ), body: Center( child: ElevatedButton( onPressed: _changeColor, child: const Text('Change Color'), ), ), ); } }
flutter/examples/api/lib/services/system_chrome/system_chrome.set_system_u_i_overlay_style.0.dart/0
{ "file_path": "flutter/examples/api/lib/services/system_chrome/system_chrome.set_system_u_i_overlay_style.0.dart", "repo_id": "flutter", "token_count": 667 }
623
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; /// Flutter code sample for [FontFeature.FontFeature.numerators]. void main() => runApp(const ExampleApp()); class ExampleApp extends StatelessWidget { const ExampleApp({super.key}); @override Widget build(BuildContext context) { return WidgetsApp( builder: (BuildContext context, Widget? navigator) => const ExampleWidget(), color: const Color(0xffffffff), ); } } /// This is the stateless widget that the main application instantiates. class ExampleWidget extends StatelessWidget { const ExampleWidget({super.key}); @override Widget build(BuildContext context) { // The Piazzolla font can be downloaded from Google Fonts // (https://www.google.com/fonts). return const Text( 'Fractions: 1/2 2/3 3/4 4/5', style: TextStyle( fontFamily: 'Piazzolla', fontFeatures: <FontFeature>[ FontFeature.numerators(), ], ), ); } }
flutter/examples/api/lib/ui/text/font_feature.font_feature_numerators.0.dart/0
{ "file_path": "flutter/examples/api/lib/ui/text/font_feature.font_feature_numerators.0.dart", "repo_id": "flutter", "token_count": 386 }
624
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; /// Flutter code sample for [FocusableActionDetector]. void main() => runApp(const FocusableActionDetectorExampleApp()); class FocusableActionDetectorExampleApp extends StatelessWidget { const FocusableActionDetectorExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: FocusableActionDetectorExample(), ); } } class FadButton extends StatefulWidget { const FadButton({ super.key, required this.onPressed, required this.child, }); final VoidCallback onPressed; final Widget child; @override State<FadButton> createState() => _FadButtonState(); } class _FadButtonState extends State<FadButton> { bool _focused = false; bool _hovering = false; bool _on = false; late final Map<Type, Action<Intent>> _actionMap; final Map<ShortcutActivator, Intent> _shortcutMap = const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.keyX): ActivateIntent(), }; @override void initState() { super.initState(); _actionMap = <Type, Action<Intent>>{ ActivateIntent: CallbackAction<Intent>( onInvoke: (Intent intent) => _toggleState(), ), }; } Color get color { Color baseColor = Colors.lightBlue; if (_focused) { baseColor = Color.alphaBlend(Colors.black.withOpacity(0.25), baseColor); } if (_hovering) { baseColor = Color.alphaBlend(Colors.black.withOpacity(0.1), baseColor); } return baseColor; } void _toggleState() { setState(() { _on = !_on; }); } void _handleFocusHighlight(bool value) { setState(() { _focused = value; }); } void _handleHoveHighlight(bool value) { setState(() { _hovering = value; }); } @override Widget build(BuildContext context) { return GestureDetector( onTap: _toggleState, child: FocusableActionDetector( actions: _actionMap, shortcuts: _shortcutMap, onShowFocusHighlight: _handleFocusHighlight, onShowHoverHighlight: _handleHoveHighlight, child: Row( children: <Widget>[ Container( padding: const EdgeInsets.all(10.0), color: color, child: widget.child, ), Container( width: 30, height: 30, margin: const EdgeInsets.all(10.0), color: _on ? Colors.red : Colors.transparent, ), ], ), ), ); } } class FocusableActionDetectorExample extends StatefulWidget { const FocusableActionDetectorExample({super.key}); @override State<FocusableActionDetectorExample> createState() => _FocusableActionDetectorExampleState(); } class _FocusableActionDetectorExampleState extends State<FocusableActionDetectorExample> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('FocusableActionDetector Example'), ), body: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: TextButton(onPressed: () {}, child: const Text('Press Me')), ), Padding( padding: const EdgeInsets.all(8.0), child: FadButton(onPressed: () {}, child: const Text('And Me')), ), ], ), ), ); } }
flutter/examples/api/lib/widgets/actions/focusable_action_detector.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/actions/focusable_action_detector.0.dart", "repo_id": "flutter", "token_count": 1537 }
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/material.dart'; /// Flutter code sample for [AutofillGroup]. void main() => runApp(const AutofillGroupExampleApp()); class AutofillGroupExampleApp extends StatelessWidget { const AutofillGroupExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('AutofillGroup Sample')), body: const AutofillGroupExample(), ), ); } } class AutofillGroupExample extends StatefulWidget { const AutofillGroupExample({super.key}); @override State<AutofillGroupExample> createState() => _AutofillGroupExampleState(); } class _AutofillGroupExampleState extends State<AutofillGroupExample> { bool isSameAddress = true; final TextEditingController shippingAddress1 = TextEditingController(); final TextEditingController shippingAddress2 = TextEditingController(); final TextEditingController billingAddress1 = TextEditingController(); final TextEditingController billingAddress2 = TextEditingController(); final TextEditingController creditCardNumber = TextEditingController(); final TextEditingController creditCardSecurityCode = TextEditingController(); final TextEditingController phoneNumber = TextEditingController(); @override Widget build(BuildContext context) { return ListView( children: <Widget>[ const Text('Shipping address'), // The address fields are grouped together as some platforms are // capable of autofilling all of these fields in one go. AutofillGroup( child: Column( children: <Widget>[ TextField( controller: shippingAddress1, autofillHints: const <String>[AutofillHints.streetAddressLine1], ), TextField( controller: shippingAddress2, autofillHints: const <String>[AutofillHints.streetAddressLine2], ), ], ), ), const Text('Billing address'), Checkbox( value: isSameAddress, onChanged: (bool? newValue) { if (newValue != null) { setState(() { isSameAddress = newValue; }); } }, ), // Again the address fields are grouped together for the same reason. if (!isSameAddress) AutofillGroup( child: Column( children: <Widget>[ TextField( controller: billingAddress1, autofillHints: const <String>[ AutofillHints.streetAddressLine1, ], ), TextField( controller: billingAddress2, autofillHints: const <String>[ AutofillHints.streetAddressLine2, ], ), ], ), ), const Text('Credit Card Information'), // The credit card number and the security code are grouped together // as some platforms are capable of autofilling both fields. AutofillGroup( child: Column( children: <Widget>[ TextField( controller: creditCardNumber, autofillHints: const <String>[AutofillHints.creditCardNumber], ), TextField( controller: creditCardSecurityCode, autofillHints: const <String>[ AutofillHints.creditCardSecurityCode, ], ), ], ), ), const Text('Contact Phone Number'), // The phone number field can still be autofilled despite lacking an // `AutofillScope`. TextField( controller: phoneNumber, autofillHints: const <String>[AutofillHints.telephoneNumber], ), ], ); } }
flutter/examples/api/lib/widgets/autofill/autofill_group.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/autofill/autofill_group.0.dart", "repo_id": "flutter", "token_count": 1811 }
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/material.dart'; /// Flutter code sample for [MouseRegion]. void main() => runApp(const MouseRegionApp()); class MouseRegionApp extends StatelessWidget { const MouseRegionApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('MouseRegion Sample')), body: const Center( child: MouseRegionExample(), ), ), ); } } class MouseRegionExample extends StatefulWidget { const MouseRegionExample({super.key}); @override State<MouseRegionExample> createState() => _MouseRegionExampleState(); } class _MouseRegionExampleState extends State<MouseRegionExample> { int _enterCounter = 0; int _exitCounter = 0; double x = 0.0; double y = 0.0; void _incrementEnter(PointerEvent details) { setState(() { _enterCounter++; }); } void _incrementExit(PointerEvent details) { setState(() { _exitCounter++; }); } void _updateLocation(PointerEvent details) { setState(() { x = details.position.dx; y = details.position.dy; }); } @override Widget build(BuildContext context) { return ConstrainedBox( constraints: BoxConstraints.tight(const Size(300.0, 200.0)), child: MouseRegion( onEnter: _incrementEnter, onHover: _updateLocation, onExit: _incrementExit, child: ColoredBox( color: Colors.lightBlueAccent, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('You have entered or exited this box this many times:'), Text( '$_enterCounter Entries\n$_exitCounter Exits', style: Theme.of(context).textTheme.headlineMedium, ), Text( 'The cursor is here: (${x.toStringAsFixed(2)}, ${y.toStringAsFixed(2)})', ), ], ), ), ), ); } }
flutter/examples/api/lib/widgets/basic/mouse_region.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/basic/mouse_region.0.dart", "repo_id": "flutter", "token_count": 908 }
627
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [FocusNode.unfocus]. void main() => runApp(const UnfocusExampleApp()); class UnfocusExampleApp extends StatelessWidget { const UnfocusExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: UnfocusExample(), ); } } class UnfocusExample extends StatefulWidget { const UnfocusExample({super.key}); @override State<UnfocusExample> createState() => _UnfocusExampleState(); } class _UnfocusExampleState extends State<UnfocusExample> { UnfocusDisposition disposition = UnfocusDisposition.scope; @override Widget build(BuildContext context) { return Material( child: ColoredBox( color: Colors.white, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Wrap( children: List<Widget>.generate(4, (int index) { return const SizedBox( width: 200, child: Padding( padding: EdgeInsets.all(8.0), child: TextField( decoration: InputDecoration(border: OutlineInputBorder()), ), ), ); }), ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ ...List<Widget>.generate(UnfocusDisposition.values.length, (int index) { return Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Radio<UnfocusDisposition>( groupValue: disposition, onChanged: (UnfocusDisposition? value) { setState(() { if (value != null) { disposition = value; } }); }, value: UnfocusDisposition.values[index], ), Text(UnfocusDisposition.values[index].name), ], ); }), OutlinedButton( child: const Text('UNFOCUS'), onPressed: () { setState(() { primaryFocus!.unfocus(disposition: disposition); }); }, ), ], ), ], ), ), ); } }
flutter/examples/api/lib/widgets/focus_manager/focus_node.unfocus.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/focus_manager/focus_node.unfocus.0.dart", "repo_id": "flutter", "token_count": 1480 }
628
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; /// Flutter code sample for [Hero]. void main() { // Slow down time to see Hero flight animation. timeDilation = 15.0; runApp(const HeroApp()); } class HeroApp extends StatelessWidget { const HeroApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: const HeroExample(), ); } } class HeroExample extends StatelessWidget { const HeroExample({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Hero Sample')), body: Column( children: <Widget>[ ListTile( leading: Hero( tag: 'hero-default-tween', child: BoxWidget( size: const Size(50.0, 50.0), color: Colors.red[700]!.withOpacity(0.5), ), ), title: const Text( 'This red icon will use a default rect tween during the hero flight.', ), ), const SizedBox(height: 10.0), ListTile( leading: Hero( tag: 'hero-custom-tween', createRectTween: (Rect? begin, Rect? end) { return MaterialRectCenterArcTween(begin: begin, end: end); }, child: BoxWidget( size: const Size(50.0, 50.0), color: Colors.blue[700]!.withOpacity(0.5), ), ), title: const Text( 'This blue icon will use a custom rect tween during the hero flight.', ), ), const SizedBox(height: 10), ElevatedButton( onPressed: () => _gotoDetailsPage(context), child: const Text('Tap to trigger hero flight'), ), ], ), ); } void _gotoDetailsPage(BuildContext context) { Navigator.of(context).push(MaterialPageRoute<void>( builder: (BuildContext context) => Scaffold( appBar: AppBar( title: const Text('Second Page'), ), body: Align( alignment: Alignment.bottomRight, child: Stack( children: <Widget>[ Hero( tag: 'hero-custom-tween', createRectTween: (Rect? begin, Rect? end) { return MaterialRectCenterArcTween(begin: begin, end: end); }, child: BoxWidget( size: const Size(400.0, 400.0), color: Colors.blue[700]!.withOpacity(0.5), ), ), Hero( tag: 'hero-default-tween', child: BoxWidget( size: const Size(400.0, 400.0), color: Colors.red[700]!.withOpacity(0.5), ), ), ], ), ), ), )); } } class BoxWidget extends StatelessWidget { const BoxWidget({ super.key, required this.size, required this.color, }); final Size size; final Color color; @override Widget build(BuildContext context) { return Container( width: size.width, height: size.height, color: color, ); } }
flutter/examples/api/lib/widgets/heroes/hero.1.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/heroes/hero.1.dart", "repo_id": "flutter", "token_count": 1706 }
629
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [InteractiveViewer.constrained]. void main() => runApp(const ConstrainedExampleApp()); class ConstrainedExampleApp extends StatelessWidget { const ConstrainedExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Constrained Sample')), body: const ConstrainedExample(), ), ); } } class ConstrainedExample extends StatelessWidget { const ConstrainedExample({super.key}); @override Widget build(BuildContext context) { const int rowCount = 48; const int columnCount = 6; return InteractiveViewer( panAxis: PanAxis.aligned, constrained: false, scaleEnabled: false, child: Table( columnWidths: <int, TableColumnWidth>{ for (int column = 0; column < columnCount; column += 1) column: const FixedColumnWidth(200.0), }, children: <TableRow>[ for (int row = 0; row < rowCount; row += 1) TableRow( children: <Widget>[ for (int column = 0; column < columnCount; column += 1) Container( height: 26, color: row % 2 + column % 2 == 1 ? Colors.white : Colors.grey.withOpacity(0.1), child: Align( alignment: Alignment.centerLeft, child: Text('$row x $column'), ), ), ], ), ], ), ); } }
flutter/examples/api/lib/widgets/interactive_viewer/interactive_viewer.constrained.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/interactive_viewer/interactive_viewer.constrained.0.dart", "repo_id": "flutter", "token_count": 772 }
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/material.dart'; /// Flutter code sample for [NestedScrollView]. void main() => runApp(const NestedScrollViewExampleApp()); class NestedScrollViewExampleApp extends StatelessWidget { const NestedScrollViewExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: NestedScrollViewExample(), ); } } class NestedScrollViewExample extends StatelessWidget { const NestedScrollViewExample({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: NestedScrollView( // Setting floatHeaderSlivers to true is required in order to float // the outer slivers over the inner scrollable. floatHeaderSlivers: true, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( title: const Text('Floating Nested SliverAppBar'), floating: true, expandedHeight: 200.0, forceElevated: innerBoxIsScrolled, ), ]; }, body: ListView.builder( padding: const EdgeInsets.all(8), itemCount: 30, itemBuilder: (BuildContext context, int index) { return SizedBox( height: 50, child: Center(child: Text('Item $index')), ); }))); } }
flutter/examples/api/lib/widgets/nested_scroll_view/nested_scroll_view.1.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/nested_scroll_view/nested_scroll_view.1.dart", "repo_id": "flutter", "token_count": 737 }
631
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [PopupRoute]. void main() => runApp(const PopupRouteApp()); class PopupRouteApp extends StatelessWidget { const PopupRouteApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: PopupRouteExample(), ); } } class PopupRouteExample extends StatelessWidget { const PopupRouteExample({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: OutlinedButton( onPressed: () { // This shows a dismissible dialog. Navigator.of(context).push(DismissibleDialog<void>()); }, child: const Text('Open DismissibleDialog'), ), ), ); } } class DismissibleDialog<T> extends PopupRoute<T> { @override Color? get barrierColor => Colors.black.withAlpha(0x50); // This allows the popup to be dismissed by tapping the scrim or by pressing // the escape key on the keyboard. @override bool get barrierDismissible => true; @override String? get barrierLabel => 'Dismissible Dialog'; @override Duration get transitionDuration => const Duration(milliseconds: 300); @override Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return Center( // Provide DefaultTextStyle to ensure that the dialog's text style // matches the rest of the text in the app. child: DefaultTextStyle( style: Theme.of(context).textTheme.bodyMedium!, // UnconstrainedBox is used to make the dialog size itself // to fit to the size of the content. child: UnconstrainedBox( child: Container( padding: const EdgeInsets.all(20.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white, ), child: Column( children: <Widget>[ Text('Dismissible Dialog', style: Theme.of(context).textTheme.headlineSmall), const SizedBox(height: 20), const Text('Tap in the scrim or press escape key to dismiss.'), ], ), ), ), ), ); } }
flutter/examples/api/lib/widgets/routes/popup_route.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/routes/popup_route.0.dart", "repo_id": "flutter", "token_count": 956 }
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/material.dart'; /// Flutter code sample for [SharedAppData]. class ShowSharedValue extends StatelessWidget { const ShowSharedValue({super.key, required this.appDataKey}); final String appDataKey; @override Widget build(BuildContext context) { // The SharedAppData.getValue() call causes this widget to depend on the // value of the SharedAppData's 'foo' key. If it's changed, with // SharedAppData.setValue(), then this widget will be rebuilt. final String value = SharedAppData.getValue<String, String>(context, appDataKey, () => 'initial'); return Text('$appDataKey: $value'); } } // Demonstrates that changes to the SharedAppData _only_ cause the dependent // widgets to be rebuilt. In this case that's the ShowSharedValue widget that's // displaying the value of a key whose value has been updated. class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _HomeState(); } class _HomeState extends State<Home> { int _fooVersion = 0; int _barVersion = 0; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const ShowSharedValue(appDataKey: 'foo'), const SizedBox(height: 16), const ShowSharedValue(appDataKey: 'bar'), const SizedBox(height: 16), ElevatedButton( child: const Text('change foo'), onPressed: () { _fooVersion += 1; // Changing the SharedAppData's value for 'foo' causes the // widgets that depend on 'foo' to be rebuilt. SharedAppData.setValue<String, String?>( context, 'foo', 'FOO $_fooVersion'); // no need to call setState() }, ), const SizedBox(height: 16), ElevatedButton( child: const Text('change bar'), onPressed: () { _barVersion += 1; SharedAppData.setValue<String, String?>( context, 'bar', 'BAR $_barVersion'); // no need to call setState() }, ), ], ), ), ); } } void main() { runApp(const MaterialApp(home: Home())); }
flutter/examples/api/lib/widgets/shared_app_data/shared_app_data.0.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/shared_app_data/shared_app_data.0.dart", "repo_id": "flutter", "token_count": 1015 }
633
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for a [ChangeNotifier] with a [ListenableBuilder]. void main() { runApp(const ListenableBuilderExample()); } class CounterModel with ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count += 1; notifyListeners(); } } class ListenableBuilderExample extends StatefulWidget { const ListenableBuilderExample({super.key}); @override State<ListenableBuilderExample> createState() => _ListenableBuilderExampleState(); } class _ListenableBuilderExampleState extends State<ListenableBuilderExample> { final CounterModel _counter = CounterModel(); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('ListenableBuilder Example')), body: CounterBody(counterNotifier: _counter), floatingActionButton: FloatingActionButton( onPressed: _counter.increment, child: const Icon(Icons.add), ), ), ); } } class CounterBody extends StatelessWidget { const CounterBody({super.key, required this.counterNotifier}); final CounterModel counterNotifier; @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('Current counter value:'), // Thanks to the ListenableBuilder, only the widget displaying the // current count is rebuilt when counterValueNotifier notifies its // listeners. The Text widget above and CounterBody itself aren't // rebuilt. ListenableBuilder( listenable: counterNotifier, builder: (BuildContext context, Widget? child) { return Text('${counterNotifier.count}'); }, ), ], ), ); } }
flutter/examples/api/lib/widgets/transitions/listenable_builder.2.dart/0
{ "file_path": "flutter/examples/api/lib/widgets/transitions/listenable_builder.2.dart", "repo_id": "flutter", "token_count": 730 }
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 'package:flutter/cupertino.dart'; import 'package:flutter_api_samples/cupertino/bottom_tab_bar/cupertino_tab_bar.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Can switch between tabs', (WidgetTester tester) async { await tester.pumpWidget( const example.CupertinoTabBarApp(), ); expect(find.byType(CupertinoTabBar), findsOneWidget); expect(find.text('Content of tab 0'), findsOneWidget); await tester.tap(find.text('Contacts')); await tester.pump(); expect(find.text('Content of tab 2'), findsOneWidget); }); }
flutter/examples/api/test/cupertino/bottom_tab_bar/cupertino_tab_bar.0_test.dart/0
{ "file_path": "flutter/examples/api/test/cupertino/bottom_tab_bar/cupertino_tab_bar.0_test.dart", "repo_id": "flutter", "token_count": 267 }
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 'package:flutter/cupertino.dart'; import 'package:flutter_api_samples/cupertino/radio/cupertino_radio.toggleable.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Has 2 CupertinoRadio widgets that can be toggled off', (WidgetTester tester) async { await tester.pumpWidget( const example.CupertinoRadioApp(), ); expect(find.byType(CupertinoRadio<example.SingingCharacter>), findsNWidgets(2)); CupertinoRadio<example.SingingCharacter> radio = tester.widget(find.byType(CupertinoRadio<example.SingingCharacter>).first); expect(radio.groupValue, example.SingingCharacter.mulligan); radio = tester.widget(find.byType(CupertinoRadio<example.SingingCharacter>).last); expect(radio.groupValue, example.SingingCharacter.mulligan); await tester.tap(find.byType(CupertinoRadio<example.SingingCharacter>).last); await tester.pumpAndSettle(); radio = tester.widget(find.byType(CupertinoRadio<example.SingingCharacter>).last); expect(radio.groupValue, example.SingingCharacter.hamilton); radio = tester.widget(find.byType(CupertinoRadio<example.SingingCharacter>).first); expect(radio.groupValue, example.SingingCharacter.hamilton); await tester.tap(find.byType(CupertinoRadio<example.SingingCharacter>).last); await tester.pumpAndSettle(); radio = tester.widget(find.byType(CupertinoRadio<example.SingingCharacter>).last); expect(radio.groupValue, null); }); }
flutter/examples/api/test/cupertino/radio/cupertino_radio.toggleable.0_test.dart/0
{ "file_path": "flutter/examples/api/test/cupertino/radio/cupertino_radio.toggleable.0_test.dart", "repo_id": "flutter", "token_count": 557 }
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 'dart:async'; import 'goldens_io.dart' if (dart.library.html) 'goldens_web.dart' as flutter_goldens; Future<void> testExecutable(FutureOr<void> Function() testMain) { // Enable golden file testing using Skia Gold. return flutter_goldens.testExecutable(testMain, namePrefix: 'api'); }
flutter/examples/api/test/flutter_test_config.dart/0
{ "file_path": "flutter/examples/api/test/flutter_test_config.dart", "repo_id": "flutter", "token_count": 146 }
637
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/autocomplete/autocomplete.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('can search and find options by email and name', (WidgetTester tester) async { await tester.pumpWidget(const example.AutocompleteExampleApp()); expect(find.text('Alice'), findsNothing); expect(find.text('Bob'), findsNothing); expect(find.text('Charlie'), findsNothing); await tester.enterText(find.byType(TextFormField), 'Ali'); await tester.pump(); expect(find.text('Alice'), findsOneWidget); expect(find.text('Bob'), findsNothing); expect(find.text('Charlie'), findsNothing); await tester.enterText(find.byType(TextFormField), 'gmail'); await tester.pump(); expect(find.text('Alice'), findsNothing); expect(find.text('Bob'), findsNothing); expect(find.text('Charlie'), findsOneWidget); }); }
flutter/examples/api/test/material/autocomplete/autocomplete.1_test.dart/0
{ "file_path": "flutter/examples/api/test/material/autocomplete/autocomplete.1_test.dart", "repo_id": "flutter", "token_count": 367 }
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/material.dart'; import 'package:flutter_api_samples/material/checkbox_list_tile/checkbox_list_tile.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Checkbox aligns appropriately', (WidgetTester tester) async { await tester.pumpWidget( const example.CheckboxListTileApp(), ); expect(find.byType(CheckboxListTile), findsNWidgets(3)); Offset tileTopLeft = tester.getTopLeft(find.byType(CheckboxListTile).at(0)); Offset checkboxTopLeft = tester.getTopLeft(find.byType(Checkbox).at(0)); // The checkbox is centered vertically with the text. expect(checkboxTopLeft - tileTopLeft, const Offset(736.0, 16.0)); tileTopLeft = tester.getTopLeft(find.byType(CheckboxListTile).at(1)); checkboxTopLeft = tester.getTopLeft(find.byType(Checkbox).at(1)); // The checkbox is centered vertically with the text. expect(checkboxTopLeft - tileTopLeft, const Offset(736.0, 30.0)); tileTopLeft = tester.getTopLeft(find.byType(CheckboxListTile).at(2)); checkboxTopLeft = tester.getTopLeft(find.byType(Checkbox).at(2)); // The checkbox is aligned to the top vertically with the text. expect(checkboxTopLeft - tileTopLeft, const Offset(736.0, 8.0)); }); testWidgets('Checkboxes can be checked', (WidgetTester tester) async { await tester.pumpWidget( const example.CheckboxListTileApp(), ); expect(find.byType(CheckboxListTile), findsNWidgets(3)); // All checkboxes are checked. expect(tester.widget<Checkbox>(find.byType(Checkbox).at(0)).value, isTrue); expect(tester.widget<Checkbox>(find.byType(Checkbox).at(1)).value, isTrue); expect(tester.widget<Checkbox>(find.byType(Checkbox).at(2)).value, isTrue); // Tap the first checkbox. await tester.tap(find.byType(Checkbox).at(0)); await tester.pumpAndSettle(); // The first checkbox is unchecked. expect(tester.widget<Checkbox>(find.byType(Checkbox).at(0)).value, isFalse); expect(tester.widget<Checkbox>(find.byType(Checkbox).at(1)).value, isTrue); expect(tester.widget<Checkbox>(find.byType(Checkbox).at(2)).value, isTrue); // Tap the second checkbox. await tester.tap(find.byType(Checkbox).at(1)); await tester.pumpAndSettle(); // The first and second checkboxes are unchecked. expect(tester.widget<Checkbox>(find.byType(Checkbox).at(0)).value, isFalse); expect(tester.widget<Checkbox>(find.byType(Checkbox).at(1)).value, isFalse); expect(tester.widget<Checkbox>(find.byType(Checkbox).at(2)).value, isTrue); // Tap the third checkbox. await tester.tap(find.byType(Checkbox).at(2)); await tester.pumpAndSettle(); // All checkboxes are unchecked. expect(tester.widget<Checkbox>(find.byType(Checkbox).at(0)).value, isFalse); expect(tester.widget<Checkbox>(find.byType(Checkbox).at(1)).value, isFalse); expect(tester.widget<Checkbox>(find.byType(Checkbox).at(2)).value, isFalse); }); }
flutter/examples/api/test/material/checkbox_list_tile/checkbox_list_tile.1_test.dart/0
{ "file_path": "flutter/examples/api/test/material/checkbox_list_tile/checkbox_list_tile.1_test.dart", "repo_id": "flutter", "token_count": 1143 }
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 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/date_picker/show_date_range_picker.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Can show date range picker', (WidgetTester tester) async { const String datePickerTitle = 'Select range'; await tester.pumpWidget( const example.DatePickerApp(), ); // The date range picker is not shown initially. expect(find.text(datePickerTitle), findsNothing); expect(find.text('Jan 1'), findsNothing); expect(find.text('Jan 5, 2021'), findsNothing); // Tap the button to show the date range picker. await tester.tap(find.byType(OutlinedButton)); await tester.pumpAndSettle(); // The date range picker shows initial date range. expect(find.text(datePickerTitle), findsOneWidget); expect(find.text('Jan 1'), findsOneWidget); expect(find.text('Jan 5, 2021'), findsOneWidget); // Tap to select new date range. await tester.tap(find.text('18').first); await tester.pumpAndSettle(); await tester.tap(find.text('22').first); await tester.pumpAndSettle(); // The selected date range is shown. expect(find.text(datePickerTitle), findsOneWidget); expect(find.text('Jan 18'), findsOneWidget); expect(find.text('Jan 22, 2021'), findsOneWidget); // Tap Save to confirm the selection and close the date range picker. await tester.tap(find.text('Save')); await tester.pumpAndSettle(); // The date range picker is closed. expect(find.text(datePickerTitle), findsNothing); expect(find.text('Jan 18'), findsNothing); expect(find.text('Jan 22, 2021'), findsNothing); }); }
flutter/examples/api/test/material/date_picker/show_date_range_picker.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/date_picker/show_date_range_picker.0_test.dart", "repo_id": "flutter", "token_count": 634 }
640
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/dropdown_menu/dropdown_menu.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('DropdownMenu', (WidgetTester tester) async { await tester.pumpWidget( const example.DropdownMenuExample(), ); expect(find.text('You selected a Blue Smile'), findsNothing); final Finder colorMenu = find.byType(DropdownMenu<example.ColorLabel>); final Finder iconMenu = find.byType(DropdownMenu<example.IconLabel>); expect(colorMenu, findsOneWidget); expect(iconMenu, findsOneWidget); Finder findMenuItem(String label) { return find.widgetWithText(MenuItemButton, label).last; } await tester.tap(colorMenu); await tester.pumpAndSettle(); expect(findMenuItem('Blue'), findsOneWidget); expect(findMenuItem('Pink'), findsOneWidget); expect(findMenuItem('Green'), findsOneWidget); expect(findMenuItem('Orange'), findsOneWidget); expect(findMenuItem('Grey'), findsOneWidget); await tester.tap(findMenuItem('Blue')); // The DropdownMenu's onSelected callback is delayed // with SchedulerBinding.instance.addPostFrameCallback // to give the focus a chance to return to where it was // before the menu appeared. The pumpAndSettle() // give the callback a chance to run. await tester.pumpAndSettle(); await tester.tap(iconMenu); await tester.pumpAndSettle(); expect(findMenuItem('Smile'), findsOneWidget); expect(findMenuItem('Cloud'), findsOneWidget); expect(findMenuItem('Brush'), findsOneWidget); expect(findMenuItem('Heart'), findsOneWidget); await tester.tap(findMenuItem('Smile')); await tester.pumpAndSettle(); expect(find.text('You selected a Blue Smile'), findsOneWidget); }); testWidgets('DropdownMenu has focus when tapping on the text field', (WidgetTester tester) async { await tester.pumpWidget( const example.DropdownMenuExample(), ); // Make sure the dropdown menus are there. final Finder colorMenu = find.byType(DropdownMenu<example.ColorLabel>); final Finder iconMenu = find.byType(DropdownMenu<example.IconLabel>); expect(colorMenu, findsOneWidget); expect(iconMenu, findsOneWidget); // Tap on the color menu and make sure it is focused. await tester.tap(colorMenu); await tester.pumpAndSettle(); expect(FocusScope.of(tester.element(colorMenu)).hasFocus, isTrue); // Tap on the icon menu and make sure it is focused. await tester.tap(iconMenu); await tester.pumpAndSettle(); expect(FocusScope.of(tester.element(iconMenu)).hasFocus, isTrue); }); }
flutter/examples/api/test/material/dropdown_menu/dropdown_menu.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/dropdown_menu/dropdown_menu.0_test.dart", "repo_id": "flutter", "token_count": 950 }
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/material.dart'; import 'package:flutter_api_samples/material/list_tile/list_tile.selected.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('ListTile item can be selected', (WidgetTester tester) async { await tester.pumpWidget( const example.ListTileApp(), ); expect(find.byType(ListTile), findsNWidgets(10)); // The first item is selected by default. expect(tester.widget<ListTile>(find.byType(ListTile).at(0)).selected, true); // Tap a list item to select it. await tester.tap(find.byType(ListTile).at(5)); await tester.pump(); // The first item is no longer selected. expect(tester.widget<ListTile>(find.byType(ListTile).at(0)).selected, false); expect(tester.widget<ListTile>(find.byType(ListTile).at(5)).selected, true); }); }
flutter/examples/api/test/material/list_tile/list_tile.selected.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/list_tile/list_tile.selected.0_test.dart", "repo_id": "flutter", "token_count": 353 }
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 'package:flutter/material.dart'; import 'package:flutter_api_samples/material/refresh_indicator/refresh_indicator.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Pulling from nested scroll view triggers refresh indicator', (WidgetTester tester) async { await tester.pumpWidget( const example.RefreshIndicatorExampleApp(), ); // Pull from the upper scroll view. await tester.fling(find.text('Pull down here').first, const Offset(0.0, 300.0), 1000.0); await tester.pump(); expect(find.byType(RefreshProgressIndicator), findsNothing); await tester.pumpAndSettle(); // Advance pending time // Pull from the nested scroll view. await tester.fling(find.text('Pull down here').at(3), const Offset(0.0, 300.0), 1000.0); await tester.pump(); expect(find.byType(RefreshProgressIndicator), findsOneWidget); await tester.pumpAndSettle(); // Advance pending time }); }
flutter/examples/api/test/material/refresh_indicator/refresh_indicator.1_test.dart/0
{ "file_path": "flutter/examples/api/test/material/refresh_indicator/refresh_indicator.1_test.dart", "repo_id": "flutter", "token_count": 377 }
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/material.dart'; import 'package:flutter_api_samples/material/snack_bar/snack_bar.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Clicking on Button shows a SnackBar', (WidgetTester tester) async { await tester.pumpWidget( const example.SnackBarExampleApp(), ); expect(find.widgetWithText(AppBar, 'SnackBar Sample'), findsOneWidget); expect(find.widgetWithText(ElevatedButton, 'Show Snackbar'), findsOneWidget); await tester.tap(find.widgetWithText(ElevatedButton, 'Show Snackbar')); await tester.pumpAndSettle(); expect(find.text('Awesome Snackbar!'), findsOneWidget); expect(find.text('Action'), findsOneWidget); }); }
flutter/examples/api/test/material/snack_bar/snack_bar.0_test.dart/0
{ "file_path": "flutter/examples/api/test/material/snack_bar/snack_bar.0_test.dart", "repo_id": "flutter", "token_count": 305 }
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/material.dart'; import 'package:flutter_api_samples/material/text_button/text_button.1.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('SelectableButton', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData( colorScheme: const ColorScheme.light(), ), home: const example.Home(), ), ); final Finder button = find.byType(example.SelectableButton); example.SelectableButton buttonWidget() => tester.widget<example.SelectableButton>(button); Material buttonMaterial() { return tester.widget<Material>( find.descendant( of: find.byType(example.SelectableButton), matching: find.byType(Material), ), ); } expect(buttonWidget().selected, false); expect(buttonMaterial().textStyle!.color, const ColorScheme.light().primary); // default button foreground color expect(buttonMaterial().color, Colors.transparent); // default button background color await tester.tap(button); // Toggles the button's selected property. await tester.pumpAndSettle(); expect(buttonWidget().selected, true); expect(buttonMaterial().textStyle!.color, Colors.white); expect(buttonMaterial().color, Colors.indigo); await tester.tap(button); // Toggles the button's selected property. await tester.pumpAndSettle(); expect(buttonWidget().selected, false); expect(buttonMaterial().textStyle!.color, const ColorScheme.light().primary); expect(buttonMaterial().color, Colors.transparent); }); }
flutter/examples/api/test/material/text_button/text_button.1_test.dart/0
{ "file_path": "flutter/examples/api/test/material/text_button/text_button.1_test.dart", "repo_id": "flutter", "token_count": 603 }
645
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_api_samples/rendering/growth_direction/growth_direction.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Example app has GrowthDirections represented', (WidgetTester tester) async { await tester.pumpWidget( const example.ExampleApp(), ); final RenderViewport viewport = tester.renderObject(find.byType(Viewport)); expect(find.text('AxisDirection.down'), findsNWidgets(2)); expect(find.text('Axis.vertical'), findsNWidgets(2)); expect(find.text('GrowthDirection.forward'), findsOneWidget); expect(find.text('GrowthDirection.reverse'), findsOneWidget); expect(find.byIcon(Icons.arrow_upward_rounded), findsNWidgets(2)); expect(find.byIcon(Icons.arrow_downward_rounded), findsNWidgets(2)); expect(viewport.axisDirection, AxisDirection.down); expect(viewport.anchor, 0.5); expect(viewport.center, isNotNull); await tester.tap( find.byWidgetPredicate((Widget widget) { return widget is Radio<AxisDirection> && widget.value == AxisDirection.up; }) ); await tester.pumpAndSettle(); expect(find.text('AxisDirection.up'), findsNWidgets(2)); expect(find.text('Axis.vertical'), findsNWidgets(2)); expect(find.text('GrowthDirection.forward'), findsOneWidget); expect(find.text('GrowthDirection.reverse'), findsOneWidget); expect(find.byIcon(Icons.arrow_upward_rounded), findsNWidgets(2)); expect(find.byIcon(Icons.arrow_downward_rounded), findsNWidgets(2)); expect(viewport.axisDirection, AxisDirection.up); }); }
flutter/examples/api/test/rendering/growth_direction.0_test.dart/0
{ "file_path": "flutter/examples/api/test/rendering/growth_direction.0_test.dart", "repo_id": "flutter", "token_count": 655 }
646
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/ui/text/font_feature.font_feature_character_variant.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('shows font features', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: example.ExampleWidget(), ), ); expect(find.byType(Text), findsOneWidget); expect((tester.widget(find.byType(Text).first) as Text).style!.fontFamily, equals('Source Code Pro')); expect( (tester.widget(find.byType(Text).first) as Text).style!.fontFeatures, equals(<FontFeature>[ FontFeature.characterVariant(1), FontFeature.characterVariant(2), FontFeature.characterVariant(4), ])); }); }
flutter/examples/api/test/ui/text/font_feature.font_feature_character_variant.0_test.dart/0
{ "file_path": "flutter/examples/api/test/ui/text/font_feature.font_feature_character_variant.0_test.dart", "repo_id": "flutter", "token_count": 361 }
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/material.dart'; import 'package:flutter_api_samples/widgets/basic/overflowbox.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('OverflowBox allows child widget to overflow parent container', (WidgetTester tester) async { const Size containerSize = Size(100, 100); const Size maxSize = Size(200, 200); await tester.pumpWidget( const example.OverflowBoxApp(), ); // The parent container has fixed width and height of 100 pixels. expect(tester.getSize(find.byType(Container).first), containerSize); final OverflowBox overflowBox = tester.widget(find.byType(OverflowBox)); // The OverflowBox imposes its own constraints of maxWidth and maxHeight of // 200 on its child which allows the child to overflow the parent container. expect(overflowBox.maxWidth, maxSize.width); expect(overflowBox.maxHeight, maxSize.height); // The child widget overflows the parent container. expect(tester.getSize(find.byType(FlutterLogo)), greaterThan(containerSize)); expect(tester.getSize(find.byType(FlutterLogo)), maxSize); }); }
flutter/examples/api/test/widgets/basic/overflowbox.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/basic/overflowbox.0_test.dart", "repo_id": "flutter", "token_count": 412 }
648
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/widgets/magnifier/magnifier.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('should update magnifier position on drag', (WidgetTester tester) async { await tester.pumpWidget(const example.MagnifierExampleApp()); Matcher isPositionedAt(Offset at) { return isA<Positioned>().having( (Positioned positioned) => Offset(positioned.left!, positioned.top!), 'magnifier position', at, ); } expect( tester.widget(find.byType(Positioned)), isPositionedAt(Offset.zero), ); final Offset centerOfFlutterLogo = tester.getCenter(find.byType(Positioned)); final Offset topLeftOfFlutterLogo = tester.getTopLeft(find.byType(FlutterLogo)); const Offset dragDistance = Offset(10, 10); await tester.dragFrom(centerOfFlutterLogo, dragDistance); await tester.pump(); expect( tester.widget(find.byType(Positioned)), // Need to adjust by the topleft since the position is local. isPositionedAt((centerOfFlutterLogo - topLeftOfFlutterLogo) + dragDistance), ); }); testWidgets('should match golden', (WidgetTester tester) async { await tester.pumpWidget(const example.MagnifierExampleApp()); final Offset centerOfFlutterLogo = tester.getCenter(find.byType(Positioned)); const Offset dragDistance = Offset(10, 10); await tester.dragFrom(centerOfFlutterLogo, dragDistance); await tester.pump(); await expectLater( find.byType(RepaintBoundary).last, matchesGoldenFile('magnifier.0_test.png'), ); }); }
flutter/examples/api/test/widgets/magnifier/magnifier.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/magnifier/magnifier.0_test.dart", "repo_id": "flutter", "token_count": 665 }
649
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_api_samples/widgets/scroll_view/list_view.0.dart' as example; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('long press ListTile should enable edit mode', (WidgetTester tester) async { await tester.pumpWidget( const example.ListViewExampleApp(), ); final Finder listView = find.byType(ListView); final Finder selectAllFinder = find.text('select all'); final Finder checkBoxFinder = find.byType(Checkbox); expect(listView, findsWidgets); expect(selectAllFinder, findsNothing); expect(checkBoxFinder, findsNothing); await tester.longPress(listView.first); await tester.pump(); expect(selectAllFinder, findsOneWidget); expect(checkBoxFinder, findsWidgets); }); testWidgets('Pressing cross button should disable edit mode', (WidgetTester tester) async { await tester.pumpWidget( const example.ListViewExampleApp(), ); final Finder listView = find.byType(ListView); final Finder crossIconFinder = find.byIcon(Icons.close); expect(listView, findsWidgets); expect(crossIconFinder, findsNothing); /// enable edit mode await tester.longPress(listView.first); await tester.pump(); expect(crossIconFinder, findsOneWidget); await tester.tap(crossIconFinder); await tester.pump(); final Finder selectAllFinder = find.text('select all'); expect(selectAllFinder, findsNothing); expect(crossIconFinder, findsNothing); }); testWidgets('tapping ListTile or checkBox should toggle ListTile state', (WidgetTester tester) async { await tester.pumpWidget( const example.ListViewExampleApp(), ); final Finder listView = find.byType(ListView); final Finder selectAllFinder = find.text('select all'); expect(listView, findsWidgets); /// enable edit mode await tester.longPress(listView.first); await tester.pump(); final Finder checkBoxFinder = find.byType(Checkbox).first; expect(selectAllFinder, findsOneWidget); expect(checkBoxFinder, findsOneWidget); expect(tester.widget<Checkbox>(checkBoxFinder).value, false); await tester.tap(checkBoxFinder); await tester.pump(); expect(tester.widget<Checkbox>(checkBoxFinder).value, true); }); }
flutter/examples/api/test/widgets/scroll_view/list_view.0_test.dart/0
{ "file_path": "flutter/examples/api/test/widgets/scroll_view/list_view.0_test.dart", "repo_id": "flutter", "token_count": 865 }
650
#include "ephemeral/Flutter-Generated.xcconfig"
flutter/examples/flutter_view/macos/Flutter/Flutter-Release.xcconfig/0
{ "file_path": "flutter/examples/flutter_view/macos/Flutter/Flutter-Release.xcconfig", "repo_id": "flutter", "token_count": 19 }
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 Foundation import AppKit import FlutterMacOS /** The code behind a storyboard view which splits a flutter view and a macOS view. */ class MainViewController: NSViewController, NativeViewControllerDelegate { static let emptyString: String = "" static let ping: String = "ping" static let channel: String = "increment" var nativeViewController: NativeViewController? var flutterViewController: FlutterViewController? var messageChannel: FlutterBasicMessageChannel? override func viewDidLoad() { super.viewDidLoad() } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if segue.identifier == "NativeViewControllerSegue" { self.nativeViewController = segue.destinationController as? NativeViewController // Since`MainViewController` owns the platform channel, but not the // UI elements that trigger an action, those UI elements need a reference // to this controller to send messages on the platform channel. self.nativeViewController?.delegate = self } if segue.identifier == "FlutterViewControllerSegue" { self.flutterViewController = segue.destinationController as? FlutterViewController RegisterMethodChannel(registry: self.flutterViewController!) weak var weakSelf = self messageChannel?.setMessageHandler({ (message, reply) in // Dispatch an event, incrementing the counter in this case, when *any* // message is received. // Depending on the order of initialization, the nativeViewController // might not be initialized until this point. weakSelf?.nativeViewController?.didReceiveIncrement() reply(MainViewController.emptyString) }) } } func RegisterMethodChannel(registry: FlutterPluginRegistry) { let registrar = registry.registrar(forPlugin: "") messageChannel = FlutterBasicMessageChannel( name: MainViewController.channel, binaryMessenger: registrar.messenger, codec: FlutterStringCodec.sharedInstance()) } // Call in any instance where `ping` is to be sent through the `increment` // channel. func didTapIncrementButton() { self.messageChannel?.sendMessage(MainViewController.ping) } }
flutter/examples/flutter_view/macos/Runner/MainViewController.swift/0
{ "file_path": "flutter/examples/flutter_view/macos/Runner/MainViewController.swift", "repo_id": "flutter", "token_count": 717 }
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 'package:flutter_test/flutter_test.dart'; import 'package:hello_world/main.dart' as hello_world; void main() { testWidgets('Hello world smoke test', (WidgetTester tester) async { hello_world.main(); // builds the app and schedules a frame but doesn't trigger one await tester.pump(); // triggers a frame expect(find.text('Hello, world!'), findsOneWidget); }); }
flutter/examples/hello_world/test/hello_test.dart/0
{ "file_path": "flutter/examples/hello_world/test/hello_test.dart", "repo_id": "flutter", "token_count": 168 }
653
name: image_list description: Simple Flutter project used for benchmarking image loading over network. version: 1.0.0+1 environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: 1.0.6 characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" meta: 1.12.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dev_dependencies: flutter_test: sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter. async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" leak_tracker: 10.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" leak_tracker_flutter_testing: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" test_api: 0.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vm_service: 14.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - images/coast.jpg # PUBSPEC CHECKSUM: 2ed7
flutter/examples/image_list/pubspec.yaml/0
{ "file_path": "flutter/examples/image_list/pubspec.yaml", "repo_id": "flutter", "token_count": 1055 }
654
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
flutter/examples/layers/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "flutter/examples/layers/macos/Runner/Configs/Debug.xcconfig", "repo_id": "flutter", "token_count": 32 }
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. // This example shows how to perform a simple animation using the underlying // render tree. import 'dart:math' as math; import 'package:flutter/animation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'src/binding.dart'; class NonStopVSync implements TickerProvider { const NonStopVSync(); @override Ticker createTicker(TickerCallback onTick) => Ticker(onTick); } void main() { // We first create a render object that represents a green box. final RenderBox green = RenderDecoratedBox( decoration: const BoxDecoration(color: Color(0xFF00FF00)), ); // Second, we wrap that green box in a render object that forces the green box // to have a specific size. final RenderBox square = RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(width: 200.0, height: 200.0), child: green, ); // Third, we wrap the sized green square in a render object that applies rotation // transform before painting its child. Each frame of the animation, we'll // update the transform of this render object to cause the green square to // spin. final RenderTransform spin = RenderTransform( transform: Matrix4.identity(), alignment: Alignment.center, child: square, ); // Finally, we center the spinning green square... final RenderBox root = RenderPositionedBox( child: spin, ); // and attach it to the window. ViewRenderingFlutterBinding(root: root); // To make the square spin, we use an animation that repeats every 1800 // milliseconds. final AnimationController animation = AnimationController( duration: const Duration(milliseconds: 1800), vsync: const NonStopVSync(), )..repeat(); // The animation will produce a value between 0.0 and 1.0 each frame, but we // want to rotate the square using a value between 0.0 and math.pi. To change // the range of the animation, we use a Tween. final Tween<double> tween = Tween<double>(begin: 0.0, end: math.pi); // We add a listener to the animation, which will be called every time the // animation ticks. animation.addListener(() { // This code runs every tick of the animation and sets a new transform on // the "spin" render object by evaluating the tween on the current value // of the animation. Setting this value will mark a number of dirty bits // inside the render tree, which cause the render tree to repaint with the // new transform value this frame. spin.transform = Matrix4.rotationZ(tween.evaluate(animation)); }); }
flutter/examples/layers/rendering/spinning_square.dart/0
{ "file_path": "flutter/examples/layers/rendering/spinning_square.dart", "repo_id": "flutter", "token_count": 782 }
656
#include "Generated.xcconfig"
flutter/examples/platform_channel_swift/ios/Flutter/Debug.xcconfig/0
{ "file_path": "flutter/examples/platform_channel_swift/ios/Flutter/Debug.xcconfig", "repo_id": "flutter", "token_count": 12 }
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 Cocoa import FlutterMacOS /** The main application window. Performs Flutter app initialization, and handles channel method calls over the `samples.flutter.io/platform_view` channel. */ class MainFlutterWindow: NSWindow { override func awakeFromNib() { let flutterViewController = FlutterViewController() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) RegisterGeneratedPlugins(registry: flutterViewController) RegisterMethodChannel(registry: flutterViewController) super.awakeFromNib() } func RegisterMethodChannel(registry: FlutterPluginRegistry) { let registrar = registry.registrar(forPlugin: "platform_view") let channel = FlutterMethodChannel(name: "samples.flutter.io/platform_view", binaryMessenger: registrar.messenger) channel.setMethodCallHandler({ (call, result) in if (call.method == "switchView") { let count = call.arguments as! Int let controller: NSViewController = PlatformViewController( withCount: count, onClose: { platformViewController in result(platformViewController.count) } ) self.contentViewController?.presentAsSheet(controller) } }) } }
flutter/examples/platform_view/macos/Runner/MainFlutterWindow.swift/0
{ "file_path": "flutter/examples/platform_view/macos/Runner/MainFlutterWindow.swift", "repo_id": "flutter", "token_count": 517 }
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. # For details regarding the *Flutter Fix* feature, see # https://flutter.dev/docs/development/tools/flutter-fix # Please add new fixes to the top of the file, separated by one blank line # from other fixes. In a comment, include a link to the PR where the change # requiring the fix was made. # Every fix must be tested. See the flutter/packages/flutter/test_fixes/README.md # file for instructions on testing these data driven fixes. # For documentation about this file format, see # https://dart.dev/go/data-driven-fixes. # * Fixes in this file are for ColorScheme from the Material library. * # For fixes to # * AppBar: fix_app_bar.yaml # * AppBarTheme: fix_app_bar_theme.yaml # * Material (general): fix_material.yaml # * SliverAppBar: fix_sliver_app_bar.yaml # * TextTheme: fix_text_theme.yaml # * ThemeData: fix_theme_data.yaml # * WidgetState: fix_widget_state.yaml version: 1 transforms: # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate background" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: '' inClass: 'ColorScheme' oneOf: - if: "surface == ''" changes: - kind: 'renameParameter' oldName: 'background' newName: 'surface' - if: "surface != ''" changes: - kind: 'removeParameter' name: 'background' variables: surface: kind: 'fragment' value: 'arguments[surface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate onBackground" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: '' inClass: 'ColorScheme' oneOf: - if: "onSurface == ''" changes: - kind: 'renameParameter' oldName: 'onBackground' newName: 'onSurface' - if: "onSurface != ''" changes: - kind: 'removeParameter' name: 'onBackground' variables: onSurface: kind: 'fragment' value: 'arguments[onSurface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate surfaceVariant" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: '' inClass: 'ColorScheme' oneOf: - if: "surfaceContainerHighest == ''" changes: - kind: 'renameParameter' oldName: 'surfaceVariant' newName: 'surfaceContainerHighest' - if: "surfaceContainerHighest != ''" changes: - kind: 'removeParameter' name: 'surfaceVariant' variables: surfaceContainerHighest: kind: 'fragment' value: 'arguments[surfaceContainerHighest]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate background" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'light' inClass: 'ColorScheme' oneOf: - if: "surface == ''" changes: - kind: 'renameParameter' oldName: 'background' newName: 'surface' - if: "surface != ''" changes: - kind: 'removeParameter' name: 'background' variables: surface: kind: 'fragment' value: 'arguments[surface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate onBackground" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'light' inClass: 'ColorScheme' oneOf: - if: "onSurface == ''" changes: - kind: 'renameParameter' oldName: 'onBackground' newName: 'onSurface' - if: "onSurface != ''" changes: - kind: 'removeParameter' name: 'onBackground' variables: onSurface: kind: 'fragment' value: 'arguments[onSurface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate surfaceVariant" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'light' inClass: 'ColorScheme' oneOf: - if: "surfaceContainerHighest == ''" changes: - kind: 'renameParameter' oldName: 'surfaceVariant' newName: 'surfaceContainerHighest' - if: "surfaceContainerHighest != ''" changes: - kind: 'removeParameter' name: 'surfaceVariant' variables: surfaceContainerHighest: kind: 'fragment' value: 'arguments[surfaceContainerHighest]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate background" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'dark' inClass: 'ColorScheme' oneOf: - if: "surface == ''" changes: - kind: 'renameParameter' oldName: 'background' newName: 'surface' - if: "surface != ''" changes: - kind: 'removeParameter' name: 'background' variables: surface: kind: 'fragment' value: 'arguments[surface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate onBackground" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'dark' inClass: 'ColorScheme' oneOf: - if: "onSurface == ''" changes: - kind: 'renameParameter' oldName: 'onBackground' newName: 'onSurface' - if: "onSurface != ''" changes: - kind: 'removeParameter' name: 'onBackground' variables: onSurface: kind: 'fragment' value: 'arguments[onSurface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate surfaceVariant" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'dark' inClass: 'ColorScheme' oneOf: - if: "surfaceContainerHighest == ''" changes: - kind: 'renameParameter' oldName: 'surfaceVariant' newName: 'surfaceContainerHighest' - if: "surfaceContainerHighest != ''" changes: - kind: 'removeParameter' name: 'surfaceVariant' variables: surfaceContainerHighest: kind: 'fragment' value: 'arguments[surfaceContainerHighest]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate background" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'highContrastLight' inClass: 'ColorScheme' oneOf: - if: "surface == ''" changes: - kind: 'renameParameter' oldName: 'background' newName: 'surface' - if: "surface != ''" changes: - kind: 'removeParameter' name: 'background' variables: surface: kind: 'fragment' value: 'arguments[surface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate onBackground" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'highContrastLight' inClass: 'ColorScheme' oneOf: - if: "onSurface == ''" changes: - kind: 'renameParameter' oldName: 'onBackground' newName: 'onSurface' - if: "onSurface != ''" changes: - kind: 'removeParameter' name: 'onBackground' variables: onSurface: kind: 'fragment' value: 'arguments[onSurface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate surfaceVariant" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'highContrastLight' inClass: 'ColorScheme' oneOf: - if: "surfaceContainerHighest == ''" changes: - kind: 'renameParameter' oldName: 'surfaceVariant' newName: 'surfaceContainerHighest' - if: "surfaceContainerHighest != ''" changes: - kind: 'removeParameter' name: 'surfaceVariant' variables: surfaceContainerHighest: kind: 'fragment' value: 'arguments[surfaceContainerHighest]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate background" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'highContrastDark' inClass: 'ColorScheme' oneOf: - if: "surface == ''" changes: - kind: 'renameParameter' oldName: 'background' newName: 'surface' - if: "surface != ''" changes: - kind: 'removeParameter' name: 'background' variables: surface: kind: 'fragment' value: 'arguments[surface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate onBackground" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'highContrastDark' inClass: 'ColorScheme' oneOf: - if: "onSurface == ''" changes: - kind: 'renameParameter' oldName: 'onBackground' newName: 'onSurface' - if: "onSurface != ''" changes: - kind: 'removeParameter' name: 'onBackground' variables: onSurface: kind: 'fragment' value: 'arguments[onSurface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate surfaceVariant" date: 2023-12-04 element: uris: [ 'material.dart' ] constructor: 'highContrastDark' inClass: 'ColorScheme' oneOf: - if: "surfaceContainerHighest == ''" changes: - kind: 'renameParameter' oldName: 'surfaceVariant' newName: 'surfaceContainerHighest' - if: "surfaceContainerHighest != ''" changes: - kind: 'removeParameter' name: 'surfaceVariant' variables: surfaceContainerHighest: kind: 'fragment' value: 'arguments[surfaceContainerHighest]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate background" date: 2023-12-04 element: uris: [ 'material.dart' ] method: 'copyWith' inClass: 'ColorScheme' oneOf: - if: "surface == ''" changes: - kind: 'renameParameter' oldName: 'background' newName: 'surface' - if: "surface != ''" changes: - kind: 'removeParameter' name: 'background' variables: surface: kind: 'fragment' value: 'arguments[surface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate onBackground" date: 2023-12-04 element: uris: [ 'material.dart' ] method: 'copyWith' inClass: 'ColorScheme' oneOf: - if: "onSurface == ''" changes: - kind: 'renameParameter' oldName: 'onBackground' newName: 'onSurface' - if: "onSurface != ''" changes: - kind: 'removeParameter' name: 'onBackground' variables: onSurface: kind: 'fragment' value: 'arguments[onSurface]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate surfaceVariant" date: 2023-12-04 element: uris: [ 'material.dart' ] method: 'copyWith' inClass: 'ColorScheme' oneOf: - if: "surfaceContainerHighest == ''" changes: - kind: 'renameParameter' oldName: 'surfaceVariant' newName: 'surfaceContainerHighest' - if: "surfaceContainerHighest != ''" changes: - kind: 'removeParameter' name: 'surfaceVariant' variables: surfaceContainerHighest: kind: 'fragment' value: 'arguments[surfaceContainerHighest]' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate 'background' to 'surface'" date: 2023-12-04 element: uris: [ 'material.dart' ] getter: 'background' inClass: 'ColorScheme' changes: - kind: 'rename' newName: 'surface' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate 'onBackground' to 'onSurface'" date: 2023-12-04 element: uris: [ 'material.dart' ] getter: 'onBackground' inClass: 'ColorScheme' changes: - kind: 'rename' newName: 'onSurface' # Changes made in https://github.com/flutter/flutter/pull/138521 - title: "Migrate 'surfaceVariant' to 'surfaceContainerHighest'" date: 2023-12-04 element: uris: [ 'material.dart' ] getter: 'surfaceVariant' inClass: 'ColorScheme' changes: - kind: 'rename' newName: 'surfaceContainerHighest' # Changes made in https://github.com/flutter/flutter/pull/93427 - title: "Remove 'primaryVariant' and 'secondaryVariant'" date: 2021-11-19 element: uris: [ 'material.dart' ] constructor: '' inClass: 'ColorScheme' changes: - kind: 'removeParameter' name: 'primaryVariant' - kind: 'removeParameter' name: 'secondaryVariant' # Changes made in https://github.com/flutter/flutter/pull/93427 - title: "Remove 'primaryVariant' and 'secondaryVariant'" date: 2021-11-19 element: uris: [ 'material.dart' ] constructor: 'light' inClass: 'ColorScheme' changes: - kind: 'removeParameter' name: 'primaryVariant' - kind: 'removeParameter' name: 'secondaryVariant' # Changes made in https://github.com/flutter/flutter/pull/93427 - title: "Remove 'primaryVariant' and 'secondaryVariant'" date: 2021-11-19 element: uris: [ 'material.dart' ] constructor: 'dark' inClass: 'ColorScheme' changes: - kind: 'removeParameter' name: 'primaryVariant' - kind: 'removeParameter' name: 'secondaryVariant' # Changes made in https://github.com/flutter/flutter/pull/93427 - title: "Remove 'primaryVariant' and 'secondaryVariant'" date: 2021-11-19 element: uris: [ 'material.dart' ] constructor: 'highContrastLight' inClass: 'ColorScheme' changes: - kind: 'removeParameter' name: 'primaryVariant' - kind: 'removeParameter' name: 'secondaryVariant' # Changes made in https://github.com/flutter/flutter/pull/93427 - title: "Remove 'primaryVariant' and 'secondaryVariant'" date: 2021-11-19 element: uris: [ 'material.dart' ] constructor: 'highContrastDark' inClass: 'ColorScheme' changes: - kind: 'removeParameter' name: 'primaryVariant' - kind: 'removeParameter' name: 'secondaryVariant' # Changes made in https://github.com/flutter/flutter/pull/93427 - title: "Remove 'primaryVariant' and 'secondaryVariant'" date: 2021-11-19 element: uris: [ 'material.dart' ] method: 'copyWith' inClass: 'ColorScheme' changes: - kind: 'removeParameter' name: 'primaryVariant' - kind: 'removeParameter' name: 'secondaryVariant' # Changes made in https://github.com/flutter/flutter/pull/93427 - title: "Migrate 'primaryVariant' to 'primaryContainer'" date: 2021-11-19 element: uris: [ 'material.dart' ] getter: 'primaryVariant' inClass: 'ColorScheme' changes: - kind: 'rename' newName: 'primaryContainer' # Changes made in https://github.com/flutter/flutter/pull/93427 - title: "Migrate 'secondaryVariant' to 'secondaryContainer'" date: 2021-11-19 element: uris: [ 'material.dart' ] getter: 'secondaryVariant' inClass: 'ColorScheme' changes: - kind: 'rename' newName: 'secondaryContainer' # Before adding a new fix: read instructions at the top of this file.
flutter/packages/flutter/lib/fix_data/fix_material/fix_color_scheme.yaml/0
{ "file_path": "flutter/packages/flutter/lib/fix_data/fix_material/fix_color_scheme.yaml", "repo_id": "flutter", "token_count": 7314 }
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. # For details regarding the *Flutter Fix* feature, see # https://flutter.dev/docs/development/tools/flutter-fix # Please add new fixes to the top of the file, separated by one blank line # from other fixes. In a comment, include a link to the PR where the change # requiring the fix was made. # Every fix must be tested. See the flutter/packages/flutter/test_fixes/README.md # file for instructions on testing these data driven fixes. # For documentation about this file format, see # https://dart.dev/go/data-driven-fixes. # * Fixes in this file are for MediaQuery and MediaQueryData from the widgets library. * version: 1 transforms: # Change made in https://github.com/flutter/flutter/pull/128522 - title: "Migrate to 'textScaler'" date: 2023-06-09 element: uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] method: 'copyWith' inClass: 'MediaQueryData' changes: - kind: 'addParameter' index: 3 name: 'textScaler' style: optional_named argumentValue: expression: 'TextScaler.linear({% textScaleFactor %})' requiredIf: "textScaleFactor != ''" - kind: 'removeParameter' name: 'textScaleFactor' variables: textScaleFactor: kind: 'fragment' value: 'arguments[textScaleFactor]' # Change made in https://github.com/flutter/flutter/pull/128522 - title: "Migrate to 'textScaler'" date: 2023-06-09 element: uris: [ 'widgets.dart', 'material.dart', 'cupertino.dart' ] constructor: '' inClass: 'MediaQueryData' changes: - kind: 'addParameter' index: 3 name: 'textScaler' style: optional_named argumentValue: expression: 'TextScaler.linear({% textScaleFactor %})' requiredIf: "textScaleFactor != ''" - kind: 'removeParameter' name: 'textScaleFactor' variables: textScaleFactor: kind: 'fragment' value: 'arguments[textScaleFactor]' # Before adding a new fix: read instructions at the top of this file.
flutter/packages/flutter/lib/fix_data/fix_widgets/fix_media_query.yaml/0
{ "file_path": "flutter/packages/flutter/lib/fix_data/fix_widgets/fix_media_query.yaml", "repo_id": "flutter", "token_count": 843 }
660
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; export 'dart:ui' show Offset; /// An abstract class providing an interface for evaluating a parametric curve. /// /// A parametric curve transforms a parameter (hence the name) `t` along a curve /// to the value of the curve at that value of `t`. The curve can be of /// arbitrary dimension, but is typically a 1D, 2D, or 3D curve. /// /// See also: /// /// * [Curve], a 1D animation easing curve that starts at 0.0 and ends at 1.0. /// * [Curve2D], a parametric curve that transforms the parameter to a 2D point. abstract class ParametricCurve<T> { /// Abstract const constructor to enable subclasses to provide /// const constructors so that they can be used in const expressions. const ParametricCurve(); /// Returns the value of the curve at point `t`. /// /// This method asserts that t is between 0 and 1 before delegating to /// [transformInternal]. /// /// It is recommended that subclasses override [transformInternal] instead of /// this function, as the above case is already handled in the default /// implementation of [transform], which delegates the remaining logic to /// [transformInternal]. T transform(double t) { assert(t >= 0.0 && t <= 1.0, 'parametric value $t is outside of [0, 1] range.'); return transformInternal(t); } /// Returns the value of the curve at point `t`. /// /// The given parametric value `t` will be between 0.0 and 1.0, inclusive. @protected T transformInternal(double t) { throw UnimplementedError(); } @override String toString() => objectRuntimeType(this, 'ParametricCurve'); } /// An parametric animation easing curve, i.e. a mapping of the unit interval to /// the unit interval. /// /// Easing curves are used to adjust the rate of change of an animation over /// time, allowing them to speed up and slow down, rather than moving at a /// constant rate. /// /// A [Curve] must map t=0.0 to 0.0 and t=1.0 to 1.0. /// /// See also: /// /// * [Curves], a collection of common animation easing curves. /// * [CurveTween], which can be used to apply a [Curve] to an [Animation]. /// * [Canvas.drawArc], which draws an arc, and has nothing to do with easing /// curves. /// * [Animatable], for a more flexible interface that maps fractions to /// arbitrary values. @immutable abstract class Curve extends ParametricCurve<double> { /// Abstract const constructor to enable subclasses to provide /// const constructors so that they can be used in const expressions. const Curve(); /// Returns the value of the curve at point `t`. /// /// This function must ensure the following: /// - The value of `t` must be between 0.0 and 1.0 /// - Values of `t`=0.0 and `t`=1.0 must be mapped to 0.0 and 1.0, /// respectively. /// /// It is recommended that subclasses override [transformInternal] instead of /// this function, as the above cases are already handled in the default /// implementation of [transform], which delegates the remaining logic to /// [transformInternal]. @override double transform(double t) { if (t == 0.0 || t == 1.0) { return t; } return super.transform(t); } /// Returns a new curve that is the reversed inversion of this one. /// /// This is often useful with [CurvedAnimation.reverseCurve]. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_bounce_in.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_flipped.mp4} /// /// See also: /// /// * [FlippedCurve], the class that is used to implement this getter. /// * [ReverseAnimation], which reverses an [Animation] rather than a [Curve]. /// * [CurvedAnimation], which can take a separate curve and reverse curve. Curve get flipped => FlippedCurve(this); } /// The identity map over the unit interval. /// /// See [Curves.linear] for an instance of this class. class _Linear extends Curve { const _Linear._(); @override double transformInternal(double t) => t; } /// A sawtooth curve that repeats a given number of times over the unit interval. /// /// The curve rises linearly from 0.0 to 1.0 and then falls discontinuously back /// to 0.0 each iteration. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_sawtooth.mp4} class SawTooth extends Curve { /// Creates a sawtooth curve. const SawTooth(this.count); /// The number of repetitions of the sawtooth pattern in the unit interval. final int count; @override double transformInternal(double t) { t *= count; return t - t.truncateToDouble(); } @override String toString() { return '${objectRuntimeType(this, 'SawTooth')}($count)'; } } /// A curve that is 0.0 until [begin], then curved (according to [curve]) from /// 0.0 at [begin] to 1.0 at [end], then remains 1.0 past [end]. /// /// An [Interval] can be used to delay an animation. For example, a six second /// animation that uses an [Interval] with its [begin] set to 0.5 and its [end] /// set to 1.0 will essentially become a three-second animation that starts /// three seconds later. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_interval.mp4} class Interval extends Curve { /// Creates an interval curve. const Interval(this.begin, this.end, { this.curve = Curves.linear }); /// The largest value for which this interval is 0.0. /// /// From t=0.0 to t=[begin], the interval's value is 0.0. final double begin; /// The smallest value for which this interval is 1.0. /// /// From t=[end] to t=1.0, the interval's value is 1.0. final double end; /// The curve to apply between [begin] and [end]. final Curve curve; @override double transformInternal(double t) { assert(begin >= 0.0); assert(begin <= 1.0); assert(end >= 0.0); assert(end <= 1.0); assert(end >= begin); t = clampDouble((t - begin) / (end - begin), 0.0, 1.0); if (t == 0.0 || t == 1.0) { return t; } return curve.transform(t); } @override String toString() { if (curve is! _Linear) { return '${objectRuntimeType(this, 'Interval')}($begin\u22EF$end)\u27A9$curve'; } return '${objectRuntimeType(this, 'Interval')}($begin\u22EF$end)'; } } /// A curve that progresses according to [beginCurve] until [split], then /// according to [endCurve]. /// /// Split curves are useful in situations where a widget must track the /// user's finger (which requires a linear animation), but can also be flung /// using a curve specified with the [endCurve] argument, after the finger is /// released. In such a case, the value of [split] would be the progress /// of the animation at the time when the finger was released. /// /// For example, if [split] is set to 0.5, [beginCurve] is [Curves.linear], /// and [endCurve] is [Curves.easeOutCubic], then the bottom-left quarter of the /// curve will be a straight line, and the top-right quarter will contain the /// entire [Curves.easeOutCubic] curve. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_split.mp4} class Split extends Curve { /// Creates a split curve. const Split( this.split, { this.beginCurve = Curves.linear, this.endCurve = Curves.easeOutCubic, }); /// The progress value separating [beginCurve] from [endCurve]. /// /// The value before which the curve progresses according to [beginCurve] and /// after which the curve progresses according to [endCurve]. /// /// When t is exactly `split`, the curve has the value `split`. /// /// Must be between 0 and 1.0, inclusively. final double split; /// The curve to use before [split] is reached. /// /// Defaults to [Curves.linear]. final Curve beginCurve; /// The curve to use after [split] is reached. /// /// Defaults to [Curves.easeOutCubic]. final Curve endCurve; @override double transform(double t) { assert(t >= 0.0 && t <= 1.0); assert(split >= 0.0 && split <= 1.0); if (t == 0.0 || t == 1.0) { return t; } if (t == split) { return split; } if (t < split) { final double curveProgress = t / split; final double transformed = beginCurve.transform(curveProgress); return lerpDouble(0, split, transformed)!; } else { final double curveProgress = (t - split) / (1 - split); final double transformed = endCurve.transform(curveProgress); return lerpDouble(split, 1, transformed)!; } } @override String toString() { return '${describeIdentity(this)}($split, $beginCurve, $endCurve)'; } } /// A curve that is 0.0 until it hits the threshold, then it jumps to 1.0. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_threshold.mp4} class Threshold extends Curve { /// Creates a threshold curve. const Threshold(this.threshold); /// The value before which the curve is 0.0 and after which the curve is 1.0. /// /// When t is exactly [threshold], the curve has the value 1.0. final double threshold; @override double transformInternal(double t) { assert(threshold >= 0.0); assert(threshold <= 1.0); return t < threshold ? 0.0 : 1.0; } } /// A cubic polynomial mapping of the unit interval. /// /// The [Curves] class contains some commonly used cubic curves: /// /// * [Curves.fastLinearToSlowEaseIn] /// * [Curves.ease] /// * [Curves.easeIn] /// * [Curves.easeInToLinear] /// * [Curves.easeInSine] /// * [Curves.easeInQuad] /// * [Curves.easeInCubic] /// * [Curves.easeInQuart] /// * [Curves.easeInQuint] /// * [Curves.easeInExpo] /// * [Curves.easeInCirc] /// * [Curves.easeInBack] /// * [Curves.easeOut] /// * [Curves.linearToEaseOut] /// * [Curves.easeOutSine] /// * [Curves.easeOutQuad] /// * [Curves.easeOutCubic] /// * [Curves.easeOutQuart] /// * [Curves.easeOutQuint] /// * [Curves.easeOutExpo] /// * [Curves.easeOutCirc] /// * [Curves.easeOutBack] /// * [Curves.easeInOut] /// * [Curves.easeInOutSine] /// * [Curves.easeInOutQuad] /// * [Curves.easeInOutCubic] /// * [Curves.easeInOutQuart] /// * [Curves.easeInOutQuint] /// * [Curves.easeInOutExpo] /// * [Curves.easeInOutCirc] /// * [Curves.easeInOutBack] /// * [Curves.fastOutSlowIn] /// * [Curves.slowMiddle] /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_fast_linear_to_slow_ease_in.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_to_linear.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_sine.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_quad.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_cubic.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_quart.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_quint.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_expo.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_circ.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_back.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_linear_to_ease_out.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_sine.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_quad.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_cubic.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_quart.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_quint.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_expo.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_circ.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_back.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_sine.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_quad.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_cubic.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_quart.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_quint.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_expo.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_circ.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_back.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_fast_out_slow_in.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_slow_middle.mp4} /// /// The [Cubic] class implements third-order Bézier curves. /// /// See also: /// /// * [Curves], where many more predefined curves are available. /// * [CatmullRomCurve], a curve which passes through specific values. class Cubic extends Curve { /// Creates a cubic curve. /// /// Rather than creating a new instance, consider using one of the common /// cubic curves in [Curves]. const Cubic(this.a, this.b, this.c, this.d); /// The x coordinate of the first control point. /// /// The line through the point (0, 0) and the first control point is tangent /// to the curve at the point (0, 0). final double a; /// The y coordinate of the first control point. /// /// The line through the point (0, 0) and the first control point is tangent /// to the curve at the point (0, 0). final double b; /// The x coordinate of the second control point. /// /// The line through the point (1, 1) and the second control point is tangent /// to the curve at the point (1, 1). final double c; /// The y coordinate of the second control point. /// /// The line through the point (1, 1) and the second control point is tangent /// to the curve at the point (1, 1). final double d; static const double _cubicErrorBound = 0.001; double _evaluateCubic(double a, double b, double m) { return 3 * a * (1 - m) * (1 - m) * m + 3 * b * (1 - m) * m * m + m * m * m; } @override double transformInternal(double t) { double start = 0.0; double end = 1.0; while (true) { final double midpoint = (start + end) / 2; final double estimate = _evaluateCubic(a, c, midpoint); if ((t - estimate).abs() < _cubicErrorBound) { return _evaluateCubic(b, d, midpoint); } if (estimate < t) { start = midpoint; } else { end = midpoint; } } } @override String toString() { return '${objectRuntimeType(this, 'Cubic')}(${a.toStringAsFixed(2)}, ${b.toStringAsFixed(2)}, ${c.toStringAsFixed(2)}, ${d.toStringAsFixed(2)})'; } } /// A cubic polynomial composed of two curves that share a common center point. /// /// The curve runs through three points: (0,0), the [midpoint], and (1,1). /// /// The [Curves] class contains a curve defined with this class: /// [Curves.easeInOutCubicEmphasized]. /// /// The [ThreePointCubic] class implements third-order Bézier curves, where two /// curves share an interior [midpoint] that the curve passes through. If the /// control points surrounding the middle point ([b1], and [a2]) are not /// colinear with the middle point, then the curve's derivative will have a /// discontinuity (a cusp) at the shared middle point. /// /// See also: /// /// * [Curves], where many more predefined curves are available. /// * [Cubic], which defines a single cubic polynomial. /// * [CatmullRomCurve], a curve which passes through specific values. class ThreePointCubic extends Curve { /// Creates two cubic curves that share a common control point. /// /// Rather than creating a new instance, consider using one of the common /// three-point cubic curves in [Curves]. /// /// The arguments correspond to the control points for the two curves, /// including the [midpoint], but do not include the two implied end points at /// (0,0) and (1,1), which are fixed. const ThreePointCubic(this.a1, this.b1, this.midpoint, this.a2, this.b2); /// The coordinates of the first control point of the first curve. /// /// The line through the point (0, 0) and this control point is tangent to the /// curve at the point (0, 0). final Offset a1; /// The coordinates of the second control point of the first curve. /// /// The line through the [midpoint] and this control point is tangent to the /// curve approaching the [midpoint]. final Offset b1; /// The coordinates of the middle shared point. /// /// The curve will go through this point. If the control points surrounding /// this middle point ([b1], and [a2]) are not colinear with this point, then /// the curve's derivative will have a discontinuity (a cusp) at this point. final Offset midpoint; /// The coordinates of the first control point of the second curve. /// /// The line through the [midpoint] and this control point is tangent to the /// curve approaching the [midpoint]. final Offset a2; /// The coordinates of the second control point of the second curve. /// /// The line through the point (1, 1) and this control point is tangent to the /// curve at (1, 1). final Offset b2; @override double transformInternal(double t) { final bool firstCurve = t < midpoint.dx; final double scaleX = firstCurve ? midpoint.dx : 1.0 - midpoint.dx; final double scaleY = firstCurve ? midpoint.dy : 1.0 - midpoint.dy; final double scaledT = (t - (firstCurve ? 0.0 : midpoint.dx)) / scaleX; if (firstCurve) { return Cubic( a1.dx / scaleX, a1.dy / scaleY, b1.dx / scaleX, b1.dy / scaleY, ).transform(scaledT) * scaleY; } else { return Cubic( (a2.dx - midpoint.dx) / scaleX, (a2.dy - midpoint.dy) / scaleY, (b2.dx - midpoint.dx) / scaleX, (b2.dy - midpoint.dy) / scaleY, ).transform(scaledT) * scaleY + midpoint.dy; } } @override String toString() { return '${objectRuntimeType(this, 'ThreePointCubic($a1, $b1, $midpoint, $a2, $b2)')} '; } } /// Abstract class that defines an API for evaluating 2D parametric curves. /// /// [Curve2D] differs from [Curve] in that the values interpolated are [Offset] /// values instead of [double] values, hence the "2D" in the name. They both /// take a single double `t` that has a range of 0.0 to 1.0, inclusive, as input /// to the [transform] function . Unlike [Curve], [Curve2D] is not required to /// map `t=0.0` and `t=1.0` to specific output values. /// /// The interpolated `t` value given to [transform] represents the progression /// along the curve, but it doesn't necessarily progress at a constant velocity, so /// incrementing `t` by, say, 0.1 might move along the curve by quite a lot at one /// part of the curve, or hardly at all in another part of the curve, depending /// on the definition of the curve. /// /// {@tool dartpad} /// This example shows how to use a [Curve2D] to modify the position of a widget /// so that it can follow an arbitrary path. /// /// ** See code in examples/api/lib/animation/curves/curve2_d.0.dart ** /// {@end-tool} /// abstract class Curve2D extends ParametricCurve<Offset> { /// Abstract const constructor to enable subclasses to provide const /// constructors so that they can be used in const expressions. const Curve2D(); /// Generates a list of samples with a recursive subdivision until a tolerance /// of `tolerance` is reached. /// /// Samples are generated in order. /// /// Samples can be used to render a curve efficiently, since the samples /// constitute line segments which vary in size with the curvature of the /// curve. They can also be used to quickly approximate the value of the curve /// by searching for the desired range in X and linearly interpolating between /// samples to obtain an approximation of Y at the desired X value. The /// implementation of [CatmullRomCurve] uses samples for this purpose /// internally. /// /// The tolerance is computed as the area of a triangle formed by a new point /// and the preceding and following point. /// /// See also: /// /// * Luiz Henrique de Figueire's Graphics Gem on [the algorithm](http://ariel.chronotext.org/dd/defigueiredo93adaptive.pdf). Iterable<Curve2DSample> generateSamples({ double start = 0.0, double end = 1.0, double tolerance = 1e-10, }) { // The sampling algorithm is: // 1. Evaluate the area of the triangle (a proxy for the "flatness" of the // curve) formed by two points and a test point. // 2. If the area of the triangle is small enough (below tolerance), then // the two points form the final segment. // 3. If the area is still too large, divide the interval into two parts // using a random subdivision point to avoid aliasing. // 4. Recursively sample the two parts. // // This algorithm concentrates samples in areas of high curvature. assert(end > start); // We want to pick a random seed that will keep the result stable if // evaluated again, so we use the first non-generated control point. final math.Random rand = math.Random(samplingSeed); bool isFlat(Offset p, Offset q, Offset r) { // Calculates the area of the triangle given by the three points. final Offset pr = p - r; final Offset qr = q - r; final double z = pr.dx * qr.dy - qr.dx * pr.dy; return (z * z) < tolerance; } final Curve2DSample first = Curve2DSample(start, transform(start)); final Curve2DSample last = Curve2DSample(end, transform(end)); final List<Curve2DSample> samples = <Curve2DSample>[first]; void sample(Curve2DSample p, Curve2DSample q, {bool forceSubdivide = false}) { // Pick a random point somewhat near the center, which avoids aliasing // problems with periodic curves. final double t = p.t + (0.45 + 0.1 * rand.nextDouble()) * (q.t - p.t); final Curve2DSample r = Curve2DSample(t, transform(t)); if (!forceSubdivide && isFlat(p.value, q.value, r.value)) { samples.add(q); } else { sample(p, r); sample(r, q); } } // If the curve starts and ends on the same point, then we force it to // subdivide at least once, because otherwise it will terminate immediately. sample( first, last, forceSubdivide: (first.value.dx - last.value.dx).abs() < tolerance && (first.value.dy - last.value.dy).abs() < tolerance, ); return samples; } /// Returns a seed value used by [generateSamples] to seed a random number /// generator to avoid sample aliasing. /// /// Subclasses should override this and provide a custom seed. /// /// The value returned should be the same each time it is called, unless the /// curve definition changes. @protected int get samplingSeed => 0; /// Returns the parameter `t` that corresponds to the given x value of the spline. /// /// This will only work properly for curves which are single-valued in x /// (where every value of `x` maps to only one value in 'y', i.e. the curve /// does not loop or curve back over itself). For curves that are not /// single-valued, it will return the parameter for only one of the values at /// the given `x` location. double findInverse(double x) { double start = 0.0; double end = 1.0; late double mid; double offsetToOrigin(double pos) => x - transform(pos).dx; // Use a binary search to find the inverse point within 1e-6, or 100 // subdivisions, whichever comes first. const double errorLimit = 1e-6; int count = 100; final double startValue = offsetToOrigin(start); while ((end - start) / 2.0 > errorLimit && count > 0) { mid = (end + start) / 2.0; final double value = offsetToOrigin(mid); if (value.sign == startValue.sign) { start = mid; } else { end = mid; } count--; } return mid; } } /// A class that holds a sample of a 2D parametric curve, containing the [value] /// (the X, Y coordinates) of the curve at the parametric value [t]. /// /// See also: /// /// * [Curve2D.generateSamples], which generates samples of this type. /// * [Curve2D], a parametric curve that maps a double parameter to a 2D location. class Curve2DSample { /// Creates an object that holds a sample; used with [Curve2D] subclasses. const Curve2DSample(this.t, this.value); /// The parametric location of this sample point along the curve. final double t; /// The value (the X, Y coordinates) of the curve at parametric value [t]. final Offset value; @override String toString() { return '[(${value.dx.toStringAsFixed(2)}, ${value.dy.toStringAsFixed(2)}), ${t.toStringAsFixed(2)}]'; } } /// A 2D spline that passes smoothly through the given control points using a /// centripetal Catmull-Rom spline. /// /// When the curve is evaluated with [transform], the output values will move /// smoothly from one control point to the next, passing through the control /// points. /// /// {@template flutter.animation.CatmullRomSpline} /// Unlike most cubic splines, Catmull-Rom splines have the advantage that their /// curves pass through the control points given to them. They are cubic /// polynomial representations, and, in fact, Catmull-Rom splines can be /// converted mathematically into cubic splines. This class implements a /// "centripetal" Catmull-Rom spline. The term centripetal implies that it won't /// form loops or self-intersections within a single segment. /// {@endtemplate} /// /// See also: /// * [Centripetal Catmull–Rom splines](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline) /// on Wikipedia. /// * [Parameterization and Applications of Catmull-Rom Curves](http://faculty.cs.tamu.edu/schaefer/research/cr_cad.pdf), /// a paper on using Catmull-Rom splines. /// * [CatmullRomCurve], an animation curve that uses a [CatmullRomSpline] as its /// internal representation. class CatmullRomSpline extends Curve2D { /// Constructs a centripetal Catmull-Rom spline curve. /// /// The `controlPoints` argument is a list of four or more points that /// describe the points that the curve must pass through. /// /// The optional `tension` argument controls how tightly the curve approaches /// the given `controlPoints`. It must be in the range 0.0 to 1.0, inclusive. It /// defaults to 0.0, which provides the smoothest curve. A value of 1.0 /// produces a linear interpolation between points. /// /// The optional `endHandle` and `startHandle` points are the beginning and /// ending handle positions. If not specified, they are created automatically /// by extending the line formed by the first and/or last line segment in the /// `controlPoints`, respectively. The spline will not go through these handle /// points, but they will affect the slope of the line at the beginning and /// end of the spline. The spline will attempt to match the slope of the line /// formed by the start or end handle and the neighboring first or last /// control point. The default is chosen so that the slope of the line at the /// ends matches that of the first or last line segment in the control points. /// /// The `controlPoints` list must contain at least four control points to /// interpolate. /// /// The internal curve data structures are lazily computed the first time /// [transform] is called. If you would rather pre-compute the structures, /// use [CatmullRomSpline.precompute] instead. CatmullRomSpline( List<Offset> controlPoints, { double tension = 0.0, Offset? startHandle, Offset? endHandle, }) : assert(tension <= 1.0, 'tension $tension must not be greater than 1.0.'), assert(tension >= 0.0, 'tension $tension must not be negative.'), assert(controlPoints.length > 3, 'There must be at least four control points to create a CatmullRomSpline.'), _controlPoints = controlPoints, _startHandle = startHandle, _endHandle = endHandle, _tension = tension, _cubicSegments = <List<Offset>>[]; /// Constructs a centripetal Catmull-Rom spline curve. /// /// The same as [CatmullRomSpline.new], except that the internal data /// structures are precomputed instead of being computed lazily. CatmullRomSpline.precompute( List<Offset> controlPoints, { double tension = 0.0, Offset? startHandle, Offset? endHandle, }) : assert(tension <= 1.0, 'tension $tension must not be greater than 1.0.'), assert(tension >= 0.0, 'tension $tension must not be negative.'), assert(controlPoints.length > 3, 'There must be at least four control points to create a CatmullRomSpline.'), _controlPoints = null, _startHandle = null, _endHandle = null, _tension = null, _cubicSegments = _computeSegments(controlPoints, tension, startHandle: startHandle, endHandle: endHandle); static List<List<Offset>> _computeSegments( List<Offset> controlPoints, double tension, { Offset? startHandle, Offset? endHandle, }) { assert( startHandle == null || startHandle.isFinite, 'The provided startHandle of CatmullRomSpline must be finite. The ' 'startHandle given was $startHandle.' ); assert( endHandle == null || endHandle.isFinite, 'The provided endHandle of CatmullRomSpline must be finite. The endHandle ' 'given was $endHandle.' ); assert(() { for (int index = 0; index < controlPoints.length; index++) { if (!controlPoints[index].isFinite) { throw FlutterError( 'The provided CatmullRomSpline control point at index $index is not ' 'finite. The control point given was ${controlPoints[index]}.' ); } } return true; }()); // If not specified, select the first and last control points (which are // handles: they are not intersected by the resulting curve) so that they // extend the first and last segments, respectively. startHandle ??= controlPoints[0] * 2.0 - controlPoints[1]; endHandle ??= controlPoints.last * 2.0 - controlPoints[controlPoints.length - 2]; final List<Offset> allPoints = <Offset>[ startHandle, ...controlPoints, endHandle, ]; // An alpha of 0.5 is what makes it a centripetal Catmull-Rom spline. A // value of 0.0 would make it a uniform Catmull-Rom spline, and a value of // 1.0 would make it a chordal Catmull-Rom spline. Non-centripetal values // for alpha can give self-intersecting behavior or looping within a // segment. const double alpha = 0.5; final double reverseTension = 1.0 - tension; final List<List<Offset>> result = <List<Offset>>[]; for (int i = 0; i < allPoints.length - 3; ++i) { final List<Offset> curve = <Offset>[allPoints[i], allPoints[i + 1], allPoints[i + 2], allPoints[i + 3]]; final Offset diffCurve10 = curve[1] - curve[0]; final Offset diffCurve21 = curve[2] - curve[1]; final Offset diffCurve32 = curve[3] - curve[2]; final double t01 = math.pow(diffCurve10.distance, alpha).toDouble(); final double t12 = math.pow(diffCurve21.distance, alpha).toDouble(); final double t23 = math.pow(diffCurve32.distance, alpha).toDouble(); final Offset m1 = (diffCurve21 + (diffCurve10 / t01 - (curve[2] - curve[0]) / (t01 + t12)) * t12) * reverseTension; final Offset m2 = (diffCurve21 + (diffCurve32 / t23 - (curve[3] - curve[1]) / (t12 + t23)) * t12) * reverseTension; final Offset sumM12 = m1 + m2; final List<Offset> segment = <Offset>[ diffCurve21 * -2.0 + sumM12, diffCurve21 * 3.0 - m1 - sumM12, m1, curve[1], ]; result.add(segment); } return result; } // The list of control point lists for each cubic segment of the spline. final List<List<Offset>> _cubicSegments; // This is non-empty only if the _cubicSegments are being computed lazily. final List<Offset>? _controlPoints; final Offset? _startHandle; final Offset? _endHandle; final double? _tension; void _initializeIfNeeded() { if (_cubicSegments.isNotEmpty) { return; } _cubicSegments.addAll( _computeSegments(_controlPoints!, _tension!, startHandle: _startHandle, endHandle: _endHandle), ); } @override @protected int get samplingSeed { _initializeIfNeeded(); final Offset seedPoint = _cubicSegments[0][1]; return ((seedPoint.dx + seedPoint.dy) * 10000).round(); } @override Offset transformInternal(double t) { _initializeIfNeeded(); final double length = _cubicSegments.length.toDouble(); final double position; final double localT; final int index; if (t < 1.0) { position = t * length; localT = position % 1.0; index = position.floor(); } else { position = length; localT = 1.0; index = _cubicSegments.length - 1; } final List<Offset> cubicControlPoints = _cubicSegments[index]; final double localT2 = localT * localT; return cubicControlPoints[0] * localT2 * localT + cubicControlPoints[1] * localT2 + cubicControlPoints[2] * localT + cubicControlPoints[3]; } } /// An animation easing curve that passes smoothly through the given control /// points using a centripetal Catmull-Rom spline. /// /// When this curve is evaluated with [transform], the values will interpolate /// smoothly from one control point to the next, passing through (0.0, 0.0), the /// given points, and then (1.0, 1.0). /// /// {@macro flutter.animation.CatmullRomSpline} /// /// This class uses a centripetal Catmull-Rom curve (a [CatmullRomSpline]) as /// its internal representation. The term centripetal implies that it won't form /// loops or self-intersections within a single segment, and corresponds to a /// Catmull-Rom α (alpha) value of 0.5. /// /// See also: /// /// * [CatmullRomSpline], the 2D spline that this curve uses to generate its values. /// * A Wikipedia article on [centripetal Catmull-Rom splines](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline). /// * [CatmullRomCurve.new] for a description of the constraints put on the /// input control points. /// * This [paper on using Catmull-Rom splines](http://faculty.cs.tamu.edu/schaefer/research/cr_cad.pdf). class CatmullRomCurve extends Curve { /// Constructs a centripetal [CatmullRomCurve]. /// /// It takes a list of two or more points that describe the points that the /// curve must pass through. See [controlPoints] for a description of the /// restrictions placed on control points. In addition to the given /// [controlPoints], the curve will begin with an implicit control point at /// (0.0, 0.0) and end with an implicit control point at (1.0, 1.0), so that /// the curve begins and ends at those points. /// /// The optional [tension] argument controls how tightly the curve approaches /// the given `controlPoints`. It must be in the range 0.0 to 1.0, inclusive. It /// defaults to 0.0, which provides the smoothest curve. A value of 1.0 /// is equivalent to a linear interpolation between points. /// /// The internal curve data structures are lazily computed the first time /// [transform] is called. If you would rather pre-compute the curve, use /// [CatmullRomCurve.precompute] instead. /// /// See also: /// /// * This [paper on using Catmull-Rom splines](http://faculty.cs.tamu.edu/schaefer/research/cr_cad.pdf). CatmullRomCurve(this.controlPoints, {this.tension = 0.0}) : assert(() { return validateControlPoints( controlPoints, tension: tension, reasons: _debugAssertReasons..clear(), ); }(), 'control points $controlPoints could not be validated:\n ${_debugAssertReasons.join('\n ')}'), // Pre-compute samples so that we don't have to evaluate the spline's inverse // all the time in transformInternal. _precomputedSamples = <Curve2DSample>[]; /// Constructs a centripetal [CatmullRomCurve]. /// /// Same as [CatmullRomCurve.new], but it precomputes the internal curve data /// structures for a more predictable computation load. CatmullRomCurve.precompute(this.controlPoints, {this.tension = 0.0}) : assert(() { return validateControlPoints( controlPoints, tension: tension, reasons: _debugAssertReasons..clear(), ); }(), 'control points $controlPoints could not be validated:\n ${_debugAssertReasons.join('\n ')}'), // Pre-compute samples so that we don't have to evaluate the spline's inverse // all the time in transformInternal. _precomputedSamples = _computeSamples(controlPoints, tension); static List<Curve2DSample> _computeSamples(List<Offset> controlPoints, double tension) { return CatmullRomSpline.precompute( // Force the first and last control points for the spline to be (0, 0) // and (1, 1), respectively. <Offset>[Offset.zero, ...controlPoints, const Offset(1.0, 1.0)], tension: tension, ).generateSamples(tolerance: 1e-12).toList(); } /// A static accumulator for assertion failures. Not used in release mode. static final List<String> _debugAssertReasons = <String>[]; // The precomputed approximation curve, so that evaluation of the curve is // efficient. // // If the curve is constructed lazily, then this will be empty, and will be filled // the first time transform is called. final List<Curve2DSample> _precomputedSamples; /// The control points used to create this curve. /// /// The `dx` value of each [Offset] in [controlPoints] represents the /// animation value at which the curve should pass through the `dy` value of /// the same control point. /// /// The [controlPoints] list must meet the following criteria: /// /// * The list must contain at least two points. /// * The X value of each point must be greater than 0.0 and less then 1.0. /// * The X values of each point must be greater than the /// previous point's X value (i.e. monotonically increasing). The Y values /// are not constrained. /// * The resulting spline must be single-valued in X. That is, for each X /// value, there must be exactly one Y value. This means that the control /// points must not generated a spline that loops or overlaps itself. /// /// The static function [validateControlPoints] can be used to check that /// these conditions are met, and will return true if they are. In debug mode, /// it will also optionally return a list of reasons in text form. In debug /// mode, the constructor will assert that these conditions are met and print /// the reasons if the assert fires. /// /// When the curve is evaluated with [transform], the values will interpolate /// smoothly from one control point to the next, passing through (0.0, 0.0), the /// given control points, and (1.0, 1.0). final List<Offset> controlPoints; /// The "tension" of the curve. /// /// The [tension] attribute controls how tightly the curve approaches the /// given [controlPoints]. It must be in the range 0.0 to 1.0, inclusive. It /// is optional, and defaults to 0.0, which provides the smoothest curve. A /// value of 1.0 is equivalent to a linear interpolation between control /// points. final double tension; /// Validates that a given set of control points for a [CatmullRomCurve] is /// well-formed and will not produce a spline that self-intersects. /// /// This method is also used in debug mode to validate a curve to make sure /// that it won't violate the contract for the [CatmullRomCurve.new] /// constructor. /// /// If in debug mode, and `reasons` is non-null, this function will fill in /// `reasons` with descriptions of the problems encountered. The `reasons` /// argument is ignored in release mode. /// /// In release mode, this function can be used to decide if a proposed /// modification to the curve will result in a valid curve. static bool validateControlPoints( List<Offset>? controlPoints, { double tension = 0.0, List<String>? reasons, }) { if (controlPoints == null) { assert(() { reasons?.add('Supplied control points cannot be null'); return true; }()); return false; } if (controlPoints.length < 2) { assert(() { reasons?.add('There must be at least two points supplied to create a valid curve.'); return true; }()); return false; } controlPoints = <Offset>[Offset.zero, ...controlPoints, const Offset(1.0, 1.0)]; final Offset startHandle = controlPoints[0] * 2.0 - controlPoints[1]; final Offset endHandle = controlPoints.last * 2.0 - controlPoints[controlPoints.length - 2]; controlPoints = <Offset>[startHandle, ...controlPoints, endHandle]; double lastX = -double.infinity; for (int i = 0; i < controlPoints.length; ++i) { if (i > 1 && i < controlPoints.length - 2 && (controlPoints[i].dx <= 0.0 || controlPoints[i].dx >= 1.0)) { assert(() { reasons?.add( 'Control points must have X values between 0.0 and 1.0, exclusive. ' 'Point $i has an x value (${controlPoints![i].dx}) which is outside the range.', ); return true; }()); return false; } if (controlPoints[i].dx <= lastX) { assert(() { reasons?.add( 'Each X coordinate must be greater than the preceding X coordinate ' '(i.e. must be monotonically increasing in X). Point $i has an x value of ' '${controlPoints![i].dx}, which is not greater than $lastX', ); return true; }()); return false; } lastX = controlPoints[i].dx; } bool success = true; // An empirical test to make sure things are single-valued in X. lastX = -double.infinity; const double tolerance = 1e-3; final CatmullRomSpline testSpline = CatmullRomSpline(controlPoints, tension: tension); final double start = testSpline.findInverse(0.0); final double end = testSpline.findInverse(1.0); final Iterable<Curve2DSample> samplePoints = testSpline.generateSamples(start: start, end: end); /// If the first and last points in the samples aren't at (0,0) or (1,1) /// respectively, then the curve is multi-valued at the ends. if (samplePoints.first.value.dy.abs() > tolerance || (1.0 - samplePoints.last.value.dy).abs() > tolerance) { bool bail = true; success = false; assert(() { reasons?.add( 'The curve has more than one Y value at X = ${samplePoints.first.value.dx}. ' 'Try moving some control points further away from this value of X, or increasing ' 'the tension.', ); // No need to keep going if we're not giving reasons. bail = reasons == null; return true; }()); if (bail) { // If we're not in debug mode, then we want to bail immediately // instead of checking everything else. return false; } } for (final Curve2DSample sample in samplePoints) { final Offset point = sample.value; final double t = sample.t; final double x = point.dx; if (t >= start && t <= end && (x < -1e-3 || x > 1.0 + 1e-3)) { bool bail = true; success = false; assert(() { reasons?.add( 'The resulting curve has an X value ($x) which is outside ' 'the range [0.0, 1.0], inclusive.', ); // No need to keep going if we're not giving reasons. bail = reasons == null; return true; }()); if (bail) { // If we're not in debug mode, then we want to bail immediately // instead of checking all the segments. return false; } } if (x < lastX) { bool bail = true; success = false; assert(() { reasons?.add( 'The curve has more than one Y value at x = $x. Try moving ' 'some control points further apart in X, or increasing the tension.', ); // No need to keep going if we're not giving reasons. bail = reasons == null; return true; }()); if (bail) { // If we're not in debug mode, then we want to bail immediately // instead of checking all the segments. return false; } } lastX = x; } return success; } @override double transformInternal(double t) { // Linearly interpolate between the two closest samples generated when the // curve was created. if (_precomputedSamples.isEmpty) { // Compute the samples now if we were constructed lazily. _precomputedSamples.addAll(_computeSamples(controlPoints, tension)); } int start = 0; int end = _precomputedSamples.length - 1; int mid; Offset value; Offset startValue = _precomputedSamples[start].value; Offset endValue = _precomputedSamples[end].value; // Use a binary search to find the index of the sample point that is just // before t. while (end - start > 1) { mid = (end + start) ~/ 2; value = _precomputedSamples[mid].value; if (t >= value.dx) { start = mid; startValue = value; } else { end = mid; endValue = value; } } // Now interpolate between the found sample and the next one. final double t2 = (t - startValue.dx) / (endValue.dx - startValue.dx); return lerpDouble(startValue.dy, endValue.dy, t2)!; } } /// A curve that is the reversed inversion of its given curve. /// /// This curve evaluates the given curve in reverse (i.e., from 1.0 to 0.0 as t /// increases from 0.0 to 1.0) and returns the inverse of the given curve's /// value (i.e., 1.0 minus the given curve's value). /// /// This is the class used to implement the [flipped] getter on curves. /// /// This is often useful with [CurvedAnimation.reverseCurve]. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_bounce_in.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_flipped.mp4} /// /// See also: /// /// * [Curve.flipped], which provides the [FlippedCurve] of a [Curve]. /// * [ReverseAnimation], which reverses an [Animation] rather than a [Curve]. /// * [CurvedAnimation], which can take a separate curve and reverse curve. class FlippedCurve extends Curve { /// Creates a flipped curve. const FlippedCurve(this.curve); /// The curve that is being flipped. final Curve curve; @override double transformInternal(double t) => 1.0 - curve.transform(1.0 - t); @override String toString() { return '${objectRuntimeType(this, 'FlippedCurve')}($curve)'; } } /// A curve where the rate of change starts out quickly and then decelerates; an /// upside-down `f(t) = t²` parabola. /// /// This is equivalent to the Android `DecelerateInterpolator` class with a unit /// factor (the default factor). /// /// See [Curves.decelerate] for an instance of this class. class _DecelerateCurve extends Curve { const _DecelerateCurve._(); @override double transformInternal(double t) { // Intended to match the behavior of: // https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/animation/DecelerateInterpolator.java // ...as of December 2016. t = 1.0 - t; return 1.0 - t * t; } } // BOUNCE CURVES double _bounce(double t) { if (t < 1.0 / 2.75) { return 7.5625 * t * t; } else if (t < 2 / 2.75) { t -= 1.5 / 2.75; return 7.5625 * t * t + 0.75; } else if (t < 2.5 / 2.75) { t -= 2.25 / 2.75; return 7.5625 * t * t + 0.9375; } t -= 2.625 / 2.75; return 7.5625 * t * t + 0.984375; } /// An oscillating curve that grows in magnitude. /// /// See [Curves.bounceIn] for an instance of this class. class _BounceInCurve extends Curve { const _BounceInCurve._(); @override double transformInternal(double t) { return 1.0 - _bounce(1.0 - t); } } /// An oscillating curve that shrink in magnitude. /// /// See [Curves.bounceOut] for an instance of this class. class _BounceOutCurve extends Curve { const _BounceOutCurve._(); @override double transformInternal(double t) { return _bounce(t); } } /// An oscillating curve that first grows and then shrink in magnitude. /// /// See [Curves.bounceInOut] for an instance of this class. class _BounceInOutCurve extends Curve { const _BounceInOutCurve._(); @override double transformInternal(double t) { if (t < 0.5) { return (1.0 - _bounce(1.0 - t * 2.0)) * 0.5; } else { return _bounce(t * 2.0 - 1.0) * 0.5 + 0.5; } } } // ELASTIC CURVES /// An oscillating curve that grows in magnitude while overshooting its bounds. /// /// An instance of this class using the default period of 0.4 is available as /// [Curves.elasticIn]. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_elastic_in.mp4} class ElasticInCurve extends Curve { /// Creates an elastic-in curve. /// /// Rather than creating a new instance, consider using [Curves.elasticIn]. const ElasticInCurve([this.period = 0.4]); /// The duration of the oscillation. final double period; @override double transformInternal(double t) { final double s = period / 4.0; t = t - 1.0; return -math.pow(2.0, 10.0 * t) * math.sin((t - s) * (math.pi * 2.0) / period); } @override String toString() { return '${objectRuntimeType(this, 'ElasticInCurve')}($period)'; } } /// An oscillating curve that shrinks in magnitude while overshooting its bounds. /// /// An instance of this class using the default period of 0.4 is available as /// [Curves.elasticOut]. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_elastic_out.mp4} class ElasticOutCurve extends Curve { /// Creates an elastic-out curve. /// /// Rather than creating a new instance, consider using [Curves.elasticOut]. const ElasticOutCurve([this.period = 0.4]); /// The duration of the oscillation. final double period; @override double transformInternal(double t) { final double s = period / 4.0; return math.pow(2.0, -10 * t) * math.sin((t - s) * (math.pi * 2.0) / period) + 1.0; } @override String toString() { return '${objectRuntimeType(this, 'ElasticOutCurve')}($period)'; } } /// An oscillating curve that grows and then shrinks in magnitude while /// overshooting its bounds. /// /// An instance of this class using the default period of 0.4 is available as /// [Curves.elasticInOut]. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_elastic_in_out.mp4} class ElasticInOutCurve extends Curve { /// Creates an elastic-in-out curve. /// /// Rather than creating a new instance, consider using [Curves.elasticInOut]. const ElasticInOutCurve([this.period = 0.4]); /// The duration of the oscillation. final double period; @override double transformInternal(double t) { final double s = period / 4.0; t = 2.0 * t - 1.0; if (t < 0.0) { return -0.5 * math.pow(2.0, 10.0 * t) * math.sin((t - s) * (math.pi * 2.0) / period); } else { return math.pow(2.0, -10.0 * t) * math.sin((t - s) * (math.pi * 2.0) / period) * 0.5 + 1.0; } } @override String toString() { return '${objectRuntimeType(this, 'ElasticInOutCurve')}($period)'; } } // PREDEFINED CURVES /// A collection of common animation curves. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_bounce_in.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_bounce_in_out.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_bounce_out.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_decelerate.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_sine.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_quad.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_cubic.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_quart.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_quint.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_expo.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_circ.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_back.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_sine.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_quad.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_cubic.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_quart.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_quint.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_expo.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_circ.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_back.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_sine.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_quad.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_cubic.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_quart.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_quint.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_expo.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_circ.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_back.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_elastic_in.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_elastic_in_out.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_elastic_out.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_fast_out_slow_in.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_slow_middle.mp4} /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_linear.mp4} /// /// See also: /// /// * [Curve], the interface implemented by the constants available from the /// [Curves] class. /// * [Easing], for the Material animation curves. abstract final class Curves { /// A linear animation curve. /// /// This is the identity map over the unit interval: its [Curve.transform] /// method returns its input unmodified. This is useful as a default curve for /// cases where a [Curve] is required but no actual curve is desired. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_linear.mp4} static const Curve linear = _Linear._(); /// A curve where the rate of change starts out quickly and then decelerates; an /// upside-down `f(t) = t²` parabola. /// /// This is equivalent to the Android `DecelerateInterpolator` class with a unit /// factor (the default factor). /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_decelerate.mp4} static const Curve decelerate = _DecelerateCurve._(); /// A curve that is very steep and linear at the beginning, but quickly flattens out /// and very slowly eases in. /// /// By default is the curve used to animate pages on iOS back to their original /// position if a swipe gesture is ended midway through a swipe. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_fast_linear_to_slow_ease_in.mp4} static const Cubic fastLinearToSlowEaseIn = Cubic(0.18, 1.0, 0.04, 1.0); /// A curve that starts slowly, speeds up very quickly, and then ends slowly. /// /// This curve is used by default to animate page transitions used by /// [CupertinoPageRoute]. /// /// It has been derived from plots of native iOS 16.3 /// animation frames on iPhone 14 Pro Max. /// Specifically, transition animation positions were measured /// every frame and plotted against time. Then, a cubic curve was /// strictly fit to the measured data points. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_fast_ease_in_to_slow_ease_out.mp4} static const ThreePointCubic fastEaseInToSlowEaseOut = ThreePointCubic( Offset(0.056, 0.024), Offset(0.108, 0.3085), Offset(0.198, 0.541), Offset(0.3655, 1.0), Offset(0.5465, 0.989), ); /// A cubic animation curve that speeds up quickly and ends slowly. /// /// This is the same as the CSS easing function `ease`. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease.mp4} static const Cubic ease = Cubic(0.25, 0.1, 0.25, 1.0); /// A cubic animation curve that starts slowly and ends quickly. /// /// This is the same as the CSS easing function `ease-in`. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in.mp4} static const Cubic easeIn = Cubic(0.42, 0.0, 1.0, 1.0); /// A cubic animation curve that starts slowly and ends linearly. /// /// The symmetric animation to [linearToEaseOut]. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_to_linear.mp4} static const Cubic easeInToLinear = Cubic(0.67, 0.03, 0.65, 0.09); /// A cubic animation curve that starts slowly and ends quickly. This is /// similar to [Curves.easeIn], but with sinusoidal easing for a slightly less /// abrupt beginning and end. Nonetheless, the result is quite gentle and is /// hard to distinguish from [Curves.linear] at a glance. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_sine.mp4} static const Cubic easeInSine = Cubic(0.47, 0.0, 0.745, 0.715); /// A cubic animation curve that starts slowly and ends quickly. Based on a /// quadratic equation where `f(t) = t²`, this is effectively the inverse of /// [Curves.decelerate]. /// /// Compared to [Curves.easeInSine], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_quad.mp4} static const Cubic easeInQuad = Cubic(0.55, 0.085, 0.68, 0.53); /// A cubic animation curve that starts slowly and ends quickly. This curve is /// based on a cubic equation where `f(t) = t³`. The result is a safe sweet /// spot when choosing a curve for widgets animating off the viewport. /// /// Compared to [Curves.easeInQuad], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_cubic.mp4} static const Cubic easeInCubic = Cubic(0.55, 0.055, 0.675, 0.19); /// A cubic animation curve that starts slowly and ends quickly. This curve is /// based on a quartic equation where `f(t) = t⁴`. /// /// Animations using this curve or steeper curves will benefit from a longer /// duration to avoid motion feeling unnatural. /// /// Compared to [Curves.easeInCubic], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_quart.mp4} static const Cubic easeInQuart = Cubic(0.895, 0.03, 0.685, 0.22); /// A cubic animation curve that starts slowly and ends quickly. This curve is /// based on a quintic equation where `f(t) = t⁵`. /// /// Compared to [Curves.easeInQuart], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_quint.mp4} static const Cubic easeInQuint = Cubic(0.755, 0.05, 0.855, 0.06); /// A cubic animation curve that starts slowly and ends quickly. This curve is /// based on an exponential equation where `f(t) = 2¹⁰⁽ᵗ⁻¹⁾`. /// /// Using this curve can give your animations extra flare, but a longer /// duration may need to be used to compensate for the steepness of the curve. /// /// Compared to [Curves.easeInQuint], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_expo.mp4} static const Cubic easeInExpo = Cubic(0.95, 0.05, 0.795, 0.035); /// A cubic animation curve that starts slowly and ends quickly. This curve is /// effectively the bottom-right quarter of a circle. /// /// Like [Curves.easeInExpo], this curve is fairly dramatic and will reduce /// the clarity of an animation if not given a longer duration. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_circ.mp4} static const Cubic easeInCirc = Cubic(0.6, 0.04, 0.98, 0.335); /// A cubic animation curve that starts slowly and ends quickly. This curve /// is similar to [Curves.elasticIn] in that it overshoots its bounds before /// reaching its end. Instead of repeated swinging motions before ascending, /// though, this curve overshoots once, then continues to ascend. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_back.mp4} static const Cubic easeInBack = Cubic(0.6, -0.28, 0.735, 0.045); /// A cubic animation curve that starts quickly and ends slowly. /// /// This is the same as the CSS easing function `ease-out`. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out.mp4} static const Cubic easeOut = Cubic(0.0, 0.0, 0.58, 1.0); /// A cubic animation curve that starts linearly and ends slowly. /// /// A symmetric animation to [easeInToLinear]. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_linear_to_ease_out.mp4} static const Cubic linearToEaseOut = Cubic(0.35, 0.91, 0.33, 0.97); /// A cubic animation curve that starts quickly and ends slowly. This is /// similar to [Curves.easeOut], but with sinusoidal easing for a slightly /// less abrupt beginning and end. Nonetheless, the result is quite gentle and /// is hard to distinguish from [Curves.linear] at a glance. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_sine.mp4} static const Cubic easeOutSine = Cubic(0.39, 0.575, 0.565, 1.0); /// A cubic animation curve that starts quickly and ends slowly. This is /// effectively the same as [Curves.decelerate], only simulated using a cubic /// bezier function. /// /// Compared to [Curves.easeOutSine], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_quad.mp4} static const Cubic easeOutQuad = Cubic(0.25, 0.46, 0.45, 0.94); /// A cubic animation curve that starts quickly and ends slowly. This curve is /// a flipped version of [Curves.easeInCubic]. /// /// The result is a safe sweet spot when choosing a curve for animating a /// widget's position entering or already inside the viewport. /// /// Compared to [Curves.easeOutQuad], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_cubic.mp4} static const Cubic easeOutCubic = Cubic(0.215, 0.61, 0.355, 1.0); /// A cubic animation curve that starts quickly and ends slowly. This curve is /// a flipped version of [Curves.easeInQuart]. /// /// Animations using this curve or steeper curves will benefit from a longer /// duration to avoid motion feeling unnatural. /// /// Compared to [Curves.easeOutCubic], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_quart.mp4} static const Cubic easeOutQuart = Cubic(0.165, 0.84, 0.44, 1.0); /// A cubic animation curve that starts quickly and ends slowly. This curve is /// a flipped version of [Curves.easeInQuint]. /// /// Compared to [Curves.easeOutQuart], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_quint.mp4} static const Cubic easeOutQuint = Cubic(0.23, 1.0, 0.32, 1.0); /// A cubic animation curve that starts quickly and ends slowly. This curve is /// a flipped version of [Curves.easeInExpo]. Using this curve can give your /// animations extra flare, but a longer duration may need to be used to /// compensate for the steepness of the curve. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_expo.mp4} static const Cubic easeOutExpo = Cubic(0.19, 1.0, 0.22, 1.0); /// A cubic animation curve that starts quickly and ends slowly. This curve is /// effectively the top-left quarter of a circle. /// /// Like [Curves.easeOutExpo], this curve is fairly dramatic and will reduce /// the clarity of an animation if not given a longer duration. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_circ.mp4} static const Cubic easeOutCirc = Cubic(0.075, 0.82, 0.165, 1.0); /// A cubic animation curve that starts quickly and ends slowly. This curve is /// similar to [Curves.elasticOut] in that it overshoots its bounds before /// reaching its end. Instead of repeated swinging motions after ascending, /// though, this curve only overshoots once. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_back.mp4} static const Cubic easeOutBack = Cubic(0.175, 0.885, 0.32, 1.275); /// A cubic animation curve that starts slowly, speeds up, and then ends /// slowly. /// /// This is the same as the CSS easing function `ease-in-out`. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out.mp4} static const Cubic easeInOut = Cubic(0.42, 0.0, 0.58, 1.0); /// A cubic animation curve that starts slowly, speeds up, and then ends /// slowly. This is similar to [Curves.easeInOut], but with sinusoidal easing /// for a slightly less abrupt beginning and end. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_sine.mp4} static const Cubic easeInOutSine = Cubic(0.445, 0.05, 0.55, 0.95); /// A cubic animation curve that starts slowly, speeds up, and then ends /// slowly. This curve can be imagined as [Curves.easeInQuad] as the first /// half, and [Curves.easeOutQuad] as the second. /// /// Compared to [Curves.easeInOutSine], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_quad.mp4} static const Cubic easeInOutQuad = Cubic(0.455, 0.03, 0.515, 0.955); /// A cubic animation curve that starts slowly, speeds up, and then ends /// slowly. This curve can be imagined as [Curves.easeInCubic] as the first /// half, and [Curves.easeOutCubic] as the second. /// /// The result is a safe sweet spot when choosing a curve for a widget whose /// initial and final positions are both within the viewport. /// /// Compared to [Curves.easeInOutQuad], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_cubic.mp4} static const Cubic easeInOutCubic = Cubic(0.645, 0.045, 0.355, 1.0); /// A cubic animation curve that starts slowly, speeds up shortly thereafter, /// and then ends slowly. This curve can be imagined as a steeper version of /// [easeInOutCubic]. /// /// The result is a more emphasized eased curve when choosing a curve for a /// widget whose initial and final positions are both within the viewport. /// /// Compared to [Curves.easeInOutCubic], this curve is slightly steeper. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_cubic_emphasized.mp4} static const ThreePointCubic easeInOutCubicEmphasized = ThreePointCubic( Offset(0.05, 0), Offset(0.133333, 0.06), Offset(0.166666, 0.4), Offset(0.208333, 0.82), Offset(0.25, 1), ); /// A cubic animation curve that starts slowly, speeds up, and then ends /// slowly. This curve can be imagined as [Curves.easeInQuart] as the first /// half, and [Curves.easeOutQuart] as the second. /// /// Animations using this curve or steeper curves will benefit from a longer /// duration to avoid motion feeling unnatural. /// /// Compared to [Curves.easeInOutCubic], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_quart.mp4} static const Cubic easeInOutQuart = Cubic(0.77, 0.0, 0.175, 1.0); /// A cubic animation curve that starts slowly, speeds up, and then ends /// slowly. This curve can be imagined as [Curves.easeInQuint] as the first /// half, and [Curves.easeOutQuint] as the second. /// /// Compared to [Curves.easeInOutQuart], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_quint.mp4} static const Cubic easeInOutQuint = Cubic(0.86, 0.0, 0.07, 1.0); /// A cubic animation curve that starts slowly, speeds up, and then ends /// slowly. /// /// Since this curve is arrived at with an exponential function, the midpoint /// is exceptionally steep. Extra consideration should be taken when designing /// an animation using this. /// /// Compared to [Curves.easeInOutQuint], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_expo.mp4} static const Cubic easeInOutExpo = Cubic(1.0, 0.0, 0.0, 1.0); /// A cubic animation curve that starts slowly, speeds up, and then ends /// slowly. This curve can be imagined as [Curves.easeInCirc] as the first /// half, and [Curves.easeOutCirc] as the second. /// /// Like [Curves.easeInOutExpo], this curve is fairly dramatic and will reduce /// the clarity of an animation if not given a longer duration. /// /// Compared to [Curves.easeInOutExpo], this curve is slightly steeper. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_circ.mp4} static const Cubic easeInOutCirc = Cubic(0.785, 0.135, 0.15, 0.86); /// A cubic animation curve that starts slowly, speeds up, and then ends /// slowly. This curve can be imagined as [Curves.easeInBack] as the first /// half, and [Curves.easeOutBack] as the second. /// /// Since two curves are used as a basis for this curve, the resulting /// animation will overshoot its bounds twice before reaching its end - first /// by exceeding its lower bound, then exceeding its upper bound and finally /// descending to its final position. /// /// Derived from Robert Penner’s easing functions. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_in_out_back.mp4} static const Cubic easeInOutBack = Cubic(0.68, -0.55, 0.265, 1.55); /// A curve that starts quickly and eases into its final position. /// /// Over the course of the animation, the object spends more time near its /// final destination. As a result, the user isn’t left waiting for the /// animation to finish, and the negative effects of motion are minimized. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_fast_out_slow_in.mp4} /// /// See also: /// /// * [Easing.legacy], the name for this curve in the Material specification. static const Cubic fastOutSlowIn = Cubic(0.4, 0.0, 0.2, 1.0); /// A cubic animation curve that starts quickly, slows down, and then ends /// quickly. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_slow_middle.mp4} static const Cubic slowMiddle = Cubic(0.15, 0.85, 0.85, 0.15); /// An oscillating curve that grows in magnitude. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_bounce_in.mp4} static const Curve bounceIn = _BounceInCurve._(); /// An oscillating curve that first grows and then shrink in magnitude. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_bounce_out.mp4} static const Curve bounceOut = _BounceOutCurve._(); /// An oscillating curve that first grows and then shrink in magnitude. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_bounce_in_out.mp4} static const Curve bounceInOut = _BounceInOutCurve._(); /// An oscillating curve that grows in magnitude while overshooting its bounds. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_elastic_in.mp4} static const ElasticInCurve elasticIn = ElasticInCurve(); /// An oscillating curve that shrinks in magnitude while overshooting its bounds. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_elastic_out.mp4} static const ElasticOutCurve elasticOut = ElasticOutCurve(); /// An oscillating curve that grows and then shrinks in magnitude while overshooting its bounds. /// /// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_elastic_in_out.mp4} static const ElasticInOutCurve elasticInOut = ElasticInOutCurve(); }
flutter/packages/flutter/lib/src/animation/curves.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/animation/curves.dart", "repo_id": "flutter", "token_count": 27310 }
661
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart' show ValueListenable, clampDouble; import 'package:flutter/widgets.dart'; import 'desktop_text_selection_toolbar.dart'; import 'desktop_text_selection_toolbar_button.dart'; import 'localizations.dart'; /// MacOS Cupertino styled text selection handle controls. /// /// Specifically does not manage the toolbar, which is left to /// [EditableText.contextMenuBuilder]. class _CupertinoDesktopTextSelectionHandleControls extends CupertinoDesktopTextSelectionControls with TextSelectionHandleControls { } /// Desktop Cupertino styled text selection controls. /// /// The [cupertinoDesktopTextSelectionControls] global variable has a /// suitable instance of this class. class CupertinoDesktopTextSelectionControls extends TextSelectionControls { /// Desktop has no text selection handles. @override Size getHandleSize(double textLineHeight) { return Size.zero; } /// Builder for the MacOS-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 _CupertinoDesktopTextSelectionControlsToolbar( 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 void handleSelectAll(TextSelectionDelegate delegate) { super.handleSelectAll(delegate); delegate.hideToolbar(); } } // TODO(justinmc): Deprecate this after TextSelectionControls.buildToolbar is // deleted, when users should migrate back to // cupertinoDesktopTextSelectionControls. // See https://github.com/flutter/flutter/pull/124262 /// Text selection handle controls that follow MacOS design conventions. final TextSelectionControls cupertinoDesktopTextSelectionHandleControls = _CupertinoDesktopTextSelectionHandleControls(); /// Text selection controls that follows MacOS design conventions. final TextSelectionControls cupertinoDesktopTextSelectionControls = CupertinoDesktopTextSelectionControls(); // Generates the child that's passed into CupertinoDesktopTextSelectionToolbar. class _CupertinoDesktopTextSelectionControlsToolbar extends StatefulWidget { const _CupertinoDesktopTextSelectionControlsToolbar({ 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 _CupertinoDesktopTextSelectionControlsToolbarState createState() => _CupertinoDesktopTextSelectionControlsToolbarState(); } class _CupertinoDesktopTextSelectionControlsToolbarState extends State<_CupertinoDesktopTextSelectionControlsToolbar> { 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(_CupertinoDesktopTextSelectionControlsToolbar 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) { // 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(); } assert(debugCheckHasMediaQuery(context)); 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 List<Widget> items = <Widget>[]; final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); final Widget onePhysicalPixelVerticalDivider = SizedBox(width: 1.0 / MediaQuery.devicePixelRatioOf(context)); void addToolbarButton( String text, VoidCallback onPressed, ) { if (items.isNotEmpty) { items.add(onePhysicalPixelVerticalDivider); } items.add(CupertinoDesktopTextSelectionToolbarButton.text( 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 CupertinoDesktopTextSelectionToolbar( anchor: widget.lastSecondaryTapDownPosition ?? midpointAnchor, children: items, ); } }
flutter/packages/flutter/lib/src/cupertino/desktop_text_selection.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/cupertino/desktop_text_selection.dart", "repo_id": "flutter", "token_count": 2440 }
662
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; import 'toggleable.dart'; // Examples can assume: // late BuildContext context; // enum SingingCharacter { lafayette } // late SingingCharacter? _character; // late StateSetter setState; const Size _size = Size(18.0, 18.0); const double _kOuterRadius = 7.0; const double _kInnerRadius = 2.975; // The relative values needed to transform a color to its equivalent focus // outline color. const double _kCupertinoFocusColorOpacity = 0.80; const double _kCupertinoFocusColorBrightness = 0.69; const double _kCupertinoFocusColorSaturation = 0.835; /// A macOS-style radio button. /// /// Used to select between a number of mutually exclusive values. When one radio /// button in a group is selected, the other radio buttons in the group are /// deselected. The values are of type `T`, the type parameter of the /// [CupertinoRadio] class. Enums are commonly used for this purpose. /// /// The radio button itself does not maintain any state. Instead, selecting the /// radio invokes the [onChanged] callback, passing [value] as a parameter. If /// [groupValue] and [value] match, this radio will be selected. Most widgets /// will respond to [onChanged] by calling [State.setState] to update the /// radio button's [groupValue]. /// /// {@tool dartpad} /// Here is an example of CupertinoRadio widgets wrapped in CupertinoListTiles. /// /// The currently selected character is passed into `groupValue`, which is /// maintained by the example's `State`. In this case, the first [CupertinoRadio] /// will start off selected because `_character` is initialized to /// `SingingCharacter.lafayette`. /// /// If the second radio button is pressed, the example's state is updated /// with `setState`, updating `_character` to `SingingCharacter.jefferson`. /// This causes the buttons to rebuild with the updated `groupValue`, and /// therefore the selection of the second button. /// /// ** See code in examples/api/lib/cupertino/radio/cupertino_radio.0.dart ** /// {@end-tool} /// /// See also: /// /// * [CupertinoSlider], for selecting a value in a range. /// * [CupertinoCheckbox] and [CupertinoSwitch], for toggling a particular value on or off. /// * [Radio], the Material Design equivalent. /// * <https://developer.apple.com/design/human-interface-guidelines/components/selection-and-input/toggles/> class CupertinoRadio<T> extends StatefulWidget { /// Creates a macOS-styled radio button. /// /// The following arguments are required: /// /// * [value] and [groupValue] together determine whether the radio button is /// selected. /// * [onChanged] is called when the user selects this radio button. const CupertinoRadio({ super.key, required this.value, required this.groupValue, required this.onChanged, this.toggleable = false, this.activeColor, this.inactiveColor, this.fillColor, this.focusColor, this.focusNode, this.autofocus = false, this.useCheckmarkStyle = false, }); /// The value represented by this radio button. /// /// If this equals the [groupValue], then this radio button will appear /// selected. final T value; /// The currently selected value for a group of radio buttons. /// /// This radio button is considered selected if its [value] matches the /// [groupValue]. final T? groupValue; /// Called when the user selects this [CupertinoRadio] button. /// /// The radio button passes [value] as a parameter to this callback. It does /// not actually change state until the parent widget rebuilds the radio /// button with a new [groupValue]. /// /// If null, the radio button will be displayed as disabled. /// /// The provided callback will not be invoked if this radio button is already /// selected. /// /// The callback provided to [onChanged] should update the state of the parent /// [StatefulWidget] using the [State.setState] method, so that the parent /// gets rebuilt; for example: /// /// ```dart /// CupertinoRadio<SingingCharacter>( /// value: SingingCharacter.lafayette, /// groupValue: _character, /// onChanged: (SingingCharacter? newValue) { /// setState(() { /// _character = newValue; /// }); /// }, /// ) /// ``` final ValueChanged<T?>? onChanged; /// Set to true if this radio button is allowed to be returned to an /// indeterminate state by selecting it again when selected. /// /// To indicate returning to an indeterminate state, [onChanged] will be /// called with null. /// /// If true, [onChanged] can be called with [value] when selected while /// [groupValue] != [value], or with null when selected again while /// [groupValue] == [value]. /// /// If false, [onChanged] will be called with [value] when it is selected /// while [groupValue] != [value], and only by selecting another radio button /// in the group (i.e. changing the value of [groupValue]) can this radio /// button be unselected. /// /// The default is false. /// /// {@tool dartpad} /// This example shows how to enable deselecting a radio button by setting the /// [toggleable] attribute. /// /// ** See code in examples/api/lib/cupertino/radio/cupertino_radio.toggleable.0.dart ** /// {@end-tool} final bool toggleable; /// Controls whether the radio displays in a checkbox style or the default iOS /// radio style. /// /// Defaults to false. final bool useCheckmarkStyle; /// The color to use when this radio button is selected. /// /// Defaults to [CupertinoColors.activeBlue]. final Color? activeColor; /// The color to use when this radio button is not selected. /// /// Defaults to [CupertinoColors.white]. final Color? inactiveColor; /// The color that fills the inner circle of the radio button when selected. /// /// Defaults to [CupertinoColors.white]. final Color? fillColor; /// The color for the radio's border when it has the input focus. /// /// If null, then a paler form of the [activeColor] will be used. final Color? focusColor; /// {@macro flutter.widgets.Focus.focusNode} final FocusNode? focusNode; /// {@macro flutter.widgets.Focus.autofocus} final bool autofocus; bool get _selected => value == groupValue; @override State<CupertinoRadio<T>> createState() => _CupertinoRadioState<T>(); } class _CupertinoRadioState<T> extends State<CupertinoRadio<T>> with TickerProviderStateMixin, ToggleableStateMixin { final _RadioPainter _painter = _RadioPainter(); bool focused = false; void _handleChanged(bool? selected) { if (selected == null) { widget.onChanged!(null); return; } if (selected) { widget.onChanged!(widget.value); } } @override void dispose() { _painter.dispose(); super.dispose(); } @override ValueChanged<bool?>? get onChanged => widget.onChanged != null ? _handleChanged : null; @override bool get tristate => widget.toggleable; @override bool? get value => widget._selected; void onFocusChange(bool value) { if (focused != value) { focused = value; } } @override Widget build(BuildContext context) { final Color effectiveActiveColor = widget.activeColor ?? CupertinoColors.activeBlue; final Color effectiveInactiveColor = widget.inactiveColor ?? CupertinoColors.white; final Color effectiveFocusOverlayColor = widget.focusColor ?? HSLColor .fromColor(effectiveActiveColor.withOpacity(_kCupertinoFocusColorOpacity)) .withLightness(_kCupertinoFocusColorBrightness) .withSaturation(_kCupertinoFocusColorSaturation) .toColor(); final Color effectiveActivePressedOverlayColor = HSLColor.fromColor(effectiveActiveColor).withLightness(0.45).toColor(); final Color effectiveFillColor = widget.fillColor ?? CupertinoColors.white; final bool? accessibilitySelected; // Apple devices also use `selected` to annotate radio button's semantics // state. switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: accessibilitySelected = null; case TargetPlatform.iOS: case TargetPlatform.macOS: accessibilitySelected = widget._selected; } return Semantics( inMutuallyExclusiveGroup: true, checked: widget._selected, selected: accessibilitySelected, child: buildToggleable( focusNode: widget.focusNode, autofocus: widget.autofocus, onFocusChange: onFocusChange, size: _size, painter: _painter ..focusColor = effectiveFocusOverlayColor ..downPosition = downPosition ..isFocused = focused ..activeColor = downPosition != null ? effectiveActivePressedOverlayColor : effectiveActiveColor ..inactiveColor = effectiveInactiveColor ..fillColor = effectiveFillColor ..value = value ..checkmarkStyle = widget.useCheckmarkStyle, ), ); } } class _RadioPainter extends ToggleablePainter { bool? get value => _value; bool? _value; set value(bool? value) { if (_value == value) { return; } _value = value; notifyListeners(); } Color get fillColor => _fillColor!; Color? _fillColor; set fillColor(Color value) { if (value == _fillColor) { return; } _fillColor = value; notifyListeners(); } bool get checkmarkStyle => _checkmarkStyle; bool _checkmarkStyle = false; set checkmarkStyle(bool value) { if (value == _checkmarkStyle) { return; } _checkmarkStyle = value; notifyListeners(); } @override void paint(Canvas canvas, Size size) { final Offset center = (Offset.zero & size).center; final Paint paint = Paint() ..color = inactiveColor ..style = PaintingStyle.fill ..strokeWidth = 0.1; if (checkmarkStyle) { if (value ?? false) { final Path path = Path(); final Paint checkPaint = Paint() ..color = activeColor ..style = PaintingStyle.stroke ..strokeWidth = 2 ..strokeCap = StrokeCap.round; final double width = _size.width; final Offset origin = Offset(center.dx - (width/2), center.dy - (width/2)); final Offset start = Offset(width * 0.25, width * 0.52); final Offset mid = Offset(width * 0.46, width * 0.75); final Offset end = Offset(width * 0.85, width * 0.29); path.moveTo(origin.dx + start.dx, origin.dy + start.dy); path.lineTo(origin.dx + mid.dx, origin.dy + mid.dy); canvas.drawPath(path, checkPaint); path.moveTo(origin.dx + mid.dx, origin.dy + mid.dy); path.lineTo(origin.dx + end.dx, origin.dy + end.dy); canvas.drawPath(path, checkPaint); } } else { // Outer border canvas.drawCircle(center, _kOuterRadius, paint); paint.style = PaintingStyle.stroke; paint.color = CupertinoColors.inactiveGray; canvas.drawCircle(center, _kOuterRadius, paint); if (value ?? false) { paint.style = PaintingStyle.fill; paint.color = activeColor; canvas.drawCircle(center, _kOuterRadius, paint); paint.color = fillColor; canvas.drawCircle(center, _kInnerRadius, paint); } } if (isFocused) { paint.style = PaintingStyle.stroke; paint.color = focusColor; paint.strokeWidth = 3.0; canvas.drawCircle(center, _kOuterRadius + 1.5, paint); } } }
flutter/packages/flutter/lib/src/cupertino/radio.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/cupertino/radio.dart", "repo_id": "flutter", "token_count": 3985 }
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/widgets.dart'; import 'button.dart'; import 'colors.dart'; import 'debug.dart'; import 'localizations.dart'; const TextStyle _kToolbarButtonFontStyle = TextStyle( inherit: false, fontSize: 15.0, letterSpacing: -0.15, fontWeight: FontWeight.w400, ); const CupertinoDynamicColor _kToolbarTextColor = CupertinoDynamicColor.withBrightness( color: CupertinoColors.black, darkColor: CupertinoColors.white, ); const CupertinoDynamicColor _kToolbarPressedColor = CupertinoDynamicColor.withBrightness( color: Color(0x10000000), darkColor: Color(0x10FFFFFF), ); // Value measured from screenshot of iOS 16.0.2 const EdgeInsets _kToolbarButtonPadding = EdgeInsets.symmetric(vertical: 18.0, horizontal: 16.0); /// A button in the style of the iOS text selection toolbar buttons. class CupertinoTextSelectionToolbarButton extends StatefulWidget { /// Create an instance of [CupertinoTextSelectionToolbarButton]. const CupertinoTextSelectionToolbarButton({ super.key, this.onPressed, required Widget this.child, }) : text = null, buttonItem = null; /// Create an instance of [CupertinoTextSelectionToolbarButton] whose child is /// a [Text] widget styled like the default iOS text selection toolbar button. const CupertinoTextSelectionToolbarButton.text({ super.key, this.onPressed, required this.text, }) : buttonItem = null, child = null; /// Create an instance of [CupertinoTextSelectionToolbarButton] from the given /// [ContextMenuButtonItem]. CupertinoTextSelectionToolbarButton.buttonItem({ super.key, required ContextMenuButtonItem this.buttonItem, }) : child = null, text = null, onPressed = buttonItem.onPressed; /// {@template flutter.cupertino.CupertinoTextSelectionToolbarButton.child} /// The child of this button. /// /// Usually a [Text] or an [Icon]. /// {@endtemplate} final Widget? child; /// {@template flutter.cupertino.CupertinoTextSelectionToolbarButton.onPressed} /// Called when this button is pressed. /// {@endtemplate} final VoidCallback? onPressed; /// {@template flutter.cupertino.CupertinoTextSelectionToolbarButton.onPressed} /// The buttonItem used to generate the button when using /// [CupertinoTextSelectionToolbarButton.buttonItem]. /// {@endtemplate} final ContextMenuButtonItem? buttonItem; /// {@template flutter.cupertino.CupertinoTextSelectionToolbarButton.text} /// The text used in the button's label when using /// [CupertinoTextSelectionToolbarButton.text]. /// {@endtemplate} final String? text; /// Returns the default button label String for the button of the given /// [ContextMenuButtonItem]'s [ContextMenuButtonType]. static String getButtonLabel(BuildContext context, ContextMenuButtonItem buttonItem) { if (buttonItem.label != null) { return buttonItem.label!; } assert(debugCheckHasCupertinoLocalizations(context)); final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); return switch (buttonItem.type) { ContextMenuButtonType.cut => localizations.cutButtonLabel, ContextMenuButtonType.copy => localizations.copyButtonLabel, ContextMenuButtonType.paste => localizations.pasteButtonLabel, ContextMenuButtonType.selectAll => localizations.selectAllButtonLabel, ContextMenuButtonType.lookUp => localizations.lookUpButtonLabel, ContextMenuButtonType.searchWeb => localizations.searchWebButtonLabel, ContextMenuButtonType.share => localizations.shareButtonLabel, ContextMenuButtonType.liveTextInput || ContextMenuButtonType.delete || ContextMenuButtonType.custom => '', }; } @override State<StatefulWidget> createState() => _CupertinoTextSelectionToolbarButtonState(); } class _CupertinoTextSelectionToolbarButtonState extends State<CupertinoTextSelectionToolbarButton> { bool isPressed = false; void _onTapDown(TapDownDetails details) { setState(() => isPressed = true); } void _onTapUp(TapUpDetails details) { setState(() => isPressed = false); widget.onPressed?.call(); } void _onTapCancel() { setState(() => isPressed = false); } @override Widget build(BuildContext context) { final Widget content = _getContentWidget(context); final Widget child = CupertinoButton( color: isPressed ? _kToolbarPressedColor.resolveFrom(context) : const Color(0x00000000), borderRadius: null, disabledColor: const Color(0x00000000), // This CupertinoButton does not actually handle the onPressed callback, // this is only here to correctly enable/disable the button (see // GestureDetector comment below). onPressed: widget.onPressed, padding: _kToolbarButtonPadding, // There's no foreground fade on iOS toolbar anymore, just the background // is darkened. pressedOpacity: 1.0, child: content, ); if (widget.onPressed != null) { // As it's needed to change the CupertinoButton's backgroundColor when // pressed, not its opacity, this GestureDetector handles both the // onPressed callback and the backgroundColor change. return GestureDetector( onTapDown: _onTapDown, onTapUp: _onTapUp, onTapCancel: _onTapCancel, child: child, ); } else { return child; } } Widget _getContentWidget(BuildContext context) { if (widget.child != null) { return widget.child!; } final Widget textWidget = Text( widget.text ?? CupertinoTextSelectionToolbarButton.getButtonLabel(context, widget.buttonItem!), overflow: TextOverflow.ellipsis, style: _kToolbarButtonFontStyle.copyWith( color: widget.onPressed != null ? _kToolbarTextColor.resolveFrom(context) : CupertinoColors.inactiveGray, ), ); if (widget.buttonItem == null) { return textWidget; } switch (widget.buttonItem!.type) { case ContextMenuButtonType.cut: case ContextMenuButtonType.copy: case ContextMenuButtonType.paste: case ContextMenuButtonType.selectAll: case ContextMenuButtonType.delete: case ContextMenuButtonType.lookUp: case ContextMenuButtonType.searchWeb: case ContextMenuButtonType.share: case ContextMenuButtonType.custom: return textWidget; case ContextMenuButtonType.liveTextInput: return SizedBox( width: 13.0, height: 13.0, child: CustomPaint( painter: _LiveTextIconPainter(color: _kToolbarTextColor.resolveFrom(context)), ), ); } } } class _LiveTextIconPainter extends CustomPainter { _LiveTextIconPainter({required this.color}); final Color color; final Paint _painter = Paint() ..strokeCap = StrokeCap.round ..strokeJoin = StrokeJoin.round ..strokeWidth = 1.0 ..style = PaintingStyle.stroke; @override void paint(Canvas canvas, Size size) { _painter.color = color; canvas.save(); canvas.translate(size.width / 2.0, size.height / 2.0); final Offset origin = Offset(-size.width / 2.0, -size.height / 2.0); // Path for the one corner. final Path path = Path() ..moveTo(origin.dx, origin.dy + 3.5) ..lineTo(origin.dx, origin.dy + 1.0) ..arcToPoint(Offset(origin.dx + 1.0, origin.dy), radius: const Radius.circular(1)) ..lineTo(origin.dx + 3.5, origin.dy); // Rotate to draw corner four times. final Matrix4 rotationMatrix = Matrix4.identity()..rotateZ(pi / 2.0); for (int i = 0; i < 4; i += 1) { canvas.drawPath(path, _painter); canvas.transform(rotationMatrix.storage); } // Draw three lines. canvas.drawLine(const Offset(-3.0, -3.0), const Offset(3.0, -3.0), _painter); canvas.drawLine(const Offset(-3.0, 0.0), const Offset(3.0, 0.0), _painter); canvas.drawLine(const Offset(-3.0, 3.0), const Offset(1.0, 3.0), _painter); canvas.restore(); } @override bool shouldRepaint(covariant _LiveTextIconPainter oldDelegate) { return oldDelegate.color != color; } }
flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar_button.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar_button.dart", "repo_id": "flutter", "token_count": 2984 }
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 'dart:js_interop'; /// Returns the current timestamp in microseconds from a monotonically /// increasing clock. /// /// This is the web implementation, which uses `window.performance.now` as the /// source of the timestamp. /// /// See: /// * https://developer.mozilla.org/en-US/docs/Web/API/Performance/now double get performanceTimestamp => 1000 * _performance.now(); @JS() @staticInterop class _DomPerformance {} @JS('performance') external _DomPerformance get _performance; extension _DomPerformanceExtension on _DomPerformance { @JS() external double now(); }
flutter/packages/flutter/lib/src/foundation/_timeline_web.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/foundation/_timeline_web.dart", "repo_id": "flutter", "token_count": 208 }
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 'assertions.dart'; import 'constants.dart'; import 'diagnostics.dart'; const bool _kMemoryAllocations = bool.fromEnvironment('flutter.memory_allocations'); /// If true, Flutter objects dispatch the memory allocation events. /// /// By default, the constant is true for debug mode and false /// for profile and release modes. /// To enable the dispatching for release mode, pass the compilation flag /// `--dart-define=flutter.memory_allocations=true`. const bool kFlutterMemoryAllocationsEnabled = _kMemoryAllocations || kDebugMode; const String _dartUiLibrary = 'dart:ui'; class _FieldNames { static const String eventType = 'eventType'; static const String libraryName = 'libraryName'; static const String className = 'className'; } /// A lifecycle event of an object. abstract class ObjectEvent{ /// Creates an instance of [ObjectEvent]. ObjectEvent({ required this.object, }); /// Reference to the object. /// /// The reference should not be stored in any /// long living place as it will prevent garbage collection. final Object object; /// The representation of the event in a form, acceptable by a /// pure dart library, that cannot depend on Flutter. /// /// The method enables code like: /// ```dart /// void myDartMethod(Map<Object, Map<String, Object>> event) {} /// FlutterMemoryAllocations.instance /// .addListener((ObjectEvent event) => myDartMethod(event.toMap())); /// ``` Map<Object, Map<String, Object>> toMap(); } /// A listener of [ObjectEvent]. typedef ObjectEventListener = void Function(ObjectEvent event); /// An event that describes creation of an object. class ObjectCreated extends ObjectEvent { /// Creates an instance of [ObjectCreated]. ObjectCreated({ required this.library, required this.className, required super.object, }); /// Name of the instrumented library. /// /// The format of this parameter should be a library Uri. /// For example: `'package:flutter/rendering.dart'`. final String library; /// Name of the instrumented class. final String className; @override Map<Object, Map<String, Object>> toMap() { return <Object, Map<String, Object>>{object: <String, Object>{ _FieldNames.libraryName: library, _FieldNames.className: className, _FieldNames.eventType: 'created', }}; } } /// An event that describes disposal of an object. class ObjectDisposed extends ObjectEvent { /// Creates an instance of [ObjectDisposed]. ObjectDisposed({ required super.object, }); @override Map<Object, Map<String, Object>> toMap() { return <Object, Map<String, Object>>{object: <String, Object>{ _FieldNames.eventType: 'disposed', }}; } } /// An interface for listening to object lifecycle events. @Deprecated( 'Use `FlutterMemoryAllocations` instead. ' 'The class `MemoryAllocations` will be introduced in a pure Dart library. ' 'This feature was deprecated after v3.18.0-18.0.pre.' ) typedef MemoryAllocations = FlutterMemoryAllocations; /// An interface for listening to object lifecycle events. /// /// If [kFlutterMemoryAllocationsEnabled] is true, /// [FlutterMemoryAllocations] listens to creation and disposal events /// for disposable objects in Flutter Framework. /// To dispatch other events objects, invoke /// [FlutterMemoryAllocations.dispatchObjectEvent]. /// /// Use this class with condition `kFlutterMemoryAllocationsEnabled`, /// to make sure not to increase size of the application by the code /// of the class, if memory allocations are disabled. /// /// The class is optimized for massive event flow and small number of /// added or removed listeners. class FlutterMemoryAllocations { FlutterMemoryAllocations._(); /// The shared instance of [FlutterMemoryAllocations]. /// /// Only call this when [kFlutterMemoryAllocationsEnabled] is true. static final FlutterMemoryAllocations instance = FlutterMemoryAllocations._(); /// List of listeners. /// /// The elements are nullable, because the listeners should be removable /// while iterating through the list. List<ObjectEventListener?>? _listeners; /// Register a listener that is called every time an object event is /// dispatched. /// /// Listeners can be removed with [removeListener]. /// /// Only call this when [kFlutterMemoryAllocationsEnabled] is true. void addListener(ObjectEventListener listener){ if (!kFlutterMemoryAllocationsEnabled) { return; } if (_listeners == null) { _listeners = <ObjectEventListener?>[]; _subscribeToSdkObjects(); } _listeners!.add(listener); } /// Number of active notification loops. /// /// When equal to zero, we can delete listeners from the list, /// otherwise should null them. int _activeDispatchLoops = 0; /// If true, listeners were nulled by [removeListener]. bool _listenersContainNulls = false; /// Stop calling the given listener every time an object event is /// dispatched. /// /// Listeners can be added with [addListener]. /// /// Only call this when [kFlutterMemoryAllocationsEnabled] is true. void removeListener(ObjectEventListener listener){ if (!kFlutterMemoryAllocationsEnabled) { return; } final List<ObjectEventListener?>? listeners = _listeners; if (listeners == null) { return; } if (_activeDispatchLoops > 0) { // If there are active dispatch loops, listeners.remove // should not be invoked, as it will // break the dispatch loops correctness. for (int i = 0; i < listeners.length; i++) { if (listeners[i] == listener) { listeners[i] = null; _listenersContainNulls = true; } } } else { listeners.removeWhere((ObjectEventListener? l) => l == listener); _checkListenersForEmptiness(); } } void _tryDefragmentListeners() { if (_activeDispatchLoops > 0 || !_listenersContainNulls) { return; } _listeners?.removeWhere((ObjectEventListener? e) => e == null); _listenersContainNulls = false; _checkListenersForEmptiness(); } void _checkListenersForEmptiness() { if (_listeners?.isEmpty ?? false) { _listeners = null; _unSubscribeFromSdkObjects(); } } /// Return true if there are listeners. /// /// If there is no listeners, the app can save on creating the event object. /// /// Only call this when [kFlutterMemoryAllocationsEnabled] is true. bool get hasListeners { if (!kFlutterMemoryAllocationsEnabled) { return false; } if (_listenersContainNulls) { return _listeners?.firstWhere((ObjectEventListener? l) => l != null) != null; } return _listeners?.isNotEmpty ?? false; } /// Dispatch a new object event to listeners. /// /// Exceptions thrown by listeners will be caught and reported using /// [FlutterError.reportError]. /// /// Listeners added during an event dispatching, will start being invoked /// for next events, but will be skipped for this event. /// /// Listeners, removed during an event dispatching, will not be invoked /// after the removal. /// /// Only call this when [kFlutterMemoryAllocationsEnabled] is true. void dispatchObjectEvent(ObjectEvent event) { if (!kFlutterMemoryAllocationsEnabled) { return; } final List<ObjectEventListener?>? listeners = _listeners; if (listeners == null || listeners.isEmpty) { return; } _activeDispatchLoops++; final int end = listeners.length; for (int i = 0; i < end; i++) { try { listeners[i]?.call(event); } catch (exception, stack) { final String type = event.object.runtimeType.toString(); FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'foundation library', context: ErrorDescription('MemoryAllocations while ' 'dispatching notifications for $type'), informationCollector: () => <DiagnosticsNode>[ DiagnosticsProperty<Object>( 'The $type sending notification was', event.object, style: DiagnosticsTreeStyle.errorProperty, ), ], )); } } _activeDispatchLoops--; _tryDefragmentListeners(); } /// Create [ObjectCreated] and invoke [dispatchObjectEvent] if there are listeners. /// /// This method is more efficient than [dispatchObjectEvent] if the event object is not created yet. void dispatchObjectCreated({ required String library, required String className, required Object object, }) { if (!hasListeners) { return; } dispatchObjectEvent(ObjectCreated( library: library, className: className, object: object, )); } /// Create [ObjectDisposed] and invoke [dispatchObjectEvent] if there are listeners. /// /// This method is more efficient than [dispatchObjectEvent] if the event object is not created yet. void dispatchObjectDisposed({required Object object}) { if (!hasListeners) { return; } dispatchObjectEvent(ObjectDisposed(object: object)); } void _subscribeToSdkObjects() { assert(ui.Image.onCreate == null); assert(ui.Image.onDispose == null); assert(ui.Picture.onCreate == null); assert(ui.Picture.onDispose == null); ui.Image.onCreate = _imageOnCreate; ui.Image.onDispose = _imageOnDispose; ui.Picture.onCreate = _pictureOnCreate; ui.Picture.onDispose = _pictureOnDispose; } void _unSubscribeFromSdkObjects() { assert(ui.Image.onCreate == _imageOnCreate); assert(ui.Image.onDispose == _imageOnDispose); assert(ui.Picture.onCreate == _pictureOnCreate); assert(ui.Picture.onDispose == _pictureOnDispose); ui.Image.onCreate = null; ui.Image.onDispose = null; ui.Picture.onCreate = null; ui.Picture.onDispose = null; } void _imageOnCreate(ui.Image image) { dispatchObjectEvent(ObjectCreated( library: _dartUiLibrary, className: '${ui.Image}', object: image, )); } void _pictureOnCreate(ui.Picture picture) { dispatchObjectEvent(ObjectCreated( library: _dartUiLibrary, className: '${ui.Picture}', object: picture, )); } void _imageOnDispose(ui.Image image) { dispatchObjectEvent(ObjectDisposed( object: image, )); } void _pictureOnDispose(ui.Picture picture) { dispatchObjectEvent(ObjectDisposed( object: picture, )); } }
flutter/packages/flutter/lib/src/foundation/memory_allocations.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/foundation/memory_allocations.dart", "repo_id": "flutter", "token_count": 3521 }
666
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' as ui show PointerChange, PointerData, PointerSignalKind; import 'events.dart'; export 'dart:ui' show PointerData; export 'events.dart' show PointerEvent; // Add `kPrimaryButton` to [buttons] when a pointer of certain devices is down. // // TODO(tongmu): This patch is supposed to be done by embedders. Patching it // in framework is a workaround before [PointerEventConverter] is moved to embedders. // https://github.com/flutter/flutter/issues/30454 int _synthesiseDownButtons(int buttons, PointerDeviceKind kind) { switch (kind) { case PointerDeviceKind.mouse: case PointerDeviceKind.trackpad: return buttons; case PointerDeviceKind.touch: case PointerDeviceKind.stylus: case PointerDeviceKind.invertedStylus: return buttons == 0 ? kPrimaryButton : buttons; case PointerDeviceKind.unknown: // We have no information about the device but we know we never want // buttons to be 0 when the pointer is down. return buttons == 0 ? kPrimaryButton : buttons; } } /// Signature for a callback that returns the device pixel ratio of a /// [FlutterView] identified by the provided `viewId`. /// /// Returns null if no view with the provided ID exists. /// /// Used by [PointerEventConverter.expand]. /// /// See also: /// /// * [FlutterView.devicePixelRatio] for an explanation of device pixel ratio. typedef DevicePixelRatioGetter = double? Function(int viewId); /// Converts from engine pointer data to framework pointer events. /// /// This takes [PointerDataPacket] objects, as received from the engine via /// [dart:ui.PlatformDispatcher.onPointerDataPacket], and converts them to /// [PointerEvent] objects. abstract final class PointerEventConverter { /// Expand the given packet of pointer data into a sequence of framework /// pointer events. /// /// The `devicePixelRatioForView` is used to obtain the device pixel ratio for /// the view a particular event occurred in to convert its data from physical /// coordinates to logical pixels. See the discussion at [PointerEvent] for /// more details on the [PointerEvent] coordinate space. static Iterable<PointerEvent> expand(Iterable<ui.PointerData> data, DevicePixelRatioGetter devicePixelRatioForView) { return data .where((ui.PointerData datum) => datum.signalKind != ui.PointerSignalKind.unknown) .map<PointerEvent?>((ui.PointerData datum) { final double? devicePixelRatio = devicePixelRatioForView(datum.viewId); if (devicePixelRatio == null) { // View doesn't exist anymore. return null; } final Offset position = Offset(datum.physicalX, datum.physicalY) / devicePixelRatio; final Offset delta = Offset(datum.physicalDeltaX, datum.physicalDeltaY) / devicePixelRatio; final double radiusMinor = _toLogicalPixels(datum.radiusMinor, devicePixelRatio); final double radiusMajor = _toLogicalPixels(datum.radiusMajor, devicePixelRatio); final double radiusMin = _toLogicalPixels(datum.radiusMin, devicePixelRatio); final double radiusMax = _toLogicalPixels(datum.radiusMax, devicePixelRatio); final Duration timeStamp = datum.timeStamp; final PointerDeviceKind kind = datum.kind; switch (datum.signalKind ?? ui.PointerSignalKind.none) { case ui.PointerSignalKind.none: switch (datum.change) { case ui.PointerChange.add: return PointerAddedEvent( viewId: datum.viewId, timeStamp: timeStamp, kind: kind, device: datum.device, position: position, obscured: datum.obscured, pressureMin: datum.pressureMin, pressureMax: datum.pressureMax, distance: datum.distance, distanceMax: datum.distanceMax, radiusMin: radiusMin, radiusMax: radiusMax, orientation: datum.orientation, tilt: datum.tilt, embedderId: datum.embedderId, ); case ui.PointerChange.hover: return PointerHoverEvent( viewId: datum.viewId, timeStamp: timeStamp, kind: kind, device: datum.device, position: position, delta: delta, buttons: datum.buttons, obscured: datum.obscured, pressureMin: datum.pressureMin, pressureMax: datum.pressureMax, distance: datum.distance, distanceMax: datum.distanceMax, size: datum.size, radiusMajor: radiusMajor, radiusMinor: radiusMinor, radiusMin: radiusMin, radiusMax: radiusMax, orientation: datum.orientation, tilt: datum.tilt, synthesized: datum.synthesized, embedderId: datum.embedderId, ); case ui.PointerChange.down: return PointerDownEvent( viewId: datum.viewId, timeStamp: timeStamp, pointer: datum.pointerIdentifier, kind: kind, device: datum.device, position: position, buttons: _synthesiseDownButtons(datum.buttons, kind), obscured: datum.obscured, pressure: datum.pressure, pressureMin: datum.pressureMin, pressureMax: datum.pressureMax, distanceMax: datum.distanceMax, size: datum.size, radiusMajor: radiusMajor, radiusMinor: radiusMinor, radiusMin: radiusMin, radiusMax: radiusMax, orientation: datum.orientation, tilt: datum.tilt, embedderId: datum.embedderId, ); case ui.PointerChange.move: return PointerMoveEvent( viewId: datum.viewId, timeStamp: timeStamp, pointer: datum.pointerIdentifier, kind: kind, device: datum.device, position: position, delta: delta, buttons: _synthesiseDownButtons(datum.buttons, kind), obscured: datum.obscured, pressure: datum.pressure, pressureMin: datum.pressureMin, pressureMax: datum.pressureMax, distanceMax: datum.distanceMax, size: datum.size, radiusMajor: radiusMajor, radiusMinor: radiusMinor, radiusMin: radiusMin, radiusMax: radiusMax, orientation: datum.orientation, tilt: datum.tilt, platformData: datum.platformData, synthesized: datum.synthesized, embedderId: datum.embedderId, ); case ui.PointerChange.up: return PointerUpEvent( viewId: datum.viewId, timeStamp: timeStamp, pointer: datum.pointerIdentifier, kind: kind, device: datum.device, position: position, buttons: datum.buttons, obscured: datum.obscured, pressure: datum.pressure, pressureMin: datum.pressureMin, pressureMax: datum.pressureMax, distance: datum.distance, distanceMax: datum.distanceMax, size: datum.size, radiusMajor: radiusMajor, radiusMinor: radiusMinor, radiusMin: radiusMin, radiusMax: radiusMax, orientation: datum.orientation, tilt: datum.tilt, embedderId: datum.embedderId, ); case ui.PointerChange.cancel: return PointerCancelEvent( viewId: datum.viewId, timeStamp: timeStamp, pointer: datum.pointerIdentifier, kind: kind, device: datum.device, position: position, buttons: datum.buttons, obscured: datum.obscured, pressureMin: datum.pressureMin, pressureMax: datum.pressureMax, distance: datum.distance, distanceMax: datum.distanceMax, size: datum.size, radiusMajor: radiusMajor, radiusMinor: radiusMinor, radiusMin: radiusMin, radiusMax: radiusMax, orientation: datum.orientation, tilt: datum.tilt, embedderId: datum.embedderId, ); case ui.PointerChange.remove: return PointerRemovedEvent( viewId: datum.viewId, timeStamp: timeStamp, kind: kind, device: datum.device, position: position, obscured: datum.obscured, pressureMin: datum.pressureMin, pressureMax: datum.pressureMax, distanceMax: datum.distanceMax, radiusMin: radiusMin, radiusMax: radiusMax, embedderId: datum.embedderId, ); case ui.PointerChange.panZoomStart: return PointerPanZoomStartEvent( viewId: datum.viewId, timeStamp: timeStamp, pointer: datum.pointerIdentifier, device: datum.device, position: position, embedderId: datum.embedderId, synthesized: datum.synthesized, ); case ui.PointerChange.panZoomUpdate: final Offset pan = Offset(datum.panX, datum.panY) / devicePixelRatio; final Offset panDelta = Offset(datum.panDeltaX, datum.panDeltaY) / devicePixelRatio; return PointerPanZoomUpdateEvent( viewId: datum.viewId, timeStamp: timeStamp, pointer: datum.pointerIdentifier, device: datum.device, position: position, pan: pan, panDelta: panDelta, scale: datum.scale, rotation: datum.rotation, embedderId: datum.embedderId, synthesized: datum.synthesized, ); case ui.PointerChange.panZoomEnd: return PointerPanZoomEndEvent( viewId: datum.viewId, timeStamp: timeStamp, pointer: datum.pointerIdentifier, device: datum.device, position: position, embedderId: datum.embedderId, synthesized: datum.synthesized, ); } case ui.PointerSignalKind.scroll: if (!datum.scrollDeltaX.isFinite || !datum.scrollDeltaY.isFinite || devicePixelRatio <= 0) { return null; } final Offset scrollDelta = Offset(datum.scrollDeltaX, datum.scrollDeltaY) / devicePixelRatio; return PointerScrollEvent( viewId: datum.viewId, timeStamp: timeStamp, kind: kind, device: datum.device, position: position, scrollDelta: scrollDelta, embedderId: datum.embedderId, ); case ui.PointerSignalKind.scrollInertiaCancel: return PointerScrollInertiaCancelEvent( viewId: datum.viewId, timeStamp: timeStamp, kind: kind, device: datum.device, position: position, embedderId: datum.embedderId, ); case ui.PointerSignalKind.scale: return PointerScaleEvent( viewId: datum.viewId, timeStamp: timeStamp, kind: kind, device: datum.device, position: position, embedderId: datum.embedderId, scale: datum.scale, ); case ui.PointerSignalKind.unknown: throw StateError('Unreachable'); } }).whereType<PointerEvent>(); } static double _toLogicalPixels(double physicalPixels, double devicePixelRatio) => physicalPixels / devicePixelRatio; }
flutter/packages/flutter/lib/src/gestures/converter.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/gestures/converter.dart", "repo_id": "flutter", "token_count": 7323 }
667
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'arena.dart'; import 'binding.dart'; import 'constants.dart'; import 'debug.dart'; import 'events.dart'; import 'pointer_router.dart'; import 'team.dart'; export 'dart:ui' show Offset, PointerDeviceKind; export 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder; export 'package:vector_math/vector_math_64.dart' show Matrix4; export 'arena.dart' show GestureDisposition; export 'events.dart' show PointerDownEvent, PointerEvent, PointerPanZoomStartEvent; export 'gesture_settings.dart' show DeviceGestureSettings; export 'team.dart' show GestureArenaTeam; /// Generic signature for callbacks passed to /// [GestureRecognizer.invokeCallback]. This allows the /// [GestureRecognizer.invokeCallback] mechanism to be generically used with /// anonymous functions that return objects of particular types. typedef RecognizerCallback<T> = T Function(); /// Configuration of offset passed to [DragStartDetails]. /// /// See also: /// /// * [DragGestureRecognizer.dragStartBehavior], which gives an example for the /// different behaviors. enum DragStartBehavior { /// Set the initial offset at the position where the first down event was /// detected. down, /// Set the initial position at the position where this gesture recognizer /// won the arena. start, } /// Configuration of multi-finger drag strategy on multi-touch devices. /// /// When dragging with only one finger, there's no difference in behavior /// between all the settings. /// /// Used by [DragGestureRecognizer.multitouchDragStrategy]. enum MultitouchDragStrategy { /// Only the latest active pointer is tracked by the recognizer. /// /// If the tracked pointer is released, the first accepted of the remaining active /// pointers will continue to be tracked. /// /// This is the behavior typically seen on Android. latestPointer, /// All active pointers will be tracked, and the result is computed from /// the boundary pointers. /// /// The scrolling offset is determined by the maximum deltas of both directions. /// /// If the user is dragging with 3 pointers at the same time, each having /// \[+10, +20, +33\] pixels of offset, the recognizer will report a delta of 33 pixels. /// /// If the user is dragging with 5 pointers at the same time, each having /// \[+10, +20, +33, -1, -12\] pixels of offset, the recognizer will report a /// delta of (+33) + (-12) = 21 pixels. /// /// The panning [PanGestureRecognizer] offset is the average of all pointers. /// /// If the user is dragging with 3 pointers at the same time, each having /// \[+10, +50, -30\] pixels of offset in one direction (horizontal or vertical), /// the recognizer will report a delta of (10 + 50 -30) / 3 = 10 pixels in this direction. /// /// This is the behavior typically seen on iOS. averageBoundaryPointers, /// All active pointers will be tracked together. The scrolling offset /// is the sum of the offsets of all active pointers. /// /// When a [Scrollable] drives scrolling by this drag strategy, the scrolling /// speed will double or triple, depending on how many fingers are dragging /// at the same time. /// /// If the user is dragging with 3 pointers at the same time, each having /// \[+10, +20, +33\] pixels of offset, the recognizer will report a delta /// of 10 + 20 + 33 = 63 pixels. /// /// If the user is dragging with 5 pointers at the same time, each having /// \[+10, +20, +33, -1, -12\] pixels of offset, the recognizer will report /// a delta of 10 + 20 + 33 - 1 - 12 = 50 pixels. sumAllPointers, } /// Signature for `allowedButtonsFilter` in [GestureRecognizer]. /// Used to filter the input buttons of incoming pointer events. /// The parameter `buttons` comes from [PointerEvent.buttons]. typedef AllowedButtonsFilter = bool Function(int buttons); /// The base class that all gesture recognizers inherit from. /// /// Provides a basic API that can be used by classes that work with /// gesture recognizers but don't care about the specific details of /// the gestures recognizers themselves. /// /// See also: /// /// * [GestureDetector], the widget that is used to detect built-in gestures. /// * [RawGestureDetector], the widget that is used to detect custom gestures. /// * [debugPrintRecognizerCallbacksTrace], a flag that can be set to help /// debug issues with gesture recognizers. abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableTreeMixin { /// Initializes the gesture recognizer. /// /// The argument is optional and is only used for debug purposes (e.g. in the /// [toString] serialization). /// /// {@template flutter.gestures.GestureRecognizer.supportedDevices} /// It's possible to limit this recognizer to a specific set of [PointerDeviceKind]s /// by providing the optional [supportedDevices] argument. If [supportedDevices] is null, /// the recognizer will accept pointer events from all device kinds. /// {@endtemplate} GestureRecognizer({ this.debugOwner, this.supportedDevices, AllowedButtonsFilter? allowedButtonsFilter, }) : _allowedButtonsFilter = allowedButtonsFilter ?? _defaultButtonAcceptBehavior { // TODO(polina-c): stop duplicating code across disposables // https://github.com/flutter/flutter/issues/137435 if (kFlutterMemoryAllocationsEnabled) { FlutterMemoryAllocations.instance.dispatchObjectCreated( library: 'package:flutter/gestures.dart', className: '$GestureRecognizer', object: this, ); } } /// The recognizer's owner. /// /// This is used in the [toString] serialization to report the object for which /// this gesture recognizer was created, to aid in debugging. final Object? debugOwner; /// Optional device specific configuration for device gestures that will /// take precedence over framework defaults. DeviceGestureSettings? gestureSettings; /// The kind of devices that are allowed to be recognized as provided by /// `supportedDevices` in the constructor, or the currently deprecated `kind`. /// These cannot both be set. If both are null, events from all device kinds will be /// tracked and recognized. Set<PointerDeviceKind>? supportedDevices; /// {@template flutter.gestures.multidrag._allowedButtonsFilter} /// Called when interaction starts. This limits the dragging behavior /// for custom clicks (such as scroll click). Its parameter comes /// from [PointerEvent.buttons]. /// /// Due to how [kPrimaryButton], [kSecondaryButton], etc., use integers, /// bitwise operations can help filter how buttons are pressed. /// For example, if someone simultaneously presses the primary and secondary /// buttons, the default behavior will return false. The following code /// accepts any button press with primary: /// `(int buttons) => buttons & kPrimaryButton != 0`. /// /// When value is `(int buttons) => false`, allow no interactions. /// When value is `(int buttons) => true`, allow all interactions. /// /// Defaults to all buttons. /// {@endtemplate} final AllowedButtonsFilter _allowedButtonsFilter; // The default value for [allowedButtonsFilter]. // Accept any input. static bool _defaultButtonAcceptBehavior(int buttons) => true; /// Holds a mapping between pointer IDs and the kind of devices they are /// coming from. final Map<int, PointerDeviceKind> _pointerToKind = <int, PointerDeviceKind>{}; /// Registers a new pointer pan/zoom that might be relevant to this gesture /// detector. /// /// A pointer pan/zoom is a stream of events that conveys data covering /// pan, zoom, and rotate data from a multi-finger trackpad gesture. /// /// The owner of this gesture recognizer calls addPointerPanZoom() with the /// PointerPanZoomStartEvent of each pointer that should be considered for /// this gesture. /// /// It's the GestureRecognizer's responsibility to then add itself /// to the global pointer router (see [PointerRouter]) to receive /// subsequent events for this pointer, and to add the pointer to /// the global gesture arena manager (see [GestureArenaManager]) to track /// that pointer. /// /// This method is called for each and all pointers being added. In /// most cases, you want to override [addAllowedPointerPanZoom] instead. void addPointerPanZoom(PointerPanZoomStartEvent event) { _pointerToKind[event.pointer] = event.kind; if (isPointerPanZoomAllowed(event)) { addAllowedPointerPanZoom(event); } else { handleNonAllowedPointerPanZoom(event); } } /// Registers a new pointer pan/zoom that's been checked to be allowed by this /// gesture recognizer. /// /// Subclasses of [GestureRecognizer] are supposed to override this method /// instead of [addPointerPanZoom] because [addPointerPanZoom] will be called for each /// pointer being added while [addAllowedPointerPanZoom] is only called for pointers /// that are allowed by this recognizer. @protected void addAllowedPointerPanZoom(PointerPanZoomStartEvent event) { } /// Registers a new pointer that might be relevant to this gesture /// detector. /// /// The owner of this gesture recognizer calls addPointer() with the /// PointerDownEvent of each pointer that should be considered for /// this gesture. /// /// It's the GestureRecognizer's responsibility to then add itself /// to the global pointer router (see [PointerRouter]) to receive /// subsequent events for this pointer, and to add the pointer to /// the global gesture arena manager (see [GestureArenaManager]) to track /// that pointer. /// /// This method is called for each and all pointers being added. In /// most cases, you want to override [addAllowedPointer] instead. void addPointer(PointerDownEvent event) { _pointerToKind[event.pointer] = event.kind; if (isPointerAllowed(event)) { addAllowedPointer(event); } else { handleNonAllowedPointer(event); } } /// Registers a new pointer that's been checked to be allowed by this gesture /// recognizer. /// /// Subclasses of [GestureRecognizer] are supposed to override this method /// instead of [addPointer] because [addPointer] will be called for each /// pointer being added while [addAllowedPointer] is only called for pointers /// that are allowed by this recognizer. @protected void addAllowedPointer(PointerDownEvent event) { } /// Handles a pointer being added that's not allowed by this recognizer. /// /// Subclasses can override this method and reject the gesture. /// /// See: /// - [OneSequenceGestureRecognizer.handleNonAllowedPointer]. @protected void handleNonAllowedPointer(PointerDownEvent event) { } /// Checks whether or not a pointer is allowed to be tracked by this recognizer. @protected bool isPointerAllowed(PointerDownEvent event) { return (supportedDevices == null || supportedDevices!.contains(event.kind)) && _allowedButtonsFilter(event.buttons); } /// Handles a pointer pan/zoom being added that's not allowed by this recognizer. /// /// Subclasses can override this method and reject the gesture. @protected void handleNonAllowedPointerPanZoom(PointerPanZoomStartEvent event) { } /// Checks whether or not a pointer pan/zoom is allowed to be tracked by this recognizer. @protected bool isPointerPanZoomAllowed(PointerPanZoomStartEvent event) { return supportedDevices == null || supportedDevices!.contains(event.kind); } /// For a given pointer ID, returns the device kind associated with it. /// /// The pointer ID is expected to be a valid one i.e. an event was received /// with that pointer ID. @protected PointerDeviceKind getKindForPointer(int pointer) { assert(_pointerToKind.containsKey(pointer)); return _pointerToKind[pointer]!; } /// Releases any resources used by the object. /// /// This method is called by the owner of this gesture recognizer /// when the object is no longer needed (e.g. when a gesture /// recognizer is being unregistered from a [GestureDetector], the /// GestureDetector widget calls this method). @mustCallSuper void dispose() { // TODO(polina-c): stop duplicating code across disposables // https://github.com/flutter/flutter/issues/137435 if (kFlutterMemoryAllocationsEnabled) { FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); } } /// Returns a very short pretty description of the gesture that the /// recognizer looks for, like 'tap' or 'horizontal drag'. String get debugDescription; /// Invoke a callback provided by the application, catching and logging any /// exceptions. /// /// The `name` argument is ignored except when reporting exceptions. /// /// The `debugReport` argument is optional and is used when /// [debugPrintRecognizerCallbacksTrace] is true. If specified, it must be a /// callback that returns a string describing useful debugging information, /// e.g. the arguments passed to the callback. @protected @pragma('vm:notify-debugger-on-exception') T? invokeCallback<T>(String name, RecognizerCallback<T> callback, { String Function()? debugReport }) { T? result; try { assert(() { if (debugPrintRecognizerCallbacksTrace) { final String? report = debugReport != null ? debugReport() : null; // The 19 in the line below is the width of the prefix used by // _debugLogDiagnostic in arena.dart. final String prefix = debugPrintGestureArenaDiagnostics ? '${' ' * 19}❙ ' : ''; debugPrint('$prefix$this calling $name callback.${ (report?.isNotEmpty ?? false) ? " $report" : "" }'); } return true; }()); result = callback(); } catch (exception, stack) { InformationCollector? collector; assert(() { collector = () => <DiagnosticsNode>[ StringProperty('Handler', name), DiagnosticsProperty<GestureRecognizer>('Recognizer', this, style: DiagnosticsTreeStyle.errorProperty), ]; return true; }()); FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'gesture', context: ErrorDescription('while handling a gesture'), informationCollector: collector, )); } return result; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<Object>('debugOwner', debugOwner, defaultValue: null)); } } /// Base class for gesture recognizers that can only recognize one /// gesture at a time. For example, a single [TapGestureRecognizer] /// can never recognize two taps happening simultaneously, even if /// multiple pointers are placed on the same widget. /// /// This is in contrast to, for instance, [MultiTapGestureRecognizer], /// which manages each pointer independently and can consider multiple /// simultaneous touches to each result in a separate tap. abstract class OneSequenceGestureRecognizer extends GestureRecognizer { /// Initialize the object. /// /// {@macro flutter.gestures.GestureRecognizer.supportedDevices} OneSequenceGestureRecognizer({ super.debugOwner, super.supportedDevices, super.allowedButtonsFilter, }); final Map<int, GestureArenaEntry> _entries = <int, GestureArenaEntry>{}; final Set<int> _trackedPointers = HashSet<int>(); @override @protected void addAllowedPointer(PointerDownEvent event) { startTrackingPointer(event.pointer, event.transform); } @override @protected void handleNonAllowedPointer(PointerDownEvent event) { resolve(GestureDisposition.rejected); } /// Called when a pointer event is routed to this recognizer. /// /// This will be called for every pointer event while the pointer is being /// tracked. Typically, this recognizer will start tracking the pointer in /// [addAllowedPointer], which means that [handleEvent] will be called /// starting with the [PointerDownEvent] that was passed to [addAllowedPointer]. /// /// See also: /// /// * [startTrackingPointer], which causes pointer events to be routed to /// this recognizer. /// * [stopTrackingPointer], which stops events from being routed to this /// recognizer. /// * [stopTrackingIfPointerNoLongerDown], which conditionally stops events /// from being routed to this recognizer. @protected void handleEvent(PointerEvent event); @override void acceptGesture(int pointer) { } @override void rejectGesture(int pointer) { } /// Called when the number of pointers this recognizer is tracking changes from one to zero. /// /// The given pointer ID is the ID of the last pointer this recognizer was /// tracking. @protected void didStopTrackingLastPointer(int pointer); /// Resolves this recognizer's participation in each gesture arena with the /// given disposition. @protected @mustCallSuper void resolve(GestureDisposition disposition) { final List<GestureArenaEntry> localEntries = List<GestureArenaEntry>.of(_entries.values); _entries.clear(); for (final GestureArenaEntry entry in localEntries) { entry.resolve(disposition); } } /// Resolves this recognizer's participation in the given gesture arena with /// the given disposition. @protected @mustCallSuper void resolvePointer(int pointer, GestureDisposition disposition) { final GestureArenaEntry? entry = _entries[pointer]; if (entry != null) { _entries.remove(pointer); entry.resolve(disposition); } } @override void dispose() { resolve(GestureDisposition.rejected); for (final int pointer in _trackedPointers) { GestureBinding.instance.pointerRouter.removeRoute(pointer, handleEvent); } _trackedPointers.clear(); assert(_entries.isEmpty); super.dispose(); } /// The team that this recognizer belongs to, if any. /// /// If [team] is null, this recognizer competes directly in the /// [GestureArenaManager] to recognize a sequence of pointer events as a /// gesture. If [team] is non-null, this recognizer competes in the arena in /// a group with other recognizers on the same team. /// /// A recognizer can be assigned to a team only when it is not participating /// in the arena. For example, a common time to assign a recognizer to a team /// is shortly after creating the recognizer. GestureArenaTeam? get team => _team; GestureArenaTeam? _team; /// The [team] can only be set once. set team(GestureArenaTeam? value) { assert(value != null); assert(_entries.isEmpty); assert(_trackedPointers.isEmpty); assert(_team == null); _team = value; } GestureArenaEntry _addPointerToArena(int pointer) { return _team?.add(pointer, this) ?? GestureBinding.instance.gestureArena.add(pointer, this); } /// Causes events related to the given pointer ID to be routed to this recognizer. /// /// The pointer events are transformed according to `transform` and then delivered /// to [handleEvent]. The value for the `transform` argument is usually obtained /// from [PointerDownEvent.transform] to transform the events from the global /// coordinate space into the coordinate space of the event receiver. It may be /// null if no transformation is necessary. /// /// Use [stopTrackingPointer] to remove the route added by this function. /// /// This method also adds this recognizer (or its [team] if it's non-null) to /// the gesture arena for the specified pointer. /// /// This is called by [OneSequenceGestureRecognizer.addAllowedPointer]. @protected void startTrackingPointer(int pointer, [Matrix4? transform]) { GestureBinding.instance.pointerRouter.addRoute(pointer, handleEvent, transform); _trackedPointers.add(pointer); // TODO(goderbauer): Enable assert after recognizers properly clean up their defunct `_entries`, see https://github.com/flutter/flutter/issues/117356. // assert(!_entries.containsKey(pointer)); _entries[pointer] = _addPointerToArena(pointer); } /// Stops events related to the given pointer ID from being routed to this recognizer. /// /// If this function reduces the number of tracked pointers to zero, it will /// call [didStopTrackingLastPointer] synchronously. /// /// Use [startTrackingPointer] to add the routes in the first place. @protected void stopTrackingPointer(int pointer) { if (_trackedPointers.contains(pointer)) { GestureBinding.instance.pointerRouter.removeRoute(pointer, handleEvent); _trackedPointers.remove(pointer); if (_trackedPointers.isEmpty) { didStopTrackingLastPointer(pointer); } } } /// Stops tracking the pointer associated with the given event if the event is /// a [PointerUpEvent] or a [PointerCancelEvent] event. @protected void stopTrackingIfPointerNoLongerDown(PointerEvent event) { if (event is PointerUpEvent || event is PointerCancelEvent || event is PointerPanZoomEndEvent) { stopTrackingPointer(event.pointer); } } } /// The possible states of a [PrimaryPointerGestureRecognizer]. /// /// The recognizer advances from [ready] to [possible] when it starts tracking a /// primary pointer. Where it advances from there depends on how the gesture is /// resolved for that pointer: /// /// * If the primary pointer is resolved by the gesture winning the arena, the /// recognizer stays in the [possible] state as long as it continues to track /// a pointer. /// * If the primary pointer is resolved by the gesture being rejected and /// losing the arena, the recognizer's state advances to [defunct]. /// /// Once the recognizer has stopped tracking any remaining pointers, the /// recognizer returns to [ready]. enum GestureRecognizerState { /// The recognizer is ready to start recognizing a gesture. ready, /// The sequence of pointer events seen thus far is consistent with the /// gesture the recognizer is attempting to recognize but the gesture has not /// been accepted definitively. possible, /// Further pointer events cannot cause this recognizer to recognize the /// gesture until the recognizer returns to the [ready] state (typically when /// all the pointers the recognizer is tracking are removed from the screen). defunct, } /// A base class for gesture recognizers that track a single primary pointer. /// /// Gestures based on this class will stop tracking the gesture if the primary /// pointer travels beyond [preAcceptSlopTolerance] or [postAcceptSlopTolerance] /// pixels from the original contact point of the gesture. /// /// If the [preAcceptSlopTolerance] was breached before the gesture was accepted /// in the gesture arena, the gesture will be rejected. abstract class PrimaryPointerGestureRecognizer extends OneSequenceGestureRecognizer { /// Initializes the [deadline] field during construction of subclasses. /// /// {@macro flutter.gestures.GestureRecognizer.supportedDevices} PrimaryPointerGestureRecognizer({ this.deadline, this.preAcceptSlopTolerance = kTouchSlop, this.postAcceptSlopTolerance = kTouchSlop, super.debugOwner, super.supportedDevices, super.allowedButtonsFilter, }) : assert( preAcceptSlopTolerance == null || preAcceptSlopTolerance >= 0, 'The preAcceptSlopTolerance must be positive or null', ), assert( postAcceptSlopTolerance == null || postAcceptSlopTolerance >= 0, 'The postAcceptSlopTolerance must be positive or null', ); /// If non-null, the recognizer will call [didExceedDeadline] after this /// amount of time has elapsed since starting to track the primary pointer. /// /// The [didExceedDeadline] will not be called if the primary pointer is /// accepted, rejected, or all pointers are up or canceled before [deadline]. final Duration? deadline; /// The maximum distance in logical pixels the gesture is allowed to drift /// from the initial touch down position before the gesture is accepted. /// /// Drifting past the allowed slop amount causes the gesture to be rejected. /// /// Can be null to indicate that the gesture can drift for any distance. /// Defaults to 18 logical pixels. final double? preAcceptSlopTolerance; /// The maximum distance in logical pixels the gesture is allowed to drift /// after the gesture has been accepted. /// /// Drifting past the allowed slop amount causes the gesture to stop tracking /// and signaling subsequent callbacks. /// /// Can be null to indicate that the gesture can drift for any distance. /// Defaults to 18 logical pixels. final double? postAcceptSlopTolerance; /// The current state of the recognizer. /// /// See [GestureRecognizerState] for a description of the states. GestureRecognizerState get state => _state; GestureRecognizerState _state = GestureRecognizerState.ready; /// The ID of the primary pointer this recognizer is tracking. /// /// If this recognizer is no longer tracking any pointers, this field holds /// the ID of the primary pointer this recognizer was most recently tracking. /// This enables the recognizer to know which pointer it was most recently /// tracking when [acceptGesture] or [rejectGesture] is called (which may be /// called after the recognizer is no longer tracking a pointer if, e.g. /// [GestureArenaManager.hold] has been called, or if there are other /// recognizers keeping the arena open). int? get primaryPointer => _primaryPointer; int? _primaryPointer; /// The location at which the primary pointer contacted the screen. /// /// This will only be non-null while this recognizer is tracking at least /// one pointer. OffsetPair? get initialPosition => _initialPosition; OffsetPair? _initialPosition; // Whether this pointer is accepted by winning the arena or as defined by // a subclass calling acceptGesture. bool _gestureAccepted = false; Timer? _timer; @override void addAllowedPointer(PointerDownEvent event) { super.addAllowedPointer(event); if (state == GestureRecognizerState.ready) { _state = GestureRecognizerState.possible; _primaryPointer = event.pointer; _initialPosition = OffsetPair(local: event.localPosition, global: event.position); if (deadline != null) { _timer = Timer(deadline!, () => didExceedDeadlineWithEvent(event)); } } } @override void handleNonAllowedPointer(PointerDownEvent event) { if (!_gestureAccepted) { super.handleNonAllowedPointer(event); } } @override void handleEvent(PointerEvent event) { assert(state != GestureRecognizerState.ready); if (state == GestureRecognizerState.possible && event.pointer == primaryPointer) { final bool isPreAcceptSlopPastTolerance = !_gestureAccepted && preAcceptSlopTolerance != null && _getGlobalDistance(event) > preAcceptSlopTolerance!; final bool isPostAcceptSlopPastTolerance = _gestureAccepted && postAcceptSlopTolerance != null && _getGlobalDistance(event) > postAcceptSlopTolerance!; if (event is PointerMoveEvent && (isPreAcceptSlopPastTolerance || isPostAcceptSlopPastTolerance)) { resolve(GestureDisposition.rejected); stopTrackingPointer(primaryPointer!); } else { handlePrimaryPointer(event); } } stopTrackingIfPointerNoLongerDown(event); } /// Override to provide behavior for the primary pointer when the gesture is still possible. @protected void handlePrimaryPointer(PointerEvent event); /// Override to be notified when [deadline] is exceeded. /// /// You must override this method or [didExceedDeadlineWithEvent] if you /// supply a [deadline]. Subclasses that override this method must _not_ /// call `super.didExceedDeadline()`. @protected void didExceedDeadline() { assert(deadline == null); } /// Same as [didExceedDeadline] but receives the [event] that initiated the /// gesture. /// /// You must override this method or [didExceedDeadline] if you supply a /// [deadline]. Subclasses that override this method must _not_ call /// `super.didExceedDeadlineWithEvent(event)`. @protected void didExceedDeadlineWithEvent(PointerDownEvent event) { didExceedDeadline(); } @override void acceptGesture(int pointer) { if (pointer == primaryPointer) { _stopTimer(); _gestureAccepted = true; } } @override void rejectGesture(int pointer) { if (pointer == primaryPointer && state == GestureRecognizerState.possible) { _stopTimer(); _state = GestureRecognizerState.defunct; } } @override void didStopTrackingLastPointer(int pointer) { assert(state != GestureRecognizerState.ready); _stopTimer(); _state = GestureRecognizerState.ready; _initialPosition = null; _gestureAccepted = false; } @override void dispose() { _stopTimer(); super.dispose(); } void _stopTimer() { if (_timer != null) { _timer!.cancel(); _timer = null; } } double _getGlobalDistance(PointerEvent event) { final Offset offset = event.position - initialPosition!.global; return offset.distance; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(EnumProperty<GestureRecognizerState>('state', state)); } } /// A container for a [local] and [global] [Offset] pair. /// /// Usually, the [global] [Offset] is in the coordinate space of the screen /// after conversion to logical pixels and the [local] offset is the same /// [Offset], but transformed to a local coordinate space. @immutable class OffsetPair { /// Creates a [OffsetPair] combining a [local] and [global] [Offset]. const OffsetPair({ required this.local, required this.global, }); /// Creates a [OffsetPair] from [PointerEvent.localPosition] and /// [PointerEvent.position]. OffsetPair.fromEventPosition(PointerEvent event) : local = event.localPosition, global = event.position; /// Creates a [OffsetPair] from [PointerEvent.localDelta] and /// [PointerEvent.delta]. OffsetPair.fromEventDelta(PointerEvent event) : local = event.localDelta, global = event.delta; /// A [OffsetPair] where both [Offset]s are [Offset.zero]. static const OffsetPair zero = OffsetPair(local: Offset.zero, global: Offset.zero); /// The [Offset] in the local coordinate space. final Offset local; /// The [Offset] in the global coordinate space after conversion to logical /// pixels. final Offset global; /// Adds the `other.global` to [global] and `other.local` to [local]. OffsetPair operator+(OffsetPair other) { return OffsetPair( local: local + other.local, global: global + other.global, ); } /// Subtracts the `other.global` from [global] and `other.local` from [local]. OffsetPair operator-(OffsetPair other) { return OffsetPair( local: local - other.local, global: global - other.global, ); } @override String toString() => '${objectRuntimeType(this, 'OffsetPair')}(local: $local, global: $global)'; }
flutter/packages/flutter/lib/src/gestures/recognizer.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/gestures/recognizer.dart", "repo_id": "flutter", "token_count": 9518 }
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. // 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 _$arrow_menu = _AnimatedIconData( Size(48.0, 48.0), <_PathFrames>[ _PathFrames( opacities: <double>[ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(39.94921875, 22.0), Offset(39.999299444085175, 22.321134814951655), Offset(40.123697128128484, 23.4571221977224), Offset(40.127941008338254, 25.772984385261328), Offset(39.36673145070893, 29.679631356759792), Offset(36.03000494036236, 35.505984938867314), Offset(30.483797891740366, 39.621714579092405), Offset(23.719442126984134, 41.17597729654657), Offset(17.808469902722187, 40.26388356552361), Offset(13.571377486425117, 38.15001206462978), Offset(10.73996518894534, 35.74540806580379), Offset(8.908677157504997, 33.47648684184537), Offset(7.746937054898215, 31.506333856475468), Offset(7.021336564573183, 29.876779670456198), Offset(6.575233382277915, 28.57846974488041), Offset(6.306002369153553, 27.58317306758941), Offset(6.147597126684428, 26.85785338221681), Offset(6.058558318339831, 26.3706514388743), Offset(6.013954859968965, 26.093012124442712), Offset(6.000028695609693, 26.000194701816614), Offset(6.0, 26.0), ], ), _PathCubicTo( <Offset>[ Offset(39.94921875, 22.0), Offset(39.999299444085175, 22.321134814951655), Offset(40.123697128128484, 23.4571221977224), Offset(40.127941008338254, 25.772984385261328), Offset(39.36673145070893, 29.679631356759792), Offset(36.03000494036236, 35.505984938867314), Offset(30.483797891740366, 39.621714579092405), Offset(23.719442126984134, 41.17597729654657), Offset(17.808469902722187, 40.26388356552361), Offset(13.571377486425117, 38.15001206462978), Offset(10.73996518894534, 35.74540806580379), Offset(8.908677157504997, 33.47648684184537), Offset(7.746937054898215, 31.506333856475468), Offset(7.021336564573183, 29.876779670456198), Offset(6.575233382277915, 28.57846974488041), Offset(6.306002369153553, 27.58317306758941), Offset(6.147597126684428, 26.85785338221681), Offset(6.058558318339831, 26.3706514388743), Offset(6.013954859968965, 26.093012124442712), Offset(6.000028695609693, 26.000194701816614), Offset(6.0, 26.0), ], <Offset>[ Offset(12.562500000000004, 21.999999999999996), Offset(12.563028263179644, 21.76974679627851), Offset(12.601915221773575, 20.955868783506492), Offset(12.859988895862408, 19.29992503795225), Offset(13.868967368048864, 16.521093282496043), Offset(17.119246052043927, 12.463158561907132), Offset(22.085512547276693, 9.843640931525094), Offset(27.97135871762438, 9.40112844480027), Offset(33.018872763119475, 10.9710702242868), Offset(36.55408111158449, 13.438130103560162), Offset(38.838028231283474, 16.033718047868426), Offset(40.24471329470705, 18.407336125221466), Offset(41.07692592252046, 20.434907268146556), Offset(41.54755362886814, 22.095337098743826), Offset(41.7985009918588, 23.40952601819154), Offset(41.921690170757245, 24.41237661448199), Offset(41.975185653795926, 25.14085315878499), Offset(41.994340767445394, 25.629108510947514), Offset(41.999299914344064, 25.906972804802937), Offset(41.99999903720365, 25.999805298117412), Offset(42.0, 26.0), ], <Offset>[ Offset(12.562500000000004, 21.999999999999996), Offset(12.563028263179644, 21.76974679627851), Offset(12.601915221773575, 20.955868783506492), Offset(12.859988895862408, 19.29992503795225), Offset(13.868967368048864, 16.521093282496043), Offset(17.119246052043927, 12.463158561907132), Offset(22.085512547276693, 9.843640931525094), Offset(27.97135871762438, 9.40112844480027), Offset(33.018872763119475, 10.9710702242868), Offset(36.55408111158449, 13.438130103560162), Offset(38.838028231283474, 16.033718047868426), Offset(40.24471329470705, 18.407336125221466), Offset(41.07692592252046, 20.434907268146556), Offset(41.54755362886814, 22.095337098743826), Offset(41.7985009918588, 23.40952601819154), Offset(41.921690170757245, 24.41237661448199), Offset(41.975185653795926, 25.14085315878499), Offset(41.994340767445394, 25.629108510947514), Offset(41.999299914344064, 25.906972804802937), Offset(41.99999903720365, 25.999805298117412), Offset(42.0, 26.0), ], ), _PathCubicTo( <Offset>[ Offset(12.562500000000004, 21.999999999999996), Offset(12.563028263179644, 21.76974679627851), Offset(12.601915221773575, 20.955868783506492), Offset(12.859988895862408, 19.29992503795225), Offset(13.868967368048864, 16.521093282496043), Offset(17.119246052043927, 12.463158561907132), Offset(22.085512547276693, 9.843640931525094), Offset(27.97135871762438, 9.40112844480027), Offset(33.018872763119475, 10.9710702242868), Offset(36.55408111158449, 13.438130103560162), Offset(38.838028231283474, 16.033718047868426), Offset(40.24471329470705, 18.407336125221466), Offset(41.07692592252046, 20.434907268146556), Offset(41.54755362886814, 22.095337098743826), Offset(41.7985009918588, 23.40952601819154), Offset(41.921690170757245, 24.41237661448199), Offset(41.975185653795926, 25.14085315878499), Offset(41.994340767445394, 25.629108510947514), Offset(41.999299914344064, 25.906972804802937), Offset(41.99999903720365, 25.999805298117412), Offset(42.0, 26.0), ], <Offset>[ Offset(12.562500000000004, 25.999999999999996), Offset(12.482656306166858, 25.76893925832956), Offset(12.239876568700678, 24.939451092644983), Offset(11.936115204605002, 23.191770024922107), Offset(12.03457162794638, 20.07566671241613), Offset(14.027204238592981, 15.000731698561715), Offset(18.235691601462104, 10.929402730985391), Offset(24.00669715972937, 8.870601601606145), Offset(29.46892180503868, 9.127744915172523), Offset(33.625033100689926, 10.714038007122415), Offset(36.54081321903698, 12.759148887275034), Offset(38.511185280577465, 14.802494849349817), Offset(39.815969078409935, 16.638858290947915), Offset(40.668101748647686, 18.193214036822702), Offset(41.21772917473674, 19.451912583754474), Offset(41.566980772751144, 20.42813499995029), Offset(41.783709535999954, 21.145438675115766), Offset(41.9118174384751, 21.629959864025817), Offset(41.978620736948194, 21.907026258707322), Offset(41.99995577009031, 21.99980529835142), Offset(42.0, 22.0), ], <Offset>[ Offset(12.562500000000004, 25.999999999999996), Offset(12.482656306166858, 25.76893925832956), Offset(12.239876568700678, 24.939451092644983), Offset(11.936115204605002, 23.191770024922107), Offset(12.03457162794638, 20.07566671241613), Offset(14.027204238592981, 15.000731698561715), Offset(18.235691601462104, 10.929402730985391), Offset(24.00669715972937, 8.870601601606145), Offset(29.46892180503868, 9.127744915172523), Offset(33.625033100689926, 10.714038007122415), Offset(36.54081321903698, 12.759148887275034), Offset(38.511185280577465, 14.802494849349817), Offset(39.815969078409935, 16.638858290947915), Offset(40.668101748647686, 18.193214036822702), Offset(41.21772917473674, 19.451912583754474), Offset(41.566980772751144, 20.42813499995029), Offset(41.783709535999954, 21.145438675115766), Offset(41.9118174384751, 21.629959864025817), Offset(41.978620736948194, 21.907026258707322), Offset(41.99995577009031, 21.99980529835142), Offset(42.0, 22.0), ], ), _PathCubicTo( <Offset>[ Offset(12.562500000000004, 25.999999999999996), Offset(12.482656306166858, 25.76893925832956), Offset(12.239876568700678, 24.939451092644983), Offset(11.936115204605002, 23.191770024922107), Offset(12.03457162794638, 20.07566671241613), Offset(14.027204238592981, 15.000731698561715), Offset(18.235691601462104, 10.929402730985391), Offset(24.00669715972937, 8.870601601606145), Offset(29.46892180503868, 9.127744915172523), Offset(33.625033100689926, 10.714038007122415), Offset(36.54081321903698, 12.759148887275034), Offset(38.511185280577465, 14.802494849349817), Offset(39.815969078409935, 16.638858290947915), Offset(40.668101748647686, 18.193214036822702), Offset(41.21772917473674, 19.451912583754474), Offset(41.566980772751144, 20.42813499995029), Offset(41.783709535999954, 21.145438675115766), Offset(41.9118174384751, 21.629959864025817), Offset(41.978620736948194, 21.907026258707322), Offset(41.99995577009031, 21.99980529835142), Offset(42.0, 22.0), ], <Offset>[ Offset(39.94921875, 26.0), Offset(39.91892748707239, 26.320327277002704), Offset(39.76165847505559, 27.44070450686089), Offset(39.204067317080856, 29.66482937223119), Offset(37.532335710606446, 33.23420478667988), Offset(32.93796312691141, 38.04355807552189), Offset(26.633976945925774, 40.7074763785527), Offset(19.754780569089124, 40.645450453352446), Offset(14.258518944641395, 38.42055825640933), Offset(10.642329475530556, 35.42591996819203), Offset(8.442750176698839, 32.47083890521039), Offset(7.175149143375414, 29.871645565973722), Offset(6.485980210787691, 27.710284879276827), Offset(6.141884684352732, 25.97465660853507), Offset(5.994461565155852, 24.620856310443347), Offset(5.951292971147453, 23.598931453057713), Offset(5.956121008888456, 22.862438898547587), Offset(5.976034989369527, 22.3715027919526), Offset(5.9932756825730955, 22.093065578347097), Offset(5.999985428496359, 22.00019470205062), Offset(6.0, 22.0), ], <Offset>[ Offset(39.94921875, 26.0), Offset(39.91892748707239, 26.320327277002704), Offset(39.76165847505559, 27.44070450686089), Offset(39.204067317080856, 29.66482937223119), Offset(37.532335710606446, 33.23420478667988), Offset(32.93796312691141, 38.04355807552189), Offset(26.633976945925774, 40.7074763785527), Offset(19.754780569089124, 40.645450453352446), Offset(14.258518944641395, 38.42055825640933), Offset(10.642329475530556, 35.42591996819203), Offset(8.442750176698839, 32.47083890521039), Offset(7.175149143375414, 29.871645565973722), Offset(6.485980210787691, 27.710284879276827), Offset(6.141884684352732, 25.97465660853507), Offset(5.994461565155852, 24.620856310443347), Offset(5.951292971147453, 23.598931453057713), Offset(5.956121008888456, 22.862438898547587), Offset(5.976034989369527, 22.3715027919526), Offset(5.9932756825730955, 22.093065578347097), Offset(5.999985428496359, 22.00019470205062), Offset(6.0, 22.0), ], ), _PathCubicTo( <Offset>[ Offset(39.94921875, 26.0), Offset(39.91892748707239, 26.320327277002704), Offset(39.76165847505559, 27.44070450686089), Offset(39.204067317080856, 29.66482937223119), Offset(37.532335710606446, 33.23420478667988), Offset(32.93796312691141, 38.04355807552189), Offset(26.633976945925774, 40.7074763785527), Offset(19.754780569089124, 40.645450453352446), Offset(14.258518944641395, 38.42055825640933), Offset(10.642329475530556, 35.42591996819203), Offset(8.442750176698839, 32.47083890521039), Offset(7.175149143375414, 29.871645565973722), Offset(6.485980210787691, 27.710284879276827), Offset(6.141884684352732, 25.97465660853507), Offset(5.994461565155852, 24.620856310443347), Offset(5.951292971147453, 23.598931453057713), Offset(5.956121008888456, 22.862438898547587), Offset(5.976034989369527, 22.3715027919526), Offset(5.9932756825730955, 22.093065578347097), Offset(5.999985428496359, 22.00019470205062), Offset(6.0, 22.0), ], <Offset>[ Offset(39.94921875, 22.0), Offset(39.999299444085175, 22.321134814951655), Offset(40.123697128128484, 23.4571221977224), Offset(40.127941008338254, 25.772984385261328), Offset(39.36673145070893, 29.679631356759792), Offset(36.03000494036236, 35.505984938867314), Offset(30.483797891740366, 39.621714579092405), Offset(23.719442126984134, 41.17597729654657), Offset(17.808469902722187, 40.26388356552361), Offset(13.571377486425117, 38.15001206462978), Offset(10.73996518894534, 35.74540806580379), Offset(8.908677157504997, 33.47648684184537), Offset(7.746937054898215, 31.506333856475468), Offset(7.021336564573183, 29.876779670456198), Offset(6.575233382277915, 28.57846974488041), Offset(6.306002369153553, 27.58317306758941), Offset(6.147597126684428, 26.85785338221681), Offset(6.058558318339831, 26.3706514388743), Offset(6.013954859968965, 26.093012124442712), Offset(6.000028695609693, 26.000194701816614), Offset(6.0, 26.0), ], <Offset>[ Offset(39.94921875, 22.0), Offset(39.999299444085175, 22.321134814951655), Offset(40.123697128128484, 23.4571221977224), Offset(40.127941008338254, 25.772984385261328), Offset(39.36673145070893, 29.679631356759792), Offset(36.03000494036236, 35.505984938867314), Offset(30.483797891740366, 39.621714579092405), Offset(23.719442126984134, 41.17597729654657), Offset(17.808469902722187, 40.26388356552361), Offset(13.571377486425117, 38.15001206462978), Offset(10.73996518894534, 35.74540806580379), Offset(8.908677157504997, 33.47648684184537), Offset(7.746937054898215, 31.506333856475468), Offset(7.021336564573183, 29.876779670456198), Offset(6.575233382277915, 28.57846974488041), Offset(6.306002369153553, 27.58317306758941), Offset(6.147597126684428, 26.85785338221681), Offset(6.058558318339831, 26.3706514388743), Offset(6.013954859968965, 26.093012124442712), Offset(6.000028695609693, 26.000194701816614), Offset(6.0, 26.0), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(24.00120242935725, 7.98287044589657), Offset(24.475307447859166, 8.003617986907148), Offset(26.126659093516306, 8.177690670193112), Offset(29.352785593371877, 8.997654274881697), Offset(34.261760845645924, 11.73586028864448), Offset(39.689530947675216, 19.233828052194387), Offset(40.483245113546566, 28.57182115613015), Offset(36.43819118187483, 37.011448735029944), Offset(29.990575804517718, 41.869715613211284), Offset(23.79684347484401, 43.53566841500789), Offset(18.750267725016194, 43.37984126279926), Offset(14.90588210305647, 42.37202895863352), Offset(12.06653769423517, 41.068216372655385), Offset(10.005013565343445, 39.76135295541911), Offset(8.528791010746735, 38.595867902966916), Offset(7.490777665658619, 37.63578444828991), Offset(6.783719048719078, 36.90231589146764), Offset(6.331695603851976, 36.39438332503497), Offset(6.082250821137091, 36.09960487240796), Offset(6.000171486902083, 36.000208945476956), Offset(6.0, 36.0), ], ), _PathCubicTo( <Offset>[ Offset(24.00120242935725, 7.98287044589657), Offset(24.475307447859166, 8.003617986907148), Offset(26.126659093516306, 8.177690670193112), Offset(29.352785593371877, 8.997654274881697), Offset(34.261760845645924, 11.73586028864448), Offset(39.689530947675216, 19.233828052194387), Offset(40.483245113546566, 28.57182115613015), Offset(36.43819118187483, 37.011448735029944), Offset(29.990575804517718, 41.869715613211284), Offset(23.79684347484401, 43.53566841500789), Offset(18.750267725016194, 43.37984126279926), Offset(14.90588210305647, 42.37202895863352), Offset(12.06653769423517, 41.068216372655385), Offset(10.005013565343445, 39.76135295541911), Offset(8.528791010746735, 38.595867902966916), Offset(7.490777665658619, 37.63578444828991), Offset(6.783719048719078, 36.90231589146764), Offset(6.331695603851976, 36.39438332503497), Offset(6.082250821137091, 36.09960487240796), Offset(6.000171486902083, 36.000208945476956), Offset(6.0, 36.0), ], <Offset>[ Offset(8.389135783884633, 23.59493709136918), Offset(8.411539419733579, 23.280020314446016), Offset(8.535460203545142, 22.174793784450976), Offset(9.004955277979905, 19.95721448439121), Offset(10.506583157969082, 16.301391783224325), Offset(15.00736732713968, 11.07994257565777), Offset(21.799606746441338, 7.957602889938901), Offset(29.78681308270101, 8.138822767869717), Offset(36.3635225612393, 11.3666818389531), Offset(40.53777507406921, 15.843550126760437), Offset(42.771588169072636, 20.33326716415372), Offset(43.71871364987625, 24.29568645796705), Offset(43.90383296365319, 27.574365631376406), Offset(43.68696452483883, 30.181901809762802), Offset(43.29833346247236, 32.192150096307955), Offset(42.87820947711742, 33.69183670134356), Offset(42.5074211611244, 34.76136730547495), Offset(42.22832709352211, 35.46839060016271), Offset(42.058590816793185, 35.86711275140609), Offset(42.00012355171139, 35.99972219110006), Offset(42.0, 36.0), ], <Offset>[ Offset(8.389135783884633, 23.59493709136918), Offset(8.411539419733579, 23.280020314446016), Offset(8.535460203545142, 22.174793784450976), Offset(9.004955277979905, 19.95721448439121), Offset(10.506583157969082, 16.301391783224325), Offset(15.00736732713968, 11.07994257565777), Offset(21.799606746441338, 7.957602889938901), Offset(29.78681308270101, 8.138822767869717), Offset(36.3635225612393, 11.3666818389531), Offset(40.53777507406921, 15.843550126760437), Offset(42.771588169072636, 20.33326716415372), Offset(43.71871364987625, 24.29568645796705), Offset(43.90383296365319, 27.574365631376406), Offset(43.68696452483883, 30.181901809762802), Offset(43.29833346247236, 32.192150096307955), Offset(42.87820947711742, 33.69183670134356), Offset(42.5074211611244, 34.76136730547495), Offset(42.22832709352211, 35.46839060016271), Offset(42.058590816793185, 35.86711275140609), Offset(42.00012355171139, 35.99972219110006), Offset(42.0, 36.0), ], ), _PathCubicTo( <Offset>[ Offset(8.389135783884633, 23.59493709136918), Offset(8.411539419733579, 23.280020314446016), Offset(8.535460203545142, 22.174793784450976), Offset(9.004955277979905, 19.95721448439121), Offset(10.506583157969082, 16.301391783224325), Offset(15.00736732713968, 11.07994257565777), Offset(21.799606746441338, 7.957602889938901), Offset(29.78681308270101, 8.138822767869717), Offset(36.3635225612393, 11.3666818389531), Offset(40.53777507406921, 15.843550126760437), Offset(42.771588169072636, 20.33326716415372), Offset(43.71871364987625, 24.29568645796705), Offset(43.90383296365319, 27.574365631376406), Offset(43.68696452483883, 30.181901809762802), Offset(43.29833346247236, 32.192150096307955), Offset(42.87820947711742, 33.69183670134356), Offset(42.5074211611244, 34.76136730547495), Offset(42.22832709352211, 35.46839060016271), Offset(42.058590816793185, 35.86711275140609), Offset(42.00012355171139, 35.99972219110006), Offset(42.0, 36.0), ], <Offset>[ Offset(11.217562908630821, 26.423364216115367), Offset(11.168037593988725, 26.178591999833156), Offset(11.026001684399013, 25.304842207741935), Offset(10.901761927954412, 23.478879507162752), Offset(11.261530717110908, 20.229502548330856), Offset(13.752640365544114, 14.878055298029915), Offset(18.8358022450215, 10.643838709326973), Offset(25.888907364460923, 9.03678212759111), Offset(32.44806665065668, 10.54863232194106), Offset(37.11467529624949, 13.774157000481484), Offset(40.00232975553069, 17.44688398809633), Offset(41.592943181014675, 20.907309278000795), Offset(42.34289639575017, 23.891503017731534), Offset(42.59272365615382, 26.334482295166104), Offset(42.57381482854062, 28.258313197161566), Offset(42.4351505629611, 29.71645007881405), Offset(42.26812747456164, 30.76853140456803), Offset(42.125177049114, 31.469720812803587), Offset(42.03274190981708, 31.867196273027055), Offset(42.00006946781973, 31.999722191465697), Offset(42.0, 32.0), ], <Offset>[ Offset(11.217562908630821, 26.423364216115367), Offset(11.168037593988725, 26.178591999833156), Offset(11.026001684399013, 25.304842207741935), Offset(10.901761927954412, 23.478879507162752), Offset(11.261530717110908, 20.229502548330856), Offset(13.752640365544114, 14.878055298029915), Offset(18.8358022450215, 10.643838709326973), Offset(25.888907364460923, 9.03678212759111), Offset(32.44806665065668, 10.54863232194106), Offset(37.11467529624949, 13.774157000481484), Offset(40.00232975553069, 17.44688398809633), Offset(41.592943181014675, 20.907309278000795), Offset(42.34289639575017, 23.891503017731534), Offset(42.59272365615382, 26.334482295166104), Offset(42.57381482854062, 28.258313197161566), Offset(42.4351505629611, 29.71645007881405), Offset(42.26812747456164, 30.76853140456803), Offset(42.125177049114, 31.469720812803587), Offset(42.03274190981708, 31.867196273027055), Offset(42.00006946781973, 31.999722191465697), Offset(42.0, 32.0), ], ), _PathCubicTo( <Offset>[ Offset(11.217562908630821, 26.423364216115367), Offset(11.168037593988725, 26.178591999833156), Offset(11.026001684399013, 25.304842207741935), Offset(10.901761927954412, 23.478879507162752), Offset(11.261530717110908, 20.229502548330856), Offset(13.752640365544114, 14.878055298029915), Offset(18.8358022450215, 10.643838709326973), Offset(25.888907364460923, 9.03678212759111), Offset(32.44806665065668, 10.54863232194106), Offset(37.11467529624949, 13.774157000481484), Offset(40.00232975553069, 17.44688398809633), Offset(41.592943181014675, 20.907309278000795), Offset(42.34289639575017, 23.891503017731534), Offset(42.59272365615382, 26.334482295166104), Offset(42.57381482854062, 28.258313197161566), Offset(42.4351505629611, 29.71645007881405), Offset(42.26812747456164, 30.76853140456803), Offset(42.125177049114, 31.469720812803587), Offset(42.03274190981708, 31.867196273027055), Offset(42.00006946781973, 31.999722191465697), Offset(42.0, 32.0), ], <Offset>[ Offset(26.829629554103438, 10.811297570642758), Offset(27.231805622114308, 10.902189672294288), Offset(28.61720057437018, 11.307739093484066), Offset(31.249592243346385, 12.519319297653237), Offset(35.01670840478775, 15.663971053751007), Offset(38.43480398607965, 23.031940774566532), Offset(37.51944061212673, 31.258056975518222), Offset(32.54028546363474, 37.909408094751335), Offset(26.0751198939351, 41.05166609619924), Offset(20.373743697024292, 41.46627528872894), Offset(15.981009311474246, 40.49345808674188), Offset(12.780111634194903, 38.983651778667266), Offset(10.505601126332149, 37.38535375901051), Offset(8.910772696658444, 35.91393344082242), Offset(7.804272376814996, 34.66203100382052), Offset(7.047718751502295, 33.6603978257604), Offset(6.544425362156314, 32.90947999056071), Offset(6.228545559443866, 32.39571353767585), Offset(6.056401914160979, 32.099688394028924), Offset(6.000117403010417, 32.00020894584259), Offset(6.0, 32.0), ], <Offset>[ Offset(26.829629554103438, 10.811297570642758), Offset(27.231805622114308, 10.902189672294288), Offset(28.61720057437018, 11.307739093484066), Offset(31.249592243346385, 12.519319297653237), Offset(35.01670840478775, 15.663971053751007), Offset(38.43480398607965, 23.031940774566532), Offset(37.51944061212673, 31.258056975518222), Offset(32.54028546363474, 37.909408094751335), Offset(26.0751198939351, 41.05166609619924), Offset(20.373743697024292, 41.46627528872894), Offset(15.981009311474246, 40.49345808674188), Offset(12.780111634194903, 38.983651778667266), Offset(10.505601126332149, 37.38535375901051), Offset(8.910772696658444, 35.91393344082242), Offset(7.804272376814996, 34.66203100382052), Offset(7.047718751502295, 33.6603978257604), Offset(6.544425362156314, 32.90947999056071), Offset(6.228545559443866, 32.39571353767585), Offset(6.056401914160979, 32.099688394028924), Offset(6.000117403010417, 32.00020894584259), Offset(6.0, 32.0), ], ), _PathCubicTo( <Offset>[ Offset(26.829629554103438, 10.811297570642758), Offset(27.231805622114308, 10.902189672294288), Offset(28.61720057437018, 11.307739093484066), Offset(31.249592243346385, 12.519319297653237), Offset(35.01670840478775, 15.663971053751007), Offset(38.43480398607965, 23.031940774566532), Offset(37.51944061212673, 31.258056975518222), Offset(32.54028546363474, 37.909408094751335), Offset(26.0751198939351, 41.05166609619924), Offset(20.373743697024292, 41.46627528872894), Offset(15.981009311474246, 40.49345808674188), Offset(12.780111634194903, 38.983651778667266), Offset(10.505601126332149, 37.38535375901051), Offset(8.910772696658444, 35.91393344082242), Offset(7.804272376814996, 34.66203100382052), Offset(7.047718751502295, 33.6603978257604), Offset(6.544425362156314, 32.90947999056071), Offset(6.228545559443866, 32.39571353767585), Offset(6.056401914160979, 32.099688394028924), Offset(6.000117403010417, 32.00020894584259), Offset(6.0, 32.0), ], <Offset>[ Offset(24.00120242935725, 7.98287044589657), Offset(24.475307447859166, 8.003617986907148), Offset(26.126659093516306, 8.177690670193112), Offset(29.352785593371877, 8.997654274881697), Offset(34.261760845645924, 11.73586028864448), Offset(39.689530947675216, 19.233828052194387), Offset(40.483245113546566, 28.57182115613015), Offset(36.43819118187483, 37.011448735029944), Offset(29.990575804517718, 41.869715613211284), Offset(23.79684347484401, 43.53566841500789), Offset(18.750267725016194, 43.37984126279926), Offset(14.90588210305647, 42.37202895863352), Offset(12.06653769423517, 41.068216372655385), Offset(10.005013565343445, 39.76135295541911), Offset(8.528791010746735, 38.595867902966916), Offset(7.490777665658619, 37.63578444828991), Offset(6.783719048719078, 36.90231589146764), Offset(6.331695603851976, 36.39438332503497), Offset(6.082250821137091, 36.09960487240796), Offset(6.000171486902083, 36.000208945476956), Offset(6.0, 36.0), ], <Offset>[ Offset(24.00120242935725, 7.98287044589657), Offset(24.475307447859166, 8.003617986907148), Offset(26.126659093516306, 8.177690670193112), Offset(29.352785593371877, 8.997654274881697), Offset(34.261760845645924, 11.73586028864448), Offset(39.689530947675216, 19.233828052194387), Offset(40.483245113546566, 28.57182115613015), Offset(36.43819118187483, 37.011448735029944), Offset(29.990575804517718, 41.869715613211284), Offset(23.79684347484401, 43.53566841500789), Offset(18.750267725016194, 43.37984126279926), Offset(14.90588210305647, 42.37202895863352), Offset(12.06653769423517, 41.068216372655385), Offset(10.005013565343445, 39.76135295541911), Offset(8.528791010746735, 38.595867902966916), Offset(7.490777665658619, 37.63578444828991), Offset(6.783719048719078, 36.90231589146764), Offset(6.331695603851976, 36.39438332503497), Offset(6.082250821137091, 36.09960487240796), Offset(6.000171486902083, 36.000208945476956), Offset(6.0, 36.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(26.829629554103434, 37.188702429357235), Offset(26.70295401712204, 37.21708146835027), Offset(26.253437940457104, 37.31668297706097), Offset(25.316159296509255, 37.51407939114749), Offset(23.588416071597663, 37.80897683895165), Offset(20.234451203252327, 37.9685842890323), Offset(16.265106286835728, 37.25239920809595), Offset(12.10312127594884, 35.1746313573166), Offset(8.858593681675742, 32.111920483700914), Offset(6.842177615689938, 28.881561047964333), Offset(5.761956468124708, 25.926691322240227), Offset(5.290469810431201, 23.40907221160189), Offset(5.178751382636996, 21.349132840198116), Offset(5.258916359304976, 19.710667345993283), Offset(5.423821188616003, 18.440676377623248), Offset(5.607765949538116, 17.48625665894383), Offset(5.772423819137188, 16.80059820468561), Offset(5.897326348355019, 16.34455713877282), Offset(5.973614735709873, 16.086271507697752), Offset(5.9999443342489265, 16.000180457509614), Offset(6.0, 16.0), ], ), _PathCubicTo( <Offset>[ Offset(26.829629554103434, 37.188702429357235), Offset(26.70295401712204, 37.21708146835027), Offset(26.253437940457104, 37.31668297706097), Offset(25.316159296509255, 37.51407939114749), Offset(23.588416071597663, 37.80897683895165), Offset(20.234451203252327, 37.9685842890323), Offset(16.265106286835728, 37.25239920809595), Offset(12.10312127594884, 35.1746313573166), Offset(8.858593681675742, 32.111920483700914), Offset(6.842177615689938, 28.881561047964333), Offset(5.761956468124708, 25.926691322240227), Offset(5.290469810431201, 23.40907221160189), Offset(5.178751382636996, 21.349132840198116), Offset(5.258916359304976, 19.710667345993283), Offset(5.423821188616003, 18.440676377623248), Offset(5.607765949538116, 17.48625665894383), Offset(5.772423819137188, 16.80059820468561), Offset(5.897326348355019, 16.34455713877282), Offset(5.973614735709873, 16.086271507697752), Offset(5.9999443342489265, 16.000180457509614), Offset(6.0, 16.0), ], <Offset>[ Offset(11.2175487664952, 21.576649926020245), Offset(11.26591566746795, 21.307620185014063), Offset(11.473792301821605, 20.377637880770784), Offset(12.06502589368821, 18.578567196580664), Offset(13.54646415229777, 15.801892832848761), Offset(17.052481673761243, 12.16993860231353), Offset(21.42462731807053, 9.9137145270952), Offset(26.111676903911107, 9.066591789474842), Offset(30.142827978195022, 9.351628521416771), Offset(33.249292834290536, 10.17924910714327), Offset(35.60828563949723, 11.183386110908502), Offset(37.40014550074941, 12.188459616498097), Offset(38.76213503811523, 13.111795882844753), Offset(39.793775377370764, 13.915564474413902), Offset(40.567255045797005, 14.584805428587808), Offset(41.13536943122808, 15.116774671440997), Offset(41.537143495419784, 15.5155379179047), Offset(41.801600251554405, 15.788922082526666), Offset(41.95043550915973, 15.946775613712157), Offset(41.99989640116428, 15.999888404883473), Offset(42.0, 16.0), ], <Offset>[ Offset(11.2175487664952, 21.576649926020245), Offset(11.26591566746795, 21.307620185014063), Offset(11.473792301821605, 20.377637880770784), Offset(12.06502589368821, 18.578567196580664), Offset(13.54646415229777, 15.801892832848761), Offset(17.052481673761243, 12.16993860231353), Offset(21.42462731807053, 9.9137145270952), Offset(26.111676903911107, 9.066591789474842), Offset(30.142827978195022, 9.351628521416771), Offset(33.249292834290536, 10.17924910714327), Offset(35.60828563949723, 11.183386110908502), Offset(37.40014550074941, 12.188459616498097), Offset(38.76213503811523, 13.111795882844753), Offset(39.793775377370764, 13.915564474413902), Offset(40.567255045797005, 14.584805428587808), Offset(41.13536943122808, 15.116774671440997), Offset(41.537143495419784, 15.5155379179047), Offset(41.801600251554405, 15.788922082526666), Offset(41.95043550915973, 15.946775613712157), Offset(41.99989640116428, 15.999888404883473), Offset(42.0, 16.0), ], ), _PathCubicTo( <Offset>[ Offset(11.2175487664952, 21.576649926020245), Offset(11.26591566746795, 21.307620185014063), Offset(11.473792301821605, 20.377637880770784), Offset(12.06502589368821, 18.578567196580664), Offset(13.54646415229777, 15.801892832848761), Offset(17.052481673761243, 12.16993860231353), Offset(21.42462731807053, 9.9137145270952), Offset(26.111676903911107, 9.066591789474842), Offset(30.142827978195022, 9.351628521416771), Offset(33.249292834290536, 10.17924910714327), Offset(35.60828563949723, 11.183386110908502), Offset(37.40014550074941, 12.188459616498097), Offset(38.76213503811523, 13.111795882844753), Offset(39.793775377370764, 13.915564474413902), Offset(40.567255045797005, 14.584805428587808), Offset(41.13536943122808, 15.116774671440997), Offset(41.537143495419784, 15.5155379179047), Offset(41.801600251554405, 15.788922082526666), Offset(41.95043550915973, 15.946775613712157), Offset(41.99989640116428, 15.999888404883473), Offset(42.0, 16.0), ], <Offset>[ Offset(8.38912164174901, 24.405077050766437), Offset(8.395184821848037, 24.09310118692493), Offset(8.459782153583708, 23.007417876572518), Offset(8.787794358833729, 20.871982437428983), Offset(9.907414129760891, 17.4624092987335), Offset(13.082563535366404, 12.659581303110395), Offset(17.494014200747685, 9.171905574648836), Offset(22.5870000408063, 7.175387672861925), Offset(27.221252362148654, 6.6195238529014375), Offset(30.937448027657968, 6.914992133489694), Offset(33.83674155554175, 7.597074418012536), Offset(36.08060605872299, 8.412374916582504), Offset(37.809259485732085, 9.226949916571378), Offset(39.13181277597566, 9.970719038360135), Offset(40.13100060158848, 10.608666338979862), Offset(40.8691843334897, 11.125641311887346), Offset(41.393512389333864, 11.518117486505904), Offset(41.739705833610245, 11.789400976065625), Offset(41.934926095887384, 11.946805681562672), Offset(41.99986395082928, 11.999888405015101), Offset(42.0, 12.0), ], <Offset>[ Offset(8.38912164174901, 24.405077050766437), Offset(8.395184821848037, 24.09310118692493), Offset(8.459782153583708, 23.007417876572518), Offset(8.787794358833729, 20.871982437428983), Offset(9.907414129760891, 17.4624092987335), Offset(13.082563535366404, 12.659581303110395), Offset(17.494014200747685, 9.171905574648836), Offset(22.5870000408063, 7.175387672861925), Offset(27.221252362148654, 6.6195238529014375), Offset(30.937448027657968, 6.914992133489694), Offset(33.83674155554175, 7.597074418012536), Offset(36.08060605872299, 8.412374916582504), Offset(37.809259485732085, 9.226949916571378), Offset(39.13181277597566, 9.970719038360135), Offset(40.13100060158848, 10.608666338979862), Offset(40.8691843334897, 11.125641311887346), Offset(41.393512389333864, 11.518117486505904), Offset(41.739705833610245, 11.789400976065625), Offset(41.934926095887384, 11.946805681562672), Offset(41.99986395082928, 11.999888405015101), Offset(42.0, 12.0), ], ), _PathCubicTo( <Offset>[ Offset(8.38912164174901, 24.405077050766437), Offset(8.395184821848037, 24.09310118692493), Offset(8.459782153583708, 23.007417876572518), Offset(8.787794358833729, 20.871982437428983), Offset(9.907414129760891, 17.4624092987335), Offset(13.082563535366404, 12.659581303110395), Offset(17.494014200747685, 9.171905574648836), Offset(22.5870000408063, 7.175387672861925), Offset(27.221252362148654, 6.6195238529014375), Offset(30.937448027657968, 6.914992133489694), Offset(33.83674155554175, 7.597074418012536), Offset(36.08060605872299, 8.412374916582504), Offset(37.809259485732085, 9.226949916571378), Offset(39.13181277597566, 9.970719038360135), Offset(40.13100060158848, 10.608666338979862), Offset(40.8691843334897, 11.125641311887346), Offset(41.393512389333864, 11.518117486505904), Offset(41.739705833610245, 11.789400976065625), Offset(41.934926095887384, 11.946805681562672), Offset(41.99986395082928, 11.999888405015101), Offset(42.0, 12.0), ], <Offset>[ Offset(24.001202429357242, 40.01712955410343), Offset(23.83222317150212, 40.00256247026114), Offset(23.23942779221921, 39.946462972862705), Offset(22.038927761654776, 39.80749463199581), Offset(19.949366049060785, 39.46949330483639), Offset(16.264533064857485, 38.458226989829164), Offset(12.33449316951288, 36.51059025564959), Offset(8.578444412844032, 33.28342724070369), Offset(5.937018065629374, 29.37981581518558), Offset(4.53033280905737, 25.617304074310752), Offset(3.9904123841692254, 22.340379629344262), Offset(3.9709303684047867, 19.632987511686302), Offset(4.225875830253855, 17.46428687392474), Offset(4.596953757909873, 15.765821909939516), Offset(4.987566744407481, 14.464537288015299), Offset(5.341580851799733, 13.495123299390182), Offset(5.628792713051272, 12.803177773286812), Offset(5.835431930410859, 12.34503603231178), Offset(5.958105322437522, 12.08630157554827), Offset(5.999911883913924, 12.000180457641243), Offset(6.0, 12.0), ], <Offset>[ Offset(24.001202429357242, 40.01712955410343), Offset(23.83222317150212, 40.00256247026114), Offset(23.23942779221921, 39.946462972862705), Offset(22.038927761654776, 39.80749463199581), Offset(19.949366049060785, 39.46949330483639), Offset(16.264533064857485, 38.458226989829164), Offset(12.33449316951288, 36.51059025564959), Offset(8.578444412844032, 33.28342724070369), Offset(5.937018065629374, 29.37981581518558), Offset(4.53033280905737, 25.617304074310752), Offset(3.9904123841692254, 22.340379629344262), Offset(3.9709303684047867, 19.632987511686302), Offset(4.225875830253855, 17.46428687392474), Offset(4.596953757909873, 15.765821909939516), Offset(4.987566744407481, 14.464537288015299), Offset(5.341580851799733, 13.495123299390182), Offset(5.628792713051272, 12.803177773286812), Offset(5.835431930410859, 12.34503603231178), Offset(5.958105322437522, 12.08630157554827), Offset(5.999911883913924, 12.000180457641243), Offset(6.0, 12.0), ], ), _PathCubicTo( <Offset>[ Offset(24.001202429357242, 40.01712955410343), Offset(23.83222317150212, 40.00256247026114), Offset(23.23942779221921, 39.946462972862705), Offset(22.038927761654776, 39.80749463199581), Offset(19.949366049060785, 39.46949330483639), Offset(16.264533064857485, 38.458226989829164), Offset(12.33449316951288, 36.51059025564959), Offset(8.578444412844032, 33.28342724070369), Offset(5.937018065629374, 29.37981581518558), Offset(4.53033280905737, 25.617304074310752), Offset(3.9904123841692254, 22.340379629344262), Offset(3.9709303684047867, 19.632987511686302), Offset(4.225875830253855, 17.46428687392474), Offset(4.596953757909873, 15.765821909939516), Offset(4.987566744407481, 14.464537288015299), Offset(5.341580851799733, 13.495123299390182), Offset(5.628792713051272, 12.803177773286812), Offset(5.835431930410859, 12.34503603231178), Offset(5.958105322437522, 12.08630157554827), Offset(5.999911883913924, 12.000180457641243), Offset(6.0, 12.0), ], <Offset>[ Offset(26.829629554103434, 37.188702429357235), Offset(26.70295401712204, 37.21708146835027), Offset(26.253437940457104, 37.31668297706097), Offset(25.316159296509255, 37.51407939114749), Offset(23.588416071597663, 37.80897683895165), Offset(20.234451203252327, 37.9685842890323), Offset(16.265106286835728, 37.25239920809595), Offset(12.10312127594884, 35.1746313573166), Offset(8.858593681675742, 32.111920483700914), Offset(6.842177615689938, 28.881561047964333), Offset(5.761956468124708, 25.926691322240227), Offset(5.290469810431201, 23.40907221160189), Offset(5.178751382636996, 21.349132840198116), Offset(5.258916359304976, 19.710667345993283), Offset(5.423821188616003, 18.440676377623248), Offset(5.607765949538116, 17.48625665894383), Offset(5.772423819137188, 16.80059820468561), Offset(5.897326348355019, 16.34455713877282), Offset(5.973614735709873, 16.086271507697752), Offset(5.9999443342489265, 16.000180457509614), Offset(6.0, 16.0), ], <Offset>[ Offset(26.829629554103434, 37.188702429357235), Offset(26.70295401712204, 37.21708146835027), Offset(26.253437940457104, 37.31668297706097), Offset(25.316159296509255, 37.51407939114749), Offset(23.588416071597663, 37.80897683895165), Offset(20.234451203252327, 37.9685842890323), Offset(16.265106286835728, 37.25239920809595), Offset(12.10312127594884, 35.1746313573166), Offset(8.858593681675742, 32.111920483700914), Offset(6.842177615689938, 28.881561047964333), Offset(5.761956468124708, 25.926691322240227), Offset(5.290469810431201, 23.40907221160189), Offset(5.178751382636996, 21.349132840198116), Offset(5.258916359304976, 19.710667345993283), Offset(5.423821188616003, 18.440676377623248), Offset(5.607765949538116, 17.48625665894383), Offset(5.772423819137188, 16.80059820468561), Offset(5.897326348355019, 16.34455713877282), Offset(5.973614735709873, 16.086271507697752), Offset(5.9999443342489265, 16.000180457509614), Offset(6.0, 16.0), ], ), _PathClose( ), ], ), ], matchTextDirection: true, );
flutter/packages/flutter/lib/src/material/animated_icons/data/arrow_menu.g.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/animated_icons/data/arrow_menu.g.dart", "repo_id": "flutter", "token_count": 29422 }
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 'dart:math' as math; import 'dart:ui' show lerpDouble; import 'package:flutter/animation.dart'; import 'package:flutter/foundation.dart'; // How close the begin and end points must be to an axis to be considered // vertical or horizontal. const double _kOnAxisDelta = 2.0; /// A [Tween] that interpolates an [Offset] along a circular arc. /// /// This class specializes the interpolation of [Tween<Offset>] so that instead /// of a straight line, the intermediate points follow the arc of a circle in a /// manner consistent with Material Design principles. /// /// The arc's radius is related to the bounding box that contains the [begin] /// and [end] points. If the bounding box is taller than it is wide, then the /// center of the circle will be horizontally aligned with the end point. /// Otherwise the center of the circle will be aligned with the begin point. /// The arc's sweep is always less than or equal to 90 degrees. /// /// See also: /// /// * [Tween], for a discussion on how to use interpolation objects. /// * [MaterialRectArcTween], which extends this concept to interpolating [Rect]s. class MaterialPointArcTween extends Tween<Offset> { /// Creates a [Tween] for animating [Offset]s along a circular arc. /// /// The [begin] and [end] properties must be non-null before the tween is /// first used, but the arguments can be null if the values are going to be /// filled in later. MaterialPointArcTween({ super.begin, super.end, }); bool _dirty = true; void _initialize() { assert(this.begin != null); assert(this.end != null); final Offset begin = this.begin!; final Offset end = this.end!; // An explanation with a diagram can be found at https://goo.gl/vMSdRg final Offset delta = end - begin; final double deltaX = delta.dx.abs(); final double deltaY = delta.dy.abs(); final double distanceFromAtoB = delta.distance; final Offset c = Offset(end.dx, begin.dy); double sweepAngle() => 2.0 * math.asin(distanceFromAtoB / (2.0 * _radius!)); if (deltaX > _kOnAxisDelta && deltaY > _kOnAxisDelta) { if (deltaX < deltaY) { _radius = distanceFromAtoB * distanceFromAtoB / (c - begin).distance / 2.0; _center = Offset(end.dx + _radius! * (begin.dx - end.dx).sign, end.dy); if (begin.dx < end.dx) { _beginAngle = sweepAngle() * (begin.dy - end.dy).sign; _endAngle = 0.0; } else { _beginAngle = math.pi + sweepAngle() * (end.dy - begin.dy).sign; _endAngle = math.pi; } } else { _radius = distanceFromAtoB * distanceFromAtoB / (c - end).distance / 2.0; _center = Offset(begin.dx, begin.dy + (end.dy - begin.dy).sign * _radius!); if (begin.dy < end.dy) { _beginAngle = -math.pi / 2.0; _endAngle = _beginAngle! + sweepAngle() * (end.dx - begin.dx).sign; } else { _beginAngle = math.pi / 2.0; _endAngle = _beginAngle! + sweepAngle() * (begin.dx - end.dx).sign; } } assert(_beginAngle != null); assert(_endAngle != null); } else { _beginAngle = null; _endAngle = null; } _dirty = false; } /// The center of the circular arc, null if [begin] and [end] are horizontally or /// vertically aligned, or if either is null. Offset? get center { if (begin == null || end == null) { return null; } if (_dirty) { _initialize(); } return _center; } Offset? _center; /// The radius of the circular arc, null if [begin] and [end] are horizontally or /// vertically aligned, or if either is null. double? get radius { if (begin == null || end == null) { return null; } if (_dirty) { _initialize(); } return _radius; } double? _radius; /// The beginning of the arc's sweep in radians, measured from the positive x /// axis. Positive angles turn clockwise. /// /// This will be null if [begin] and [end] are horizontally or vertically /// aligned, or if either is null. double? get beginAngle { if (begin == null || end == null) { return null; } if (_dirty) { _initialize(); } return _beginAngle; } double? _beginAngle; /// The end of the arc's sweep in radians, measured from the positive x axis. /// Positive angles turn clockwise. /// /// This will be null if [begin] and [end] are horizontally or vertically /// aligned, or if either is null. double? get endAngle { if (begin == null || end == null) { return null; } if (_dirty) { _initialize(); } return _beginAngle; } double? _endAngle; @override set begin(Offset? value) { if (value != begin) { super.begin = value; _dirty = true; } } @override set end(Offset? value) { if (value != end) { super.end = value; _dirty = true; } } @override Offset lerp(double t) { if (_dirty) { _initialize(); } if (t == 0.0) { return begin!; } if (t == 1.0) { return end!; } if (_beginAngle == null || _endAngle == null) { return Offset.lerp(begin, end, t)!; } final double angle = lerpDouble(_beginAngle, _endAngle, t)!; final double x = math.cos(angle) * _radius!; final double y = math.sin(angle) * _radius!; return _center! + Offset(x, y); } @override String toString() { return '${objectRuntimeType(this, 'MaterialPointArcTween')}($begin \u2192 $end; center=$center, radius=$radius, beginAngle=$beginAngle, endAngle=$endAngle)'; } } enum _CornerId { topLeft, topRight, bottomLeft, bottomRight } class _Diagonal { const _Diagonal(this.beginId, this.endId); final _CornerId beginId; final _CornerId endId; } const List<_Diagonal> _allDiagonals = <_Diagonal>[ _Diagonal(_CornerId.topLeft, _CornerId.bottomRight), _Diagonal(_CornerId.bottomRight, _CornerId.topLeft), _Diagonal(_CornerId.topRight, _CornerId.bottomLeft), _Diagonal(_CornerId.bottomLeft, _CornerId.topRight), ]; typedef _KeyFunc<T> = double Function(T input); // Select the element for which the key function returns the maximum value. T _maxBy<T>(Iterable<T> input, _KeyFunc<T> keyFunc) { late T maxValue; double? maxKey; for (final T value in input) { final double key = keyFunc(value); if (maxKey == null || key > maxKey) { maxValue = value; maxKey = key; } } return maxValue; } /// A [Tween] that interpolates a [Rect] by having its opposite corners follow /// circular arcs. /// /// This class specializes the interpolation of [Tween<Rect>] so that instead of /// growing or shrinking linearly, opposite corners of the rectangle follow arcs /// in a manner consistent with Material Design principles. /// /// Specifically, the rectangle corners whose diagonals are closest to the overall /// direction of the animation follow arcs defined with [MaterialPointArcTween]. /// /// See also: /// /// * [MaterialRectCenterArcTween], which interpolates a rect along a circular /// arc between the begin and end [Rect]'s centers. /// * [Tween], for a discussion on how to use interpolation objects. /// * [MaterialPointArcTween], the analog for [Offset] interpolation. /// * [RectTween], which does a linear rectangle interpolation. /// * [Hero.createRectTween], which can be used to specify the tween that defines /// a hero's path. class MaterialRectArcTween extends RectTween { /// Creates a [Tween] for animating [Rect]s along a circular arc. /// /// The [begin] and [end] properties must be non-null before the tween is /// first used, but the arguments can be null if the values are going to be /// filled in later. MaterialRectArcTween({ super.begin, super.end, }); bool _dirty = true; void _initialize() { assert(begin != null); assert(end != null); final Offset centersVector = end!.center - begin!.center; final _Diagonal diagonal = _maxBy<_Diagonal>(_allDiagonals, (_Diagonal d) => _diagonalSupport(centersVector, d)); _beginArc = MaterialPointArcTween( begin: _cornerFor(begin!, diagonal.beginId), end: _cornerFor(end!, diagonal.beginId), ); _endArc = MaterialPointArcTween( begin: _cornerFor(begin!, diagonal.endId), end: _cornerFor(end!, diagonal.endId), ); _dirty = false; } double _diagonalSupport(Offset centersVector, _Diagonal diagonal) { final Offset delta = _cornerFor(begin!, diagonal.endId) - _cornerFor(begin!, diagonal.beginId); final double length = delta.distance; return centersVector.dx * delta.dx / length + centersVector.dy * delta.dy / length; } Offset _cornerFor(Rect rect, _CornerId id) { return switch (id) { _CornerId.topLeft => rect.topLeft, _CornerId.topRight => rect.topRight, _CornerId.bottomLeft => rect.bottomLeft, _CornerId.bottomRight => rect.bottomRight, }; } /// The path of the corresponding [begin], [end] rectangle corners that lead /// the animation. MaterialPointArcTween? get beginArc { if (begin == null) { return null; } if (_dirty) { _initialize(); } return _beginArc; } late MaterialPointArcTween _beginArc; /// The path of the corresponding [begin], [end] rectangle corners that trail /// the animation. MaterialPointArcTween? get endArc { if (end == null) { return null; } if (_dirty) { _initialize(); } return _endArc; } late MaterialPointArcTween _endArc; @override set begin(Rect? value) { if (value != begin) { super.begin = value; _dirty = true; } } @override set end(Rect? value) { if (value != end) { super.end = value; _dirty = true; } } @override Rect lerp(double t) { if (_dirty) { _initialize(); } if (t == 0.0) { return begin!; } if (t == 1.0) { return end!; } return Rect.fromPoints(_beginArc.lerp(t), _endArc.lerp(t)); } @override String toString() { return '${objectRuntimeType(this, 'MaterialRectArcTween')}($begin \u2192 $end; beginArc=$beginArc, endArc=$endArc)'; } } /// A [Tween] that interpolates a [Rect] by moving it along a circular arc from /// [begin]'s [Rect.center] to [end]'s [Rect.center] while interpolating the /// rectangle's width and height. /// /// The arc that defines that center of the interpolated rectangle as it morphs /// from [begin] to [end] is a [MaterialPointArcTween]. /// /// See also: /// /// * [MaterialRectArcTween], A [Tween] that interpolates a [Rect] by having /// its opposite corners follow circular arcs. /// * [Tween], for a discussion on how to use interpolation objects. /// * [MaterialPointArcTween], the analog for [Offset] interpolation. /// * [RectTween], which does a linear rectangle interpolation. /// * [Hero.createRectTween], which can be used to specify the tween that defines /// a hero's path. class MaterialRectCenterArcTween extends RectTween { /// Creates a [Tween] for animating [Rect]s along a circular arc. /// /// The [begin] and [end] properties must be non-null before the tween is /// first used, but the arguments can be null if the values are going to be /// filled in later. MaterialRectCenterArcTween({ super.begin, super.end, }); bool _dirty = true; void _initialize() { assert(begin != null); assert(end != null); _centerArc = MaterialPointArcTween( begin: begin!.center, end: end!.center, ); _dirty = false; } /// If [begin] and [end] are non-null, returns a tween that interpolates along /// a circular arc between [begin]'s [Rect.center] and [end]'s [Rect.center]. MaterialPointArcTween? get centerArc { if (begin == null || end == null) { return null; } if (_dirty) { _initialize(); } return _centerArc; } late MaterialPointArcTween _centerArc; @override set begin(Rect? value) { if (value != begin) { super.begin = value; _dirty = true; } } @override set end(Rect? value) { if (value != end) { super.end = value; _dirty = true; } } @override Rect lerp(double t) { if (_dirty) { _initialize(); } if (t == 0.0) { return begin!; } if (t == 1.0) { return end!; } final Offset center = _centerArc.lerp(t); final double width = lerpDouble(begin!.width, end!.width, t)!; final double height = lerpDouble(begin!.height, end!.height, t)!; return Rect.fromLTWH(center.dx - width / 2.0, center.dy - height / 2.0, width, height); } @override String toString() { return '${objectRuntimeType(this, 'MaterialRectCenterArcTween')}($begin \u2192 $end; centerArc=$centerArc)'; } }
flutter/packages/flutter/lib/src/material/arc.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/arc.dart", "repo_id": "flutter", "token_count": 4765 }
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 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'ink_well.dart'; import 'material_state.dart'; import 'theme_data.dart'; // Examples can assume: // late BuildContext context; // typedef MyAppHome = Placeholder; /// The type for [ButtonStyle.backgroundBuilder] and [ButtonStyle.foregroundBuilder]. /// /// The [states] parameter is the button's current pressed/hovered/etc state. The [child] is /// typically a descendant of the returned widget. typedef ButtonLayerBuilder = Widget Function(BuildContext context, Set<MaterialState> states, Widget? child); /// The visual properties that most buttons have in common. /// /// Buttons and their themes have a ButtonStyle property which defines the visual /// properties whose default values are to be overridden. The default values are /// defined by the individual button widgets and are typically based on overall /// theme's [ThemeData.colorScheme] and [ThemeData.textTheme]. /// /// All of the ButtonStyle properties are null by default. /// /// Many of the ButtonStyle properties are [MaterialStateProperty] objects which /// resolve to different values depending on the button's state. For example /// the [Color] properties are defined with `MaterialStateProperty<Color>` and /// can resolve to different colors depending on if the button is pressed, /// hovered, focused, disabled, etc. /// /// These properties can override the default value for just one state or all of /// them. For example to create a [ElevatedButton] whose background color is the /// color scheme’s primary color with 50% opacity, but only when the button is /// pressed, one could write: /// /// ```dart /// ElevatedButton( /// style: ButtonStyle( /// backgroundColor: MaterialStateProperty.resolveWith<Color?>( /// (Set<MaterialState> states) { /// if (states.contains(MaterialState.pressed)) { /// return Theme.of(context).colorScheme.primary.withOpacity(0.5); /// } /// return null; // Use the component's default. /// }, /// ), /// ), /// child: const Text('Fly me to the moon'), /// onPressed: () { /// // ... /// }, /// ), /// ``` /// /// In this case the background color for all other button states would fallback /// to the ElevatedButton’s default values. To unconditionally set the button's /// [backgroundColor] for all states one could write: /// /// ```dart /// ElevatedButton( /// style: const ButtonStyle( /// backgroundColor: MaterialStatePropertyAll<Color>(Colors.green), /// ), /// child: const Text('Let me play among the stars'), /// onPressed: () { /// // ... /// }, /// ), /// ``` /// /// Configuring a ButtonStyle directly makes it possible to very /// precisely control the button’s visual attributes for all states. /// This level of control is typically required when a custom /// “branded” look and feel is desirable. However, in many cases it’s /// useful to make relatively sweeping changes based on a few initial /// parameters with simple values. The button styleFrom() methods /// enable such sweeping changes. See for example: /// [ElevatedButton.styleFrom], [FilledButton.styleFrom], /// [OutlinedButton.styleFrom], [TextButton.styleFrom]. /// /// For example, to override the default text and icon colors for a /// [TextButton], as well as its overlay color, with all of the /// standard opacity adjustments for the pressed, focused, and /// hovered states, one could write: /// /// ```dart /// TextButton( /// style: TextButton.styleFrom(foregroundColor: Colors.green), /// child: const Text('Let me see what spring is like'), /// onPressed: () { /// // ... /// }, /// ), /// ``` /// /// To configure all of the application's text buttons in the same /// way, specify the overall theme's `textButtonTheme`: /// /// ```dart /// MaterialApp( /// theme: ThemeData( /// textButtonTheme: TextButtonThemeData( /// style: TextButton.styleFrom(foregroundColor: Colors.green), /// ), /// ), /// home: const MyAppHome(), /// ), /// ``` /// /// ## Material 3 button types /// /// Material Design 3 specifies five types of common buttons. Flutter provides /// support for these using the following button classes: /// <style>table,td,th { border-collapse: collapse; padding: 0.45em; } td { border: 1px solid }</style> /// /// | Type | Flutter implementation | /// | :----------- | :---------------------- | /// | Elevated | [ElevatedButton] | /// | Filled | [FilledButton] | /// | Filled Tonal | [FilledButton.tonal] | /// | Outlined | [OutlinedButton] | /// | Text | [TextButton] | /// /// {@tool dartpad} /// This sample shows how to create each of the Material 3 button types with Flutter. /// /// ** See code in examples/api/lib/material/button_style/button_style.0.dart ** /// {@end-tool} /// /// See also: /// /// * [ElevatedButtonTheme], the theme for [ElevatedButton]s. /// * [FilledButtonTheme], the theme for [FilledButton]s. /// * [OutlinedButtonTheme], the theme for [OutlinedButton]s. /// * [TextButtonTheme], the theme for [TextButton]s. @immutable class ButtonStyle with Diagnosticable { /// Create a [ButtonStyle]. const ButtonStyle({ this.textStyle, this.backgroundColor, this.foregroundColor, this.overlayColor, this.shadowColor, this.surfaceTintColor, this.elevation, this.padding, this.minimumSize, this.fixedSize, this.maximumSize, this.iconColor, this.iconSize, this.side, this.shape, this.mouseCursor, this.visualDensity, this.tapTargetSize, this.animationDuration, this.enableFeedback, this.alignment, this.splashFactory, this.backgroundBuilder, this.foregroundBuilder, }); /// The style for a button's [Text] widget descendants. /// /// The color of the [textStyle] is typically not used directly, the /// [foregroundColor] is used instead. final MaterialStateProperty<TextStyle?>? textStyle; /// The button's background fill color. final MaterialStateProperty<Color?>? backgroundColor; /// The color for the button's [Text] and [Icon] widget descendants. /// /// This color is typically used instead of the color of the [textStyle]. All /// of the components that compute defaults from [ButtonStyle] values /// compute a default [foregroundColor] and use that instead of the /// [textStyle]'s color. final MaterialStateProperty<Color?>? foregroundColor; /// The highlight color that's typically used to indicate that /// the button is focused, hovered, or pressed. final MaterialStateProperty<Color?>? overlayColor; /// The shadow color of the button's [Material]. /// /// The material's elevation shadow can be difficult to see for /// dark themes, so by default the button classes add a /// semi-transparent overlay to indicate elevation. See /// [ThemeData.applyElevationOverlayColor]. final MaterialStateProperty<Color?>? shadowColor; /// The surface tint color of the button's [Material]. /// /// See [Material.surfaceTintColor] for more details. final MaterialStateProperty<Color?>? surfaceTintColor; /// The elevation of the button's [Material]. final MaterialStateProperty<double?>? elevation; /// The padding between the button's boundary and its child. final MaterialStateProperty<EdgeInsetsGeometry?>? padding; /// The minimum size of the button itself. /// /// The size of the rectangle the button lies within may be larger /// per [tapTargetSize]. /// /// This value must be less than or equal to [maximumSize]. final MaterialStateProperty<Size?>? minimumSize; /// The button's size. /// /// This size is still constrained by the style's [minimumSize] /// and [maximumSize]. Fixed size dimensions whose value is /// [double.infinity] are ignored. /// /// To specify buttons with a fixed width and the default height use /// `fixedSize: Size.fromWidth(320)`. Similarly, to specify a fixed /// height and the default width use `fixedSize: Size.fromHeight(100)`. final MaterialStateProperty<Size?>? fixedSize; /// The maximum size of the button itself. /// /// A [Size.infinite] or null value for this property means that /// the button's maximum size is not constrained. /// /// This value must be greater than or equal to [minimumSize]. final MaterialStateProperty<Size?>? maximumSize; /// The icon's color inside of the button. /// /// If this is null, the icon color will be [foregroundColor]. final MaterialStateProperty<Color?>? iconColor; /// The icon's size inside of the button. final MaterialStateProperty<double?>? iconSize; /// The color and weight of the button's outline. /// /// This value is combined with [shape] to create a shape decorated /// with an outline. final MaterialStateProperty<BorderSide?>? side; /// The shape of the button's underlying [Material]. /// /// This shape is combined with [side] to create a shape decorated /// with an outline. final MaterialStateProperty<OutlinedBorder?>? shape; /// The cursor for a mouse pointer when it enters or is hovering over /// this button's [InkWell]. final MaterialStateProperty<MouseCursor?>? mouseCursor; /// 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; /// Configures the minimum size of the area within which the button may be pressed. /// /// If the [tapTargetSize] is larger than [minimumSize], the button will include /// a transparent margin that responds to taps. /// /// Always defaults to [ThemeData.materialTapTargetSize]. final MaterialTapTargetSize? tapTargetSize; /// Defines the duration of animated changes for [shape] and [elevation]. /// /// Typically the component default value is [kThemeChangeDuration]. final Duration? animationDuration; /// 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. /// /// Typically the component default value is true. /// /// See also: /// /// * [Feedback] for providing platform-specific feedback to certain actions. final bool? enableFeedback; /// 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; /// Creates the [InkWell] splash factory, which defines the appearance of /// "ink" splashes that occur in response to taps. /// /// Use [NoSplash.splashFactory] to defeat ink splash rendering. For example: /// ```dart /// ElevatedButton( /// style: ElevatedButton.styleFrom( /// splashFactory: NoSplash.splashFactory, /// ), /// onPressed: () { }, /// child: const Text('No Splash'), /// ) /// ``` final InteractiveInkFeatureFactory? splashFactory; /// Creates a widget that becomes the child of the button's [Material] /// and whose child is the rest of the button, including the button's /// `child` parameter. /// /// The widget created by [backgroundBuilder] is constrained to be /// the same size as the overall button and will appear behind the /// button's child. The widget created by [foregroundBuilder] is /// constrained to be the same size as the button's child, i.e. it's /// inset by [ButtonStyle.padding] and aligned by the button's /// [ButtonStyle.alignment]. /// /// By default the returned widget is clipped to the Material's [ButtonStyle.shape]. /// /// See also: /// /// * [foregroundBuilder], to create a widget that's as big as the button's /// child and is layered behind the child. /// * [ButtonStyleButton.clipBehavior], for more information about /// configuring clipping. final ButtonLayerBuilder? backgroundBuilder; /// Creates a Widget that contains the button's child parameter which is used /// instead of the button's child. /// /// The returned widget is clipped by the button's /// [ButtonStyle.shape], inset by the button's [ButtonStyle.padding] /// and aligned by the button's [ButtonStyle.alignment]. /// /// See also: /// /// * [backgroundBuilder], to create a widget that's as big as the button and /// is layered behind the button's child. /// * [ButtonStyleButton.clipBehavior], for more information about /// configuring clipping. final ButtonLayerBuilder? foregroundBuilder; /// Returns a copy of this ButtonStyle with the given fields replaced with /// the new values. ButtonStyle copyWith({ MaterialStateProperty<TextStyle?>? textStyle, MaterialStateProperty<Color?>? backgroundColor, MaterialStateProperty<Color?>? foregroundColor, MaterialStateProperty<Color?>? overlayColor, MaterialStateProperty<Color?>? shadowColor, MaterialStateProperty<Color?>? surfaceTintColor, MaterialStateProperty<double?>? elevation, MaterialStateProperty<EdgeInsetsGeometry?>? padding, MaterialStateProperty<Size?>? minimumSize, MaterialStateProperty<Size?>? fixedSize, MaterialStateProperty<Size?>? maximumSize, MaterialStateProperty<Color?>? iconColor, MaterialStateProperty<double?>? iconSize, MaterialStateProperty<BorderSide?>? side, MaterialStateProperty<OutlinedBorder?>? shape, MaterialStateProperty<MouseCursor?>? mouseCursor, VisualDensity? visualDensity, MaterialTapTargetSize? tapTargetSize, Duration? animationDuration, bool? enableFeedback, AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, ButtonLayerBuilder? backgroundBuilder, ButtonLayerBuilder? foregroundBuilder, }) { return ButtonStyle( textStyle: textStyle ?? this.textStyle, backgroundColor: backgroundColor ?? this.backgroundColor, foregroundColor: foregroundColor ?? this.foregroundColor, overlayColor: overlayColor ?? this.overlayColor, shadowColor: shadowColor ?? this.shadowColor, surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor, elevation: elevation ?? this.elevation, padding: padding ?? this.padding, minimumSize: minimumSize ?? this.minimumSize, fixedSize: fixedSize ?? this.fixedSize, maximumSize: maximumSize ?? this.maximumSize, iconColor: iconColor ?? this.iconColor, iconSize: iconSize ?? this.iconSize, side: side ?? this.side, shape: shape ?? this.shape, mouseCursor: mouseCursor ?? this.mouseCursor, visualDensity: visualDensity ?? this.visualDensity, tapTargetSize: tapTargetSize ?? this.tapTargetSize, animationDuration: animationDuration ?? this.animationDuration, enableFeedback: enableFeedback ?? this.enableFeedback, alignment: alignment ?? this.alignment, splashFactory: splashFactory ?? this.splashFactory, backgroundBuilder: backgroundBuilder ?? this.backgroundBuilder, foregroundBuilder: foregroundBuilder ?? this.foregroundBuilder, ); } /// Returns a copy of this ButtonStyle where the non-null fields in [style] /// have replaced the corresponding null fields in this ButtonStyle. /// /// In other words, [style] is used to fill in unspecified (null) fields /// this ButtonStyle. ButtonStyle merge(ButtonStyle? style) { if (style == null) { return this; } return copyWith( textStyle: textStyle ?? style.textStyle, backgroundColor: backgroundColor ?? style.backgroundColor, foregroundColor: foregroundColor ?? style.foregroundColor, overlayColor: overlayColor ?? style.overlayColor, shadowColor: shadowColor ?? style.shadowColor, surfaceTintColor: surfaceTintColor ?? style.surfaceTintColor, elevation: elevation ?? style.elevation, padding: padding ?? style.padding, minimumSize: minimumSize ?? style.minimumSize, fixedSize: fixedSize ?? style.fixedSize, maximumSize: maximumSize ?? style.maximumSize, iconColor: iconColor ?? style.iconColor, iconSize: iconSize ?? style.iconSize, side: side ?? style.side, shape: shape ?? style.shape, mouseCursor: mouseCursor ?? style.mouseCursor, visualDensity: visualDensity ?? style.visualDensity, tapTargetSize: tapTargetSize ?? style.tapTargetSize, animationDuration: animationDuration ?? style.animationDuration, enableFeedback: enableFeedback ?? style.enableFeedback, alignment: alignment ?? style.alignment, splashFactory: splashFactory ?? style.splashFactory, backgroundBuilder: backgroundBuilder ?? style.backgroundBuilder, foregroundBuilder: foregroundBuilder ?? style.foregroundBuilder, ); } @override int get hashCode { final List<Object?> values = <Object?>[ textStyle, backgroundColor, foregroundColor, overlayColor, shadowColor, surfaceTintColor, elevation, padding, minimumSize, fixedSize, maximumSize, iconColor, iconSize, side, shape, mouseCursor, visualDensity, tapTargetSize, animationDuration, enableFeedback, alignment, splashFactory, backgroundBuilder, foregroundBuilder, ]; return Object.hashAll(values); } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is ButtonStyle && other.textStyle == textStyle && other.backgroundColor == backgroundColor && other.foregroundColor == foregroundColor && other.overlayColor == overlayColor && other.shadowColor == shadowColor && other.surfaceTintColor == surfaceTintColor && other.elevation == elevation && other.padding == padding && other.minimumSize == minimumSize && other.fixedSize == fixedSize && other.maximumSize == maximumSize && other.iconColor == iconColor && other.iconSize == iconSize && other.side == side && other.shape == shape && other.mouseCursor == mouseCursor && other.visualDensity == visualDensity && other.tapTargetSize == tapTargetSize && other.animationDuration == animationDuration && other.enableFeedback == enableFeedback && other.alignment == alignment && other.splashFactory == splashFactory && other.backgroundBuilder == backgroundBuilder && other.foregroundBuilder == foregroundBuilder; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<MaterialStateProperty<TextStyle?>>('textStyle', textStyle, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('backgroundColor', backgroundColor, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('foregroundColor', foregroundColor, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('overlayColor', overlayColor, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('shadowColor', shadowColor, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<double?>>('elevation', elevation, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<EdgeInsetsGeometry?>>('padding', padding, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Size?>>('minimumSize', minimumSize, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Size?>>('fixedSize', fixedSize, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Size?>>('maximumSize', maximumSize, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('iconColor', iconColor, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<double?>>('iconSize', iconSize, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<BorderSide?>>('side', side, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<OutlinedBorder?>>('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<MouseCursor?>>('mouseCursor', mouseCursor, defaultValue: null)); properties.add(DiagnosticsProperty<VisualDensity>('visualDensity', visualDensity, defaultValue: null)); properties.add(EnumProperty<MaterialTapTargetSize>('tapTargetSize', tapTargetSize, defaultValue: null)); properties.add(DiagnosticsProperty<Duration>('animationDuration', animationDuration, defaultValue: null)); properties.add(DiagnosticsProperty<bool>('enableFeedback', enableFeedback, defaultValue: null)); properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: null)); properties.add(DiagnosticsProperty<ButtonLayerBuilder>('backgroundBuilder', backgroundBuilder, defaultValue: null)); properties.add(DiagnosticsProperty<ButtonLayerBuilder>('foregroundBuilder', foregroundBuilder, defaultValue: null)); } /// Linearly interpolate between two [ButtonStyle]s. static ButtonStyle? lerp(ButtonStyle? a, ButtonStyle? b, double t) { if (identical(a, b)) { return a; } return ButtonStyle( textStyle: MaterialStateProperty.lerp<TextStyle?>(a?.textStyle, b?.textStyle, t, TextStyle.lerp), backgroundColor: MaterialStateProperty.lerp<Color?>(a?.backgroundColor, b?.backgroundColor, t, Color.lerp), foregroundColor: MaterialStateProperty.lerp<Color?>(a?.foregroundColor, b?.foregroundColor, t, Color.lerp), overlayColor: MaterialStateProperty.lerp<Color?>(a?.overlayColor, b?.overlayColor, t, Color.lerp), shadowColor: MaterialStateProperty.lerp<Color?>(a?.shadowColor, b?.shadowColor, t, Color.lerp), surfaceTintColor: MaterialStateProperty.lerp<Color?>(a?.surfaceTintColor, b?.surfaceTintColor, t, Color.lerp), elevation: MaterialStateProperty.lerp<double?>(a?.elevation, b?.elevation, t, lerpDouble), padding: MaterialStateProperty.lerp<EdgeInsetsGeometry?>(a?.padding, b?.padding, t, EdgeInsetsGeometry.lerp), minimumSize: MaterialStateProperty.lerp<Size?>(a?.minimumSize, b?.minimumSize, t, Size.lerp), fixedSize: MaterialStateProperty.lerp<Size?>(a?.fixedSize, b?.fixedSize, t, Size.lerp), maximumSize: MaterialStateProperty.lerp<Size?>(a?.maximumSize, b?.maximumSize, t, Size.lerp), iconColor: MaterialStateProperty.lerp<Color?>(a?.iconColor, b?.iconColor, t, Color.lerp), iconSize: MaterialStateProperty.lerp<double?>(a?.iconSize, b?.iconSize, t, lerpDouble), side: _lerpSides(a?.side, b?.side, t), shape: MaterialStateProperty.lerp<OutlinedBorder?>(a?.shape, b?.shape, t, OutlinedBorder.lerp), mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity, tapTargetSize: t < 0.5 ? a?.tapTargetSize : b?.tapTargetSize, animationDuration: t < 0.5 ? a?.animationDuration : b?.animationDuration, enableFeedback: t < 0.5 ? a?.enableFeedback : b?.enableFeedback, alignment: AlignmentGeometry.lerp(a?.alignment, b?.alignment, t), splashFactory: t < 0.5 ? a?.splashFactory : b?.splashFactory, backgroundBuilder: t < 0.5 ? a?.backgroundBuilder : b?.backgroundBuilder, foregroundBuilder: t < 0.5 ? a?.foregroundBuilder : b?.foregroundBuilder, ); } // Special case because BorderSide.lerp() doesn't support null arguments static MaterialStateProperty<BorderSide?>? _lerpSides(MaterialStateProperty<BorderSide?>? a, MaterialStateProperty<BorderSide?>? b, double t) { if (a == null && b == null) { return null; } return _LerpSides(a, b, t); } } class _LerpSides implements MaterialStateProperty<BorderSide?> { const _LerpSides(this.a, this.b, this.t); final MaterialStateProperty<BorderSide?>? a; final MaterialStateProperty<BorderSide?>? b; final double t; @override BorderSide? resolve(Set<MaterialState> states) { final BorderSide? resolvedA = a?.resolve(states); final BorderSide? resolvedB = b?.resolve(states); if (resolvedA == null && resolvedB == null) { return null; } if (resolvedA == null) { return BorderSide.lerp(BorderSide(width: 0, color: resolvedB!.color.withAlpha(0)), resolvedB, t); } if (resolvedB == null) { return BorderSide.lerp(resolvedA, BorderSide(width: 0, color: resolvedA.color.withAlpha(0)), t); } return BorderSide.lerp(resolvedA, resolvedB, t); } }
flutter/packages/flutter/lib/src/material/button_style.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/button_style.dart", "repo_id": "flutter", "token_count": 7994 }
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/animation.dart'; // The easing curves of the Material Library /// The standard easing curve in the Material 2 specification. /// /// Elements that begin and end at rest use standard easing. /// They speed up quickly and slow down gradually, in order /// to emphasize the end of the transition. /// /// See also: /// * <https://material.io/design/motion/speed.html#easing> @Deprecated( 'Use Easing.legacy (M2) or Easing.standard (M3) instead. ' 'This curve is updated in M3. ' 'This feature was deprecated after v3.18.0-0.1.pre.' ) const Curve standardEasing = Curves.fastOutSlowIn; /// The accelerate easing curve in the Material 2 specification. /// /// Elements exiting a screen use acceleration easing, /// where they start at rest and end at peak velocity. /// /// See also: /// * <https://material.io/design/motion/speed.html#easing> @Deprecated( 'Use Easing.legacyAccelerate (M2) or Easing.standardAccelerate (M3) instead. ' 'This curve is updated in M3. ' 'This feature was deprecated after v3.18.0-0.1.pre.' ) const Curve accelerateEasing = Cubic(0.4, 0.0, 1.0, 1.0); /// The decelerate easing curve in the Material 2 specification. /// /// Incoming elements are animated using deceleration easing, /// which starts a transition at peak velocity (the fastest /// point of an element’s movement) and ends at rest. /// /// See also: /// * <https://material.io/design/motion/speed.html#easing> @Deprecated( 'Use Easing.legacyDecelerate (M2) or Easing.standardDecelerate (M3) instead. ' 'This curve is updated in M3. ' 'This feature was deprecated after v3.18.0-0.1.pre.' ) const Curve decelerateEasing = Cubic(0.0, 0.0, 0.2, 1.0);
flutter/packages/flutter/lib/src/material/curves.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/curves.dart", "repo_id": "flutter", "token_count": 573 }
672
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'debug.dart'; import 'divider.dart'; import 'theme.dart'; const double _kDrawerHeaderHeight = 160.0 + 1.0; // bottom edge /// The top-most region of a Material Design drawer. The header's [child] /// widget, if any, is placed inside a [Container] whose [decoration] can be /// passed as an argument, inset by the given [padding]. /// /// Part of the Material Design [Drawer]. /// /// Requires one of its ancestors to be a [Material] widget. This condition is /// satisfied by putting the [DrawerHeader] in a [Drawer]. /// /// See also: /// /// * [UserAccountsDrawerHeader], a variant of [DrawerHeader] that is /// specialized for showing user accounts. /// * <https://material.io/design/components/navigation-drawer.html> class DrawerHeader extends StatelessWidget { /// Creates a Material Design drawer header. /// /// Requires one of its ancestors to be a [Material] widget. const DrawerHeader({ super.key, this.decoration, this.margin = const EdgeInsets.only(bottom: 8.0), this.padding = const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 8.0), this.duration = const Duration(milliseconds: 250), this.curve = Curves.fastOutSlowIn, required this.child, }); /// Decoration for the main drawer header [Container]; useful for applying /// backgrounds. /// /// This decoration will extend under the system status bar. /// /// If this is changed, it will be animated according to [duration] and [curve]. final Decoration? decoration; /// The padding by which to inset [child]. /// /// The [DrawerHeader] additionally offsets the child by the height of the /// system status bar. /// /// If the child is null, the padding has no effect. final EdgeInsetsGeometry padding; /// The margin around the drawer header. final EdgeInsetsGeometry? margin; /// The duration for animations of the [decoration]. final Duration duration; /// The curve for animations of the [decoration]. final Curve curve; /// A widget to be placed inside the drawer header, inset by the [padding]. /// /// This widget will be sized to the size of the header. To position the child /// precisely, consider using an [Align] or [Center] widget. /// /// {@macro flutter.widgets.ProxyWidget.child} final Widget? child; @override Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); assert(debugCheckHasMediaQuery(context)); final ThemeData theme = Theme.of(context); final double statusBarHeight = MediaQuery.paddingOf(context).top; return Container( height: statusBarHeight + _kDrawerHeaderHeight, margin: margin, decoration: BoxDecoration( border: Border( bottom: Divider.createBorderSide(context), ), ), child: AnimatedContainer( padding: padding.add(EdgeInsets.only(top: statusBarHeight)), decoration: decoration, duration: duration, curve: curve, child: child == null ? null : DefaultTextStyle( style: theme.textTheme.bodyLarge!, child: MediaQuery.removePadding( context: context, removeTop: true, child: child!, ), ), ), ); } }
flutter/packages/flutter/lib/src/material/drawer_header.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/drawer_header.dart", "repo_id": "flutter", "token_count": 1121 }
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 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/foundation.dart' show clampDouble; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; import 'constants.dart'; import 'theme.dart'; /// The collapsing effect while the space bar collapses from its full size. enum CollapseMode { /// The background widget will scroll in a parallax fashion. parallax, /// The background widget pin in place until it reaches the min extent. pin, /// The background widget will act as normal with no collapsing effect. none, } /// The stretching effect while the space bar stretches beyond its full size. enum StretchMode { /// The background widget will expand to fill the extra space. zoomBackground, /// The background will blur using a [ImageFilter.blur] effect. blurBackground, /// The title will fade away as the user over-scrolls. fadeTitle, } /// The part of a Material Design [AppBar] that expands, collapses, and /// stretches. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=mSc7qFzxHDw} /// /// Most commonly used in the [SliverAppBar.flexibleSpace] field, a flexible /// space bar expands and contracts as the app scrolls so that the [AppBar] /// reaches from the top of the app to the top of the scrolling contents of the /// app. When using [SliverAppBar.flexibleSpace], the [SliverAppBar.expandedHeight] /// must be large enough to accommodate the [SliverAppBar.flexibleSpace] widget. /// /// Furthermore is included functionality for stretch behavior. When /// [SliverAppBar.stretch] is true, and your [ScrollPhysics] allow for /// overscroll, this space will stretch with the overscroll. /// /// The widget that sizes the [AppBar] must wrap it in the widget returned by /// [FlexibleSpaceBar.createSettings], to convey sizing information down to the /// [FlexibleSpaceBar]. /// /// {@tool dartpad} /// This sample application demonstrates the different features of the /// [FlexibleSpaceBar] when used in a [SliverAppBar]. This app bar is configured /// to stretch into the overscroll space, and uses the /// [FlexibleSpaceBar.stretchModes] to apply `fadeTitle`, `blurBackground` and /// `zoomBackground`. The app bar also makes use of [CollapseMode.parallax] by /// default. /// /// ** See code in examples/api/lib/material/flexible_space_bar/flexible_space_bar.0.dart ** /// {@end-tool} /// /// See also: /// /// * [SliverAppBar], which implements the expanding and contracting. /// * [AppBar], which is used by [SliverAppBar]. /// * <https://material.io/design/components/app-bars-top.html#behavior> class FlexibleSpaceBar extends StatefulWidget { /// Creates a flexible space bar. /// /// Most commonly used in the [AppBar.flexibleSpace] field. const FlexibleSpaceBar({ super.key, this.title, this.background, this.centerTitle, this.titlePadding, this.collapseMode = CollapseMode.parallax, this.stretchModes = const <StretchMode>[StretchMode.zoomBackground], this.expandedTitleScale = 1.5, }) : assert(expandedTitleScale >= 1); /// The primary contents of the flexible space bar when expanded. /// /// Typically a [Text] widget. final Widget? title; /// Shown behind the [title] when expanded. /// /// Typically an [Image] widget with [Image.fit] set to [BoxFit.cover]. final Widget? background; /// Whether the title should be centered. /// /// If the length of the title is greater than the available space, set /// this property to false. This aligns the title to the start of the /// flexible space bar and applies [titlePadding] to the title. /// /// By default this property is true if the current target platform /// is [TargetPlatform.iOS] or [TargetPlatform.macOS], false otherwise. final bool? centerTitle; /// Collapse effect while scrolling. /// /// Defaults to [CollapseMode.parallax]. final CollapseMode collapseMode; /// Stretch effect while over-scrolling. /// /// Defaults to include [StretchMode.zoomBackground]. final List<StretchMode> stretchModes; /// Defines how far the [title] is inset from either the widget's /// bottom-left or its center. /// /// Typically this property is used to adjust how far the title is /// inset from the bottom-left and it is specified along with /// [centerTitle] false. /// /// If [centerTitle] is true, then the title is centered within the /// flexible space bar with a bottom padding of 16.0 pixels. /// /// If [centerTitle] is false and [FlexibleSpaceBarSettings.hasLeading] is true, /// then the title is aligned to the start of the flexible space bar with the /// [titlePadding] applied. If [titlePadding] is null, then defaults to start /// padding of 72.0 pixels and bottom padding of 16.0 pixels. final EdgeInsetsGeometry? titlePadding; /// Defines how much the title is scaled when the FlexibleSpaceBar is expanded /// due to the user scrolling downwards. The title is scaled uniformly on the /// x and y axes while maintaining its bottom-left position (bottom-center if /// [centerTitle] is true). /// /// Defaults to 1.5 and must be greater than 1. final double expandedTitleScale; /// Wraps a widget that contains an [AppBar] to convey sizing information down /// to the [FlexibleSpaceBar]. /// /// Used by [Scaffold] and [SliverAppBar]. /// /// `toolbarOpacity` affects how transparent the text within the toolbar /// appears. `minExtent` sets the minimum height of the resulting /// [FlexibleSpaceBar] when fully collapsed. `maxExtent` sets the maximum /// height of the resulting [FlexibleSpaceBar] when fully expanded. /// `currentExtent` sets the scale of the [FlexibleSpaceBar.background] and /// [FlexibleSpaceBar.title] widgets of [FlexibleSpaceBar] upon /// initialization. `scrolledUnder` is true if the [FlexibleSpaceBar] /// overlaps the app's primary scrollable, false if it does not, and null /// if the caller has not determined as much. /// See also: /// /// * [FlexibleSpaceBarSettings] which creates a settings object that can be /// used to specify these settings to a [FlexibleSpaceBar]. static Widget createSettings({ double? toolbarOpacity, double? minExtent, double? maxExtent, bool? isScrolledUnder, bool? hasLeading, required double currentExtent, required Widget child, }) { return FlexibleSpaceBarSettings( toolbarOpacity: toolbarOpacity ?? 1.0, minExtent: minExtent ?? currentExtent, maxExtent: maxExtent ?? currentExtent, isScrolledUnder: isScrolledUnder, hasLeading: hasLeading, currentExtent: currentExtent, child: child, ); } @override State<FlexibleSpaceBar> createState() => _FlexibleSpaceBarState(); } class _FlexibleSpaceBarState extends State<FlexibleSpaceBar> { bool _getEffectiveCenterTitle(ThemeData theme) { return widget.centerTitle ?? switch (theme.platform) { TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.linux || TargetPlatform.windows => false, TargetPlatform.iOS || TargetPlatform.macOS => true, }; } Alignment _getTitleAlignment(bool effectiveCenterTitle) { if (effectiveCenterTitle) { return Alignment.bottomCenter; } return switch (Directionality.of(context)) { TextDirection.rtl => Alignment.bottomRight, TextDirection.ltr => Alignment.bottomLeft, }; } double _getCollapsePadding(double t, FlexibleSpaceBarSettings settings) { switch (widget.collapseMode) { case CollapseMode.pin: return -(settings.maxExtent - settings.currentExtent); case CollapseMode.none: return 0.0; case CollapseMode.parallax: final double deltaExtent = settings.maxExtent - settings.minExtent; return -Tween<double>(begin: 0.0, end: deltaExtent / 4.0).transform(t); } } @override Widget build(BuildContext context) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { final FlexibleSpaceBarSettings settings = context.dependOnInheritedWidgetOfExactType<FlexibleSpaceBarSettings>()!; final List<Widget> children = <Widget>[]; final double deltaExtent = settings.maxExtent - settings.minExtent; // 0.0 -> Expanded // 1.0 -> Collapsed to toolbar final double t = clampDouble(1.0 - (settings.currentExtent - settings.minExtent) / deltaExtent, 0.0, 1.0); // background if (widget.background != null) { final double fadeStart = math.max(0.0, 1.0 - kToolbarHeight / deltaExtent); const double fadeEnd = 1.0; assert(fadeStart <= fadeEnd); // If the min and max extent are the same, the app bar cannot collapse // and the content should be visible, so opacity = 1. final double opacity = settings.maxExtent == settings.minExtent ? 1.0 : 1.0 - Interval(fadeStart, fadeEnd).transform(t); double height = settings.maxExtent; // StretchMode.zoomBackground if (widget.stretchModes.contains(StretchMode.zoomBackground) && constraints.maxHeight > height) { height = constraints.maxHeight; } final double topPadding = _getCollapsePadding(t, settings); children.add(Positioned( top: topPadding, left: 0.0, right: 0.0, height: height, child: _FlexibleSpaceHeaderOpacity( // IOS is relying on this semantics node to correctly traverse // through the app bar when it is collapsed. alwaysIncludeSemantics: true, opacity: opacity, child: widget.background ), )); // StretchMode.blurBackground if (widget.stretchModes.contains(StretchMode.blurBackground) && constraints.maxHeight > settings.maxExtent) { final double blurAmount = (constraints.maxHeight - settings.maxExtent) / 10; children.add(Positioned.fill( child: BackdropFilter( filter: ui.ImageFilter.blur( sigmaX: blurAmount, sigmaY: blurAmount, ), child: Container( color: Colors.transparent, ), ), )); } } // title if (widget.title != null) { final ThemeData theme = Theme.of(context); Widget? title; switch (theme.platform) { case TargetPlatform.iOS: case TargetPlatform.macOS: title = widget.title; case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: title = Semantics( namesRoute: true, child: widget.title, ); } // StretchMode.fadeTitle if (widget.stretchModes.contains(StretchMode.fadeTitle) && constraints.maxHeight > settings.maxExtent) { final double stretchOpacity = 1 - clampDouble( (constraints.maxHeight - settings.maxExtent) / 100, 0.0, 1.0); title = Opacity( opacity: stretchOpacity, child: title, ); } final double opacity = settings.toolbarOpacity; if (opacity > 0.0) { TextStyle titleStyle = theme.useMaterial3 ? theme.textTheme.titleLarge! : theme.primaryTextTheme.titleLarge!; titleStyle = titleStyle.copyWith( color: titleStyle.color!.withOpacity(opacity), ); final bool effectiveCenterTitle = _getEffectiveCenterTitle(theme); final double leadingPadding = (settings.hasLeading ?? true) ? 72.0 : 0.0; final EdgeInsetsGeometry padding = widget.titlePadding ?? EdgeInsetsDirectional.only( start: effectiveCenterTitle ? 0.0 : leadingPadding, bottom: 16.0, ); final double scaleValue = Tween<double>(begin: widget.expandedTitleScale, end: 1.0).transform(t); final Matrix4 scaleTransform = Matrix4.identity() ..scale(scaleValue, scaleValue, 1.0); final Alignment titleAlignment = _getTitleAlignment(effectiveCenterTitle); children.add(Container( padding: padding, child: Transform( alignment: titleAlignment, transform: scaleTransform, child: Align( alignment: titleAlignment, child: DefaultTextStyle( style: titleStyle, child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Container( width: constraints.maxWidth / scaleValue, alignment: titleAlignment, child: title, ); }, ), ), ), ), )); } } return ClipRect(child: Stack(children: children)); }, ); } } /// Provides sizing and opacity information to a [FlexibleSpaceBar]. /// /// See also: /// /// * [FlexibleSpaceBar] which creates a flexible space bar. class FlexibleSpaceBarSettings extends InheritedWidget { /// Creates a Flexible Space Bar Settings widget. /// /// Used by [Scaffold] and [SliverAppBar]. [child] must have a /// [FlexibleSpaceBar] widget in its tree for the settings to take affect. const FlexibleSpaceBarSettings({ super.key, required this.toolbarOpacity, required this.minExtent, required this.maxExtent, required this.currentExtent, required super.child, this.isScrolledUnder, this.hasLeading, }) : assert(minExtent >= 0), assert(maxExtent >= 0), assert(currentExtent >= 0), assert(toolbarOpacity >= 0.0), assert(minExtent <= maxExtent), assert(minExtent <= currentExtent), assert(currentExtent <= maxExtent); /// Affects how transparent the text within the toolbar appears. final double toolbarOpacity; /// Minimum height of the resulting [FlexibleSpaceBar] when fully collapsed. final double minExtent; /// Maximum height of the resulting [FlexibleSpaceBar] when fully expanded. final double maxExtent; /// If the [FlexibleSpaceBar.title] or the [FlexibleSpaceBar.background] is /// not null, then this value is used to calculate the relative scale of /// these elements upon initialization. final double currentExtent; /// True if the FlexibleSpaceBar overlaps the primary scrollable's contents. /// /// This value is used by the [AppBar] to resolve /// [AppBar.backgroundColor] against [MaterialState.scrolledUnder], /// i.e. to enable apps to specify different colors when content /// has been scrolled up and behind the app bar. /// /// Null if the caller hasn't determined if the FlexibleSpaceBar /// overlaps the primary scrollable's contents. final bool? isScrolledUnder; /// True if the FlexibleSpaceBar has a leading widget. /// /// This value is used by the [FlexibleSpaceBar] to determine /// if there should be a gap between the leading widget and /// the title. /// /// Null if the caller hasn't determined if the FlexibleSpaceBar /// has a leading widget. final bool? hasLeading; @override bool updateShouldNotify(FlexibleSpaceBarSettings oldWidget) { return toolbarOpacity != oldWidget.toolbarOpacity || minExtent != oldWidget.minExtent || maxExtent != oldWidget.maxExtent || currentExtent != oldWidget.currentExtent || isScrolledUnder != oldWidget.isScrolledUnder || hasLeading != oldWidget.hasLeading; } } // We need the child widget to repaint, however both the opacity // and potentially `widget.background` can be constant which won't // lead to repainting. // see: https://github.com/flutter/flutter/issues/127836 class _FlexibleSpaceHeaderOpacity extends SingleChildRenderObjectWidget { const _FlexibleSpaceHeaderOpacity({required this.opacity, required super.child, required this.alwaysIncludeSemantics}); final double opacity; final bool alwaysIncludeSemantics; @override RenderObject createRenderObject(BuildContext context) { return _RenderFlexibleSpaceHeaderOpacity(opacity: opacity, alwaysIncludeSemantics: alwaysIncludeSemantics); } @override void updateRenderObject(BuildContext context, covariant _RenderFlexibleSpaceHeaderOpacity renderObject) { renderObject ..alwaysIncludeSemantics = alwaysIncludeSemantics ..opacity = opacity; } } class _RenderFlexibleSpaceHeaderOpacity extends RenderOpacity { _RenderFlexibleSpaceHeaderOpacity({super.opacity, super.alwaysIncludeSemantics}); @override bool get isRepaintBoundary => false; @override void paint(PaintingContext context, Offset offset) { if (child == null) { return; } if ((opacity * 255).roundToDouble() <= 0) { layer = null; return; } assert(needsCompositing); layer = context.pushOpacity(offset, (opacity * 255).round(), super.paint, oldLayer: layer as OpacityLayer?); assert(() { layer!.debugCreator = debugCreator; return true; }()); } }
flutter/packages/flutter/lib/src/material/flexible_space_bar.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/flexible_space_bar.dart", "repo_id": "flutter", "token_count": 6489 }
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 'dart:math' as math; import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart' show clampDouble; import 'package:flutter/widgets.dart'; /// Defines the appearance of an [InputDecorator]'s border. /// /// An input decorator's border is specified by [InputDecoration.border]. /// /// The border is drawn relative to the input decorator's "container" which /// is the optionally filled area above the decorator's helper, error, /// and counter. /// /// Input border's are decorated with a line whose weight and color are defined /// by [borderSide]. The input decorator's renderer animates the input border's /// appearance in response to state changes, like gaining or losing the focus, /// by creating new copies of its input border with [copyWith]. /// /// See also: /// /// * [UnderlineInputBorder], the default [InputDecorator] border which /// draws a horizontal line at the bottom of the input decorator's container. /// * [OutlineInputBorder], an [InputDecorator] border which draws a /// rounded rectangle around the input decorator's container. /// * [InputDecoration], which is used to configure an [InputDecorator]. abstract class InputBorder extends ShapeBorder { /// Creates a border for an [InputDecorator]. /// /// Applications typically do not specify a [borderSide] parameter because the /// [InputDecorator] substitutes its own, using [copyWith], based on the /// current theme and [InputDecorator.isFocused]. const InputBorder({ this.borderSide = BorderSide.none, }); /// No input border. /// /// Use this value with [InputDecoration.border] to specify that no border /// should be drawn. The [InputDecoration.collapsed] constructor sets /// its border to this value. static const InputBorder none = _NoInputBorder(); /// Defines the border line's color and weight. /// /// The [InputDecorator] creates copies of its input border, using [copyWith], /// based on the current theme and [InputDecorator.isFocused]. final BorderSide borderSide; /// Creates a copy of this input border with the specified `borderSide`. InputBorder copyWith({ BorderSide? borderSide }); /// True if this border will enclose the [InputDecorator]'s container. /// /// This property affects the alignment of container's contents. For example /// when an input decorator is configured with an [OutlineInputBorder] its /// label is centered with its container. bool get isOutline; /// Paint this input border on [canvas]. /// /// The [rect] parameter bounds the [InputDecorator]'s container. /// /// The additional `gap` parameters reflect the state of the [InputDecorator]'s /// floating label. When an input decorator gains the focus, its label /// animates upwards, to make room for the input child. The [gapStart] and /// [gapExtent] parameters define a floating label width interval, and /// [gapPercentage] defines the animation's progress (0.0 to 1.0). @override void paint( Canvas canvas, Rect rect, { double? gapStart, double gapExtent = 0.0, double gapPercentage = 0.0, TextDirection? textDirection, }); } // Used to create the InputBorder.none singleton. class _NoInputBorder extends InputBorder { const _NoInputBorder() : super(borderSide: BorderSide.none); @override _NoInputBorder copyWith({ BorderSide? borderSide }) => const _NoInputBorder(); @override bool get isOutline => false; @override EdgeInsetsGeometry get dimensions => EdgeInsets.zero; @override _NoInputBorder scale(double t) => const _NoInputBorder(); @override Path getInnerPath(Rect rect, { TextDirection? textDirection }) { return Path()..addRect(rect); } @override Path getOuterPath(Rect rect, { TextDirection? textDirection }) { return Path()..addRect(rect); } @override void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { canvas.drawRect(rect, paint); } @override bool get preferPaintInterior => true; @override void paint( Canvas canvas, Rect rect, { double? gapStart, double gapExtent = 0.0, double gapPercentage = 0.0, TextDirection? textDirection, }) { // Do not paint. } } /// Draws a horizontal line at the bottom of an [InputDecorator]'s container and /// defines the container's shape. /// /// The input decorator's "container" is the optionally filled area above the /// decorator's helper, error, and counter. /// /// See also: /// /// * [OutlineInputBorder], an [InputDecorator] border which draws a /// rounded rectangle around the input decorator's container. /// * [InputDecoration], which is used to configure an [InputDecorator]. class UnderlineInputBorder extends InputBorder { /// Creates an underline border for an [InputDecorator]. /// /// The [borderSide] parameter defaults to [BorderSide.none] (it must not be /// null). Applications typically do not specify a [borderSide] parameter /// because the input decorator substitutes its own, using [copyWith], based /// on the current theme and [InputDecorator.isFocused]. /// /// The [borderRadius] parameter defaults to a value where the top left /// and right corners have a circular radius of 4.0. const UnderlineInputBorder({ super.borderSide = const BorderSide(), this.borderRadius = const BorderRadius.only( topLeft: Radius.circular(4.0), topRight: Radius.circular(4.0), ), }); /// The radii of the border's rounded rectangle corners. /// /// When this border is used with a filled input decorator, see /// [InputDecoration.filled], the border radius defines the shape /// of the background fill as well as the bottom left and right /// edges of the underline itself. /// /// By default the top right and top left corners have a circular radius /// of 4.0. final BorderRadius borderRadius; @override bool get isOutline => false; @override UnderlineInputBorder copyWith({ BorderSide? borderSide, BorderRadius? borderRadius }) { return UnderlineInputBorder( borderSide: borderSide ?? this.borderSide, borderRadius: borderRadius ?? this.borderRadius, ); } @override EdgeInsetsGeometry get dimensions { return EdgeInsets.only(bottom: borderSide.width); } @override UnderlineInputBorder scale(double t) { return UnderlineInputBorder(borderSide: borderSide.scale(t)); } @override Path getInnerPath(Rect rect, { TextDirection? textDirection }) { return Path() ..addRect(Rect.fromLTWH(rect.left, rect.top, rect.width, math.max(0.0, rect.height - borderSide.width))); } @override Path getOuterPath(Rect rect, { TextDirection? textDirection }) { return Path()..addRRect(borderRadius.resolve(textDirection).toRRect(rect)); } @override void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { canvas.drawRRect(borderRadius.resolve(textDirection).toRRect(rect), paint); } @override bool get preferPaintInterior => true; @override ShapeBorder? lerpFrom(ShapeBorder? a, double t) { if (a is UnderlineInputBorder) { return UnderlineInputBorder( borderSide: BorderSide.lerp(a.borderSide, borderSide, t), borderRadius: BorderRadius.lerp(a.borderRadius, borderRadius, t)!, ); } return super.lerpFrom(a, t); } @override ShapeBorder? lerpTo(ShapeBorder? b, double t) { if (b is UnderlineInputBorder) { return UnderlineInputBorder( borderSide: BorderSide.lerp(borderSide, b.borderSide, t), borderRadius: BorderRadius.lerp(borderRadius, b.borderRadius, t)!, ); } return super.lerpTo(b, t); } /// Draw a horizontal line at the bottom of [rect]. /// /// The [borderSide] defines the line's color and weight. The `textDirection` /// `gap` and `textDirection` parameters are ignored. @override void paint( Canvas canvas, Rect rect, { double? gapStart, double gapExtent = 0.0, double gapPercentage = 0.0, TextDirection? textDirection, }) { if (borderRadius.bottomLeft != Radius.zero || borderRadius.bottomRight != Radius.zero) { // This prevents the border from leaking the color due to anti-aliasing rounding errors. final BorderRadius updatedBorderRadius = BorderRadius.only( bottomLeft: borderRadius.bottomLeft.clamp(maximum: Radius.circular(rect.height / 2)), bottomRight: borderRadius.bottomRight.clamp(maximum: Radius.circular(rect.height / 2)), ); // We set the strokeAlign to center, so the behavior is consistent with // drawLine and with the historical behavior of this border. BoxBorder.paintNonUniformBorder(canvas, rect, textDirection: textDirection, borderRadius: updatedBorderRadius, bottom: borderSide.copyWith(strokeAlign: BorderSide.strokeAlignCenter), color: borderSide.color); } else { canvas.drawLine(rect.bottomLeft, rect.bottomRight, borderSide.toPaint()); } } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is UnderlineInputBorder && other.borderSide == borderSide && other.borderRadius == borderRadius; } @override int get hashCode => Object.hash(borderSide, borderRadius); } /// Draws a rounded rectangle around an [InputDecorator]'s container. /// /// When the input decorator's label is floating, for example because its /// input child has the focus, the label appears in a gap in the border outline. /// /// The input decorator's "container" is the optionally filled area above the /// decorator's helper, error, and counter. /// /// See also: /// /// * [UnderlineInputBorder], the default [InputDecorator] border which /// draws a horizontal line at the bottom of the input decorator's container. /// * [InputDecoration], which is used to configure an [InputDecorator]. class OutlineInputBorder extends InputBorder { /// Creates a rounded rectangle outline border for an [InputDecorator]. /// /// If the [borderSide] parameter is [BorderSide.none], it will not draw a /// border. However, it will still define a shape (which you can see if /// [InputDecoration.filled] is true). /// /// If an application does not specify a [borderSide] parameter of /// value [BorderSide.none], the input decorator substitutes its own, using /// [copyWith], based on the current theme and [InputDecorator.isFocused]. /// /// The [borderRadius] parameter defaults to a value where all four corners /// have a circular radius of 4.0. The corner radii must be circular, i.e. /// their [Radius.x] and [Radius.y] values must be the same. /// /// See also: /// /// * [InputDecoration.floatingLabelBehavior], which should be set to /// [FloatingLabelBehavior.never] when the [borderSide] is /// [BorderSide.none]. If let as [FloatingLabelBehavior.auto], the label /// will extend beyond the container as if the border were still being /// drawn. const OutlineInputBorder({ super.borderSide = const BorderSide(), this.borderRadius = const BorderRadius.all(Radius.circular(4.0)), this.gapPadding = 4.0, }) : assert(gapPadding >= 0.0); // The label text's gap can extend into the corners (even both the top left // and the top right corner). To avoid the more complicated problem of finding // how far the gap penetrates into an elliptical corner, just require them // to be circular. // // This can't be checked by the constructor because const constructor. static bool _cornersAreCircular(BorderRadius borderRadius) { return borderRadius.topLeft.x == borderRadius.topLeft.y && borderRadius.bottomLeft.x == borderRadius.bottomLeft.y && borderRadius.topRight.x == borderRadius.topRight.y && borderRadius.bottomRight.x == borderRadius.bottomRight.y; } /// Horizontal padding on either side of the border's /// [InputDecoration.labelText] width gap. /// /// This value is used by the [paint] method to compute the actual gap width. final double gapPadding; /// The radii of the border's rounded rectangle corners. /// /// The corner radii must be circular, i.e. their [Radius.x] and [Radius.y] /// values must be the same. final BorderRadius borderRadius; @override bool get isOutline => true; @override OutlineInputBorder copyWith({ BorderSide? borderSide, BorderRadius? borderRadius, double? gapPadding, }) { return OutlineInputBorder( borderSide: borderSide ?? this.borderSide, borderRadius: borderRadius ?? this.borderRadius, gapPadding: gapPadding ?? this.gapPadding, ); } @override EdgeInsetsGeometry get dimensions { return EdgeInsets.all(borderSide.width); } @override OutlineInputBorder scale(double t) { return OutlineInputBorder( borderSide: borderSide.scale(t), borderRadius: borderRadius * t, gapPadding: gapPadding * t, ); } @override ShapeBorder? lerpFrom(ShapeBorder? a, double t) { if (a is OutlineInputBorder) { final OutlineInputBorder outline = a; return OutlineInputBorder( borderRadius: BorderRadius.lerp(outline.borderRadius, borderRadius, t)!, borderSide: BorderSide.lerp(outline.borderSide, borderSide, t), gapPadding: outline.gapPadding, ); } return super.lerpFrom(a, t); } @override ShapeBorder? lerpTo(ShapeBorder? b, double t) { if (b is OutlineInputBorder) { final OutlineInputBorder outline = b; return OutlineInputBorder( borderRadius: BorderRadius.lerp(borderRadius, outline.borderRadius, t)!, borderSide: BorderSide.lerp(borderSide, outline.borderSide, t), gapPadding: outline.gapPadding, ); } return super.lerpTo(b, t); } @override Path getInnerPath(Rect rect, { TextDirection? textDirection }) { return Path() ..addRRect(borderRadius.resolve(textDirection).toRRect(rect).deflate(borderSide.width)); } @override Path getOuterPath(Rect rect, { TextDirection? textDirection }) { return Path() ..addRRect(borderRadius.resolve(textDirection).toRRect(rect)); } @override void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { canvas.drawRRect(borderRadius.resolve(textDirection).toRRect(rect), paint); } @override bool get preferPaintInterior => true; Path _gapBorderPath(Canvas canvas, RRect center, double start, double extent) { // When the corner radii on any side add up to be greater than the // given height, each radius has to be scaled to not exceed the // size of the width/height of the RRect. final RRect scaledRRect = center.scaleRadii(); final Rect tlCorner = Rect.fromLTWH( scaledRRect.left, scaledRRect.top, scaledRRect.tlRadiusX * 2.0, scaledRRect.tlRadiusY * 2.0, ); final Rect trCorner = Rect.fromLTWH( scaledRRect.right - scaledRRect.trRadiusX * 2.0, scaledRRect.top, scaledRRect.trRadiusX * 2.0, scaledRRect.trRadiusY * 2.0, ); final Rect brCorner = Rect.fromLTWH( scaledRRect.right - scaledRRect.brRadiusX * 2.0, scaledRRect.bottom - scaledRRect.brRadiusY * 2.0, scaledRRect.brRadiusX * 2.0, scaledRRect.brRadiusY * 2.0, ); final Rect blCorner = Rect.fromLTWH( scaledRRect.left, scaledRRect.bottom - scaledRRect.blRadiusY * 2.0, scaledRRect.blRadiusX * 2.0, scaledRRect.blRadiusY * 2.0, ); // This assumes that the radius is circular (x and y radius are equal). // Currently, BorderRadius only supports circular radii. const double cornerArcSweep = math.pi / 2.0; final Path path = Path(); // Top left corner if (scaledRRect.tlRadius != Radius.zero) { final double tlCornerArcSweep = math.acos(clampDouble(1 - start / scaledRRect.tlRadiusX, 0.0, 1.0)); path.addArc(tlCorner, math.pi, tlCornerArcSweep); } else { // Because the path is painted with Paint.strokeCap = StrokeCap.butt, horizontal coordinate is moved // to the left using borderSide.width / 2. path.moveTo(scaledRRect.left - borderSide.width / 2, scaledRRect.top); } // Draw top border from top left corner to gap start. if (start > scaledRRect.tlRadiusX) { path.lineTo(scaledRRect.left + start, scaledRRect.top); } // Draw top border from gap end to top right corner and draw top right corner. const double trCornerArcStart = (3 * math.pi) / 2.0; const double trCornerArcSweep = cornerArcSweep; if (start + extent < scaledRRect.width - scaledRRect.trRadiusX) { path.moveTo(scaledRRect.left + start + extent, scaledRRect.top); path.lineTo(scaledRRect.right - scaledRRect.trRadiusX, scaledRRect.top); if (scaledRRect.trRadius != Radius.zero) { path.addArc(trCorner, trCornerArcStart, trCornerArcSweep); } } else if (start + extent < scaledRRect.width) { final double dx = scaledRRect.width - (start + extent); final double sweep = math.asin(clampDouble(1 - dx / scaledRRect.trRadiusX, 0.0, 1.0)); path.addArc(trCorner, trCornerArcStart + sweep, trCornerArcSweep - sweep); } // Draw right border and bottom right corner. if (scaledRRect.brRadius != Radius.zero) { path.moveTo(scaledRRect.right, scaledRRect.top + scaledRRect.trRadiusY); } path.lineTo(scaledRRect.right, scaledRRect.bottom - scaledRRect.brRadiusY); if (scaledRRect.brRadius != Radius.zero) { path.addArc(brCorner, 0.0, cornerArcSweep); } // Draw bottom border and bottom left corner. path.lineTo(scaledRRect.left + scaledRRect.blRadiusX, scaledRRect.bottom); if (scaledRRect.blRadius != Radius.zero) { path.addArc(blCorner, math.pi / 2.0, cornerArcSweep); } // Draw left border path.lineTo(scaledRRect.left, scaledRRect.top + scaledRRect.tlRadiusY); return path; } /// Draw a rounded rectangle around [rect] using [borderRadius]. /// /// The [borderSide] defines the line's color and weight. /// /// The top side of the rounded rectangle may be interrupted by a single gap /// if [gapExtent] is non-null. In that case the gap begins at /// `gapStart - gapPadding` (assuming that the [textDirection] is [TextDirection.ltr]). /// The gap's width is `(gapPadding + gapExtent + gapPadding) * gapPercentage`. @override void paint( Canvas canvas, Rect rect, { double? gapStart, double gapExtent = 0.0, double gapPercentage = 0.0, TextDirection? textDirection, }) { assert(gapPercentage >= 0.0 && gapPercentage <= 1.0); assert(_cornersAreCircular(borderRadius)); final Paint paint = borderSide.toPaint(); final RRect outer = borderRadius.toRRect(rect); final RRect center = outer.deflate(borderSide.width / 2.0); if (gapStart == null || gapExtent <= 0.0 || gapPercentage == 0.0) { canvas.drawRRect(center, paint); } else { final double extent = lerpDouble(0.0, gapExtent + gapPadding * 2.0, gapPercentage)!; switch (textDirection!) { case TextDirection.rtl: final Path path = _gapBorderPath(canvas, center, math.max(0.0, gapStart + gapPadding - extent), extent); canvas.drawPath(path, paint); case TextDirection.ltr: final Path path = _gapBorderPath(canvas, center, math.max(0.0, gapStart - gapPadding), extent); canvas.drawPath(path, paint); } } } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is OutlineInputBorder && other.borderSide == borderSide && other.borderRadius == borderRadius && other.gapPadding == gapPadding; } @override int get hashCode => Object.hash(borderSide, borderRadius, gapPadding); }
flutter/packages/flutter/lib/src/material/input_border.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/input_border.dart", "repo_id": "flutter", "token_count": 6890 }
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. import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'menu_anchor.dart'; import 'menu_style.dart'; import 'theme.dart'; // Examples can assume: // late Widget child; /// Defines the configuration of the submenus created by the [SubmenuButton], /// [MenuBar], or [MenuAnchor] widgets. /// /// Descendant widgets obtain the current [MenuThemeData] object using /// `MenuTheme.of(context)`. /// /// Typically, a [MenuThemeData] is specified as part of the overall [Theme] /// with [ThemeData.menuTheme]. Otherwise, [MenuTheme] can be used to configure /// its own widget subtree. /// /// All [MenuThemeData] properties are `null` by default. If any of these /// properties are null, the menu bar will provide its own defaults. /// /// See also: /// /// * [ThemeData], which describes the overall theme for the application. /// * [MenuBarThemeData], which describes the theme for the menu bar itself in a /// [MenuBar] widget. @immutable class MenuThemeData with Diagnosticable { /// Creates a const set of properties used to configure [MenuTheme]. const MenuThemeData({this.style}); /// The [MenuStyle] of a [SubmenuButton] menu. /// /// Any values not set in the [MenuStyle] will use the menu default for that /// property. final MenuStyle? style; /// Linearly interpolate between two menu button themes. static MenuThemeData? lerp(MenuThemeData? a, MenuThemeData? b, double t) { if (identical(a, b)) { return a; } return MenuThemeData(style: MenuStyle.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 MenuThemeData && other.style == style; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<MenuStyle>('style', style, defaultValue: null)); } } /// An inherited widget that defines the configuration in this widget's /// descendants for menus created by the [SubmenuButton], [MenuBar], or /// [MenuAnchor] widgets. /// /// Values specified here are used for [SubmenuButton]'s menu properties that /// are not given an explicit non-null value. /// /// See also: /// /// * [MenuThemeData], a configuration object that holds attributes of a menu /// used by this theme. /// * [MenuBarTheme], which does the same thing for the [MenuBar] widget. /// * [MenuBar], a widget that manages [MenuItemButton]s. /// * [MenuAnchor], a widget that creates a region that has a submenu. /// * [MenuItemButton], a widget that is a selectable item in a menu bar menu. /// * [SubmenuButton], a widget that specifies an item with a cascading submenu /// in a [MenuBar] menu. class MenuTheme extends InheritedTheme { /// Creates a const theme that controls the configurations for the menus /// created by the [SubmenuButton] or [MenuAnchor] widgets. const MenuTheme({ super.key, required this.data, required super.child, }); /// The properties for [MenuBar] and [MenuItemButton] in this widget's /// descendants. final MenuThemeData data; /// Returns the closest instance of this class's [data] value that encloses /// the given context. If there is no ancestor, it returns /// [ThemeData.menuTheme]. /// /// Typical usage is as follows: /// /// ```dart /// Widget build(BuildContext context) { /// return MenuTheme( /// data: const MenuThemeData( /// style: MenuStyle( /// backgroundColor: MaterialStatePropertyAll<Color>(Colors.red), /// ), /// ), /// child: child, /// ); /// } /// ``` static MenuThemeData of(BuildContext context) { final MenuTheme? menuTheme = context.dependOnInheritedWidgetOfExactType<MenuTheme>(); return menuTheme?.data ?? Theme.of(context).menuTheme; } @override Widget wrap(BuildContext context, Widget child) { return MenuTheme(data: data, child: child); } @override bool updateShouldNotify(MenuTheme oldWidget) => data != oldWidget.data; }
flutter/packages/flutter/lib/src/material/menu_theme.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/menu_theme.dart", "repo_id": "flutter", "token_count": 1339 }
676
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'material_state.dart'; import 'theme.dart'; // Examples can assume: // late BuildContext context; /// Used to configure how the [PopupMenuButton] positions its popup menu. enum PopupMenuPosition { /// Menu is positioned over the anchor. over, /// Menu is positioned under the anchor. under, } /// Defines the visual properties of the routes used to display popup menus /// as well as [PopupMenuItem] and [PopupMenuDivider] widgets. /// /// Descendant widgets obtain the current [PopupMenuThemeData] object /// using `PopupMenuTheme.of(context)`. Instances of /// [PopupMenuThemeData] can be customized with /// [PopupMenuThemeData.copyWith]. /// /// Typically, a [PopupMenuThemeData] is specified as part of the /// overall [Theme] with [ThemeData.popupMenuTheme]. Otherwise, /// [PopupMenuTheme] can be used to configure its own widget subtree. /// /// All [PopupMenuThemeData] properties are `null` by default. /// If any of these properties are null, the popup menu will provide its /// own defaults. /// /// See also: /// /// * [ThemeData], which describes the overall theme information for the /// application. @immutable class PopupMenuThemeData with Diagnosticable { /// Creates the set of properties used to configure [PopupMenuTheme]. const PopupMenuThemeData({ this.color, this.shape, this.elevation, this.shadowColor, this.surfaceTintColor, this.textStyle, this.labelTextStyle, this.enableFeedback, this.mouseCursor, this.position, this.iconColor, this.iconSize, }); /// The background color of the popup menu. final Color? color; /// The shape of the popup menu. final ShapeBorder? shape; /// The elevation of the popup menu. final double? elevation; /// The color used to paint shadow below the popup menu. final Color? shadowColor; /// The color used as an overlay on [color] of the popup menu. final Color? surfaceTintColor; /// The text style of items in the popup menu. final TextStyle? textStyle; /// You can use this to specify a different style of the label /// when the popup menu item is enabled and disabled. final MaterialStateProperty<TextStyle?>? labelTextStyle; /// If specified, defines the feedback property for [PopupMenuButton]. /// /// If [PopupMenuButton.enableFeedback] is provided, [enableFeedback] is ignored. final bool? enableFeedback; /// {@macro flutter.material.popupmenu.mouseCursor} /// /// If specified, overrides the default value of [PopupMenuItem.mouseCursor]. final MaterialStateProperty<MouseCursor?>? mouseCursor; /// Whether the popup menu is positioned over or under the popup menu button. /// /// When not set, the position defaults to [PopupMenuPosition.over] which makes the /// popup menu appear directly over the button that was used to create it. final PopupMenuPosition? position; /// The color of the icon in the popup menu button. final Color? iconColor; /// The size of the icon in the popup menu button. final double? iconSize; /// Creates a copy of this object with the given fields replaced with the /// new values. PopupMenuThemeData copyWith({ Color? color, ShapeBorder? shape, double? elevation, Color? shadowColor, Color? surfaceTintColor, TextStyle? textStyle, MaterialStateProperty<TextStyle?>? labelTextStyle, bool? enableFeedback, MaterialStateProperty<MouseCursor?>? mouseCursor, PopupMenuPosition? position, Color? iconColor, double? iconSize, }) { return PopupMenuThemeData( color: color ?? this.color, shape: shape ?? this.shape, elevation: elevation ?? this.elevation, shadowColor: shadowColor ?? this.shadowColor, surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor, textStyle: textStyle ?? this.textStyle, labelTextStyle: labelTextStyle ?? this.labelTextStyle, enableFeedback: enableFeedback ?? this.enableFeedback, mouseCursor: mouseCursor ?? this.mouseCursor, position: position ?? this.position, iconColor: iconColor ?? this.iconColor, iconSize: iconSize ?? this.iconSize, ); } /// Linearly interpolate between two popup menu themes. /// /// If both arguments are null, then null is returned. /// /// {@macro dart.ui.shadow.lerp} static PopupMenuThemeData? lerp(PopupMenuThemeData? a, PopupMenuThemeData? b, double t) { if (identical(a, b)) { return a; } return PopupMenuThemeData( color: Color.lerp(a?.color, b?.color, t), shape: ShapeBorder.lerp(a?.shape, b?.shape, t), elevation: lerpDouble(a?.elevation, b?.elevation, t), shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t), surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t), textStyle: TextStyle.lerp(a?.textStyle, b?.textStyle, t), labelTextStyle: MaterialStateProperty.lerp<TextStyle?>(a?.labelTextStyle, b?.labelTextStyle, t, TextStyle.lerp), enableFeedback: t < 0.5 ? a?.enableFeedback : b?.enableFeedback, mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, position: t < 0.5 ? a?.position : b?.position, iconColor: Color.lerp(a?.iconColor, b?.iconColor, t), iconSize: lerpDouble(a?.iconSize, b?.iconSize, t), ); } @override int get hashCode => Object.hash( color, shape, elevation, shadowColor, surfaceTintColor, textStyle, labelTextStyle, enableFeedback, mouseCursor, position, iconColor, iconSize, ); @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is PopupMenuThemeData && other.color == color && other.shape == shape && other.elevation == elevation && other.shadowColor == shadowColor && other.surfaceTintColor == surfaceTintColor && other.textStyle == textStyle && other.labelTextStyle == labelTextStyle && other.enableFeedback == enableFeedback && other.mouseCursor == mouseCursor && other.position == position && other.iconColor == iconColor && other.iconSize == iconSize; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(ColorProperty('color', color, defaultValue: null)); properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null)); properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(DiagnosticsProperty<TextStyle>('text style', textStyle, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<TextStyle?>>('labelTextStyle', labelTextStyle, defaultValue: null)); properties.add(DiagnosticsProperty<bool>('enableFeedback', enableFeedback, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<MouseCursor?>>('mouseCursor', mouseCursor, defaultValue: null)); properties.add(EnumProperty<PopupMenuPosition?>('position', position, defaultValue: null)); properties.add(ColorProperty('iconColor', iconColor, defaultValue: null)); properties.add(DoubleProperty('iconSize', iconSize, defaultValue: null)); } } /// An inherited widget that defines the configuration for /// popup menus in this widget's subtree. /// /// Values specified here are used for popup menu properties that are not /// given an explicit non-null value. class PopupMenuTheme extends InheritedTheme { /// Creates a popup menu theme that controls the configurations for /// popup menus in its widget subtree. const PopupMenuTheme({ super.key, required this.data, required super.child, }); /// The properties for descendant popup menu widgets. final PopupMenuThemeData data; /// The closest instance of this class's [data] value that encloses the given /// context. If there is no ancestor, it returns [ThemeData.popupMenuTheme]. /// Applications can assume that the returned value will not be null. /// /// Typical usage is as follows: /// /// ```dart /// PopupMenuThemeData theme = PopupMenuTheme.of(context); /// ``` static PopupMenuThemeData of(BuildContext context) { final PopupMenuTheme? popupMenuTheme = context.dependOnInheritedWidgetOfExactType<PopupMenuTheme>(); return popupMenuTheme?.data ?? Theme.of(context).popupMenuTheme; } @override Widget wrap(BuildContext context, Widget child) { return PopupMenuTheme(data: data, child: child); } @override bool updateShouldNotify(PopupMenuTheme oldWidget) => data != oldWidget.data; }
flutter/packages/flutter/lib/src/material/popup_menu_theme.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/popup_menu_theme.dart", "repo_id": "flutter", "token_count": 2966 }
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:math' as math; import 'dart:math'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'button_style.dart'; import 'button_style_button.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'constants.dart'; import 'icons.dart'; import 'ink_well.dart'; import 'material.dart'; import 'material_state.dart'; import 'segmented_button_theme.dart'; import 'text_button.dart'; import 'text_button_theme.dart'; import 'theme.dart'; import 'theme_data.dart'; import 'tooltip.dart'; /// Data describing a segment of a [SegmentedButton]. class ButtonSegment<T> { /// Construct a [ButtonSegment]. /// /// One of [icon] or [label] must be non-null. const ButtonSegment({ required this.value, this.icon, this.label, this.tooltip, this.enabled = true, }) : assert(icon != null || label != null); /// Value used to identify the segment. /// /// This value must be unique across all segments in a [SegmentedButton]. final T value; /// Optional icon displayed in the segment. final Widget? icon; /// Optional label displayed in the segment. final Widget? label; /// Optional tooltip for the segment final String? tooltip; /// Determines if the segment is available for selection. final bool enabled; } /// A Material button that allows the user to select from limited set of options. /// /// Segmented buttons are used to help people select options, switch views, or /// sort elements. They are typically used in cases where there are only 2-5 /// options. /// /// The options are represented by segments described with [ButtonSegment] /// entries in the [segments] field. Each segment has a [ButtonSegment.value] /// that is used to indicate which segments are selected. /// /// The [selected] field is a set of selected [ButtonSegment.value]s. This /// should be updated by the app in response to [onSelectionChanged] updates. /// /// By default, only a single segment can be selected (for mutually exclusive /// choices). This can be relaxed with the [multiSelectionEnabled] field. /// /// Like [ButtonStyleButton]s, the [SegmentedButton]'s visuals can be /// configured with a [ButtonStyle] [style] field. However, unlike other /// buttons, some of the style parameters are applied to the entire segmented /// button, and others are used for each of the segments. /// /// By default, a checkmark icon is used to show selected items. To configure /// this behavior, you can use the [showSelectedIcon] and [selectedIcon] fields. /// /// Individual segments can be enabled or disabled with their /// [ButtonSegment.enabled] flag. If the [onSelectionChanged] field is null, /// then the entire segmented button will be disabled, regardless of the /// individual segment settings. /// /// {@tool dartpad} /// This sample shows how to display a [SegmentedButton] with either a single or /// multiple selection. /// /// ** See code in examples/api/lib/material/segmented_button/segmented_button.0.dart ** /// {@end-tool} /// /// {@tool dartpad} /// This sample showcases how to customize [SegmentedButton] using [SegmentedButton.styleFrom]. /// /// ** See code in examples/api/lib/material/segmented_button/segmented_button.1.dart ** /// {@end-tool} /// /// See also: /// /// * Material Design spec: <https://m3.material.io/components/segmented-buttons/overview> /// * [ButtonStyle], which can be used in the [style] field to configure /// the appearance of the button and its segments. /// * [ToggleButtons], a similar widget that was built for Material 2. /// [SegmentedButton] should be considered as a replacement for /// [ToggleButtons]. /// * [Radio], an alternative way to present the user with a mutually exclusive set of options. /// * [FilterChip], [ChoiceChip], which can be used when you need to show more than five options. class SegmentedButton<T> extends StatefulWidget { /// Creates a const [SegmentedButton]. /// /// [segments] must contain at least one segment, but it is recommended /// to have two to five segments. If you need only single segment, /// consider using a [Checkbox] or [Radio] widget instead. If you need /// more than five options, consider using [FilterChip] or [ChoiceChip] /// widgets. /// /// If [onSelectionChanged] is null, then the entire segmented button will /// be disabled. /// /// By default [selected] must only contain one entry. However, if /// [multiSelectionEnabled] is true, then [selected] can contain multiple /// entries. If [emptySelectionAllowed] is true, then [selected] can be empty. const SegmentedButton({ super.key, required this.segments, required this.selected, this.onSelectionChanged, this.multiSelectionEnabled = false, this.emptySelectionAllowed = false, this.style, this.showSelectedIcon = true, this.selectedIcon, }) : assert(segments.length > 0), assert(selected.length > 0 || emptySelectionAllowed), assert(selected.length < 2 || multiSelectionEnabled); /// Descriptions of the segments in the button. /// /// This a required parameter and must contain at least one segment, /// but it is recommended to contain two to five segments. If you need only /// a single segment, consider using a [Checkbox] or [Radio] widget instead. /// If you need more than five options, consider using [FilterChip] or /// [ChoiceChip] widgets. final List<ButtonSegment<T>> segments; /// The set of [ButtonSegment.value]s that indicate which [segments] are /// selected. /// /// As the [SegmentedButton] does not maintain the state of the selection, /// you will need to update this in response to [onSelectionChanged] calls. /// /// This is a required parameter. final Set<T> selected; /// The function that is called when the selection changes. /// /// The callback's parameter indicates which of the segments are selected. /// /// When the callback is null, the entire [SegmentedButton] is disabled, /// and will not respond to input. /// /// The default is null. final void Function(Set<T>)? onSelectionChanged; /// Determines if multiple segments can be selected at one time. /// /// If true, more than one segment can be selected. When selecting a /// segment, the other selected segments will stay selected. Selecting an /// already selected segment will unselect it. /// /// If false, only one segment may be selected at a time. When a segment /// is selected, any previously selected segment will be unselected. /// /// The default is false, so only a single segment may be selected at one /// time. final bool multiSelectionEnabled; /// Determines if having no selected segments is allowed. /// /// If true, then it is acceptable for none of the segments to be selected. /// This means that [selected] can be empty. If the user taps on a /// selected segment, it will be removed from the selection set passed into /// [onSelectionChanged]. /// /// If false (the default), there must be at least one segment selected. If /// the user taps on the only selected segment it will not be deselected, and /// [onSelectionChanged] will not be called. final bool emptySelectionAllowed; /// A static convenience method that constructs a segmented button /// [ButtonStyle] given simple values. /// /// The [foregroundColor], [selectedForegroundColor], and [disabledForegroundColor] /// colors are used to create a [MaterialStateProperty] [ButtonStyle.foregroundColor], /// and a derived [ButtonStyle.overlayColor]. /// /// The [backgroundColor], [selectedBackgroundColor] and [disabledBackgroundColor] /// colors are used to create a [MaterialStateProperty] [ButtonStyle.backgroundColor]. /// /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] /// parameters are used to construct [ButtonStyle.mouseCursor]. /// /// All of the other parameters are either used directly or used to /// create a [MaterialStateProperty] with a single value for all /// states. /// /// All parameters default to null. By default this method returns /// a [ButtonStyle] that doesn't override anything. /// /// {@tool snippet} /// /// For example, to override the default text and icon colors for a /// [SegmentedButton], as well as its overlay color, with all of the /// standard opacity adjustments for the pressed, focused, and /// hovered states, one could write: /// /// ** See code in examples/api/lib/material/segmented_button/segmented_button.1.dart ** /// /// ```dart /// SegmentedButton<int>( /// style: SegmentedButton.styleFrom( /// foregroundColor: Colors.black, /// selectedForegroundColor: Colors.white, /// backgroundColor: Colors.amber, /// selectedBackgroundColor: Colors.red, /// ), /// segments: const <ButtonSegment<int>>[ /// ButtonSegment<int>( /// value: 0, /// label: Text('0'), /// icon: Icon(Icons.calendar_view_day), /// ), /// ButtonSegment<int>( /// value: 1, /// label: Text('1'), /// icon: Icon(Icons.calendar_view_week), /// ), /// ], /// selected: const <int>{0}, /// onSelectionChanged: (Set<int> selection) {}, /// ), /// ``` /// {@end-tool} static ButtonStyle styleFrom({ Color? foregroundColor, Color? backgroundColor, Color? selectedForegroundColor, Color? selectedBackgroundColor, Color? disabledForegroundColor, Color? disabledBackgroundColor, Color? shadowColor, Color? surfaceTintColor, double? elevation, TextStyle? textStyle, EdgeInsetsGeometry? padding, Size? minimumSize, Size? fixedSize, Size? maximumSize, BorderSide? side, OutlinedBorder? shape, MouseCursor? enabledMouseCursor, MouseCursor? disabledMouseCursor, VisualDensity? visualDensity, MaterialTapTargetSize? tapTargetSize, Duration? animationDuration, bool? enableFeedback, AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, }) { final MaterialStateProperty<Color?>? foregroundColorProp = (foregroundColor == null && disabledForegroundColor == null && selectedForegroundColor == null) ? null : _SegmentButtonDefaultColor(foregroundColor, disabledForegroundColor, selectedForegroundColor); final MaterialStateProperty<Color?>? backgroundColorProp = (backgroundColor == null && disabledBackgroundColor == null && selectedBackgroundColor == null) ? null : _SegmentButtonDefaultColor(backgroundColor, disabledBackgroundColor, selectedBackgroundColor); final MaterialStateProperty<Color?>? overlayColor = (foregroundColor == null && selectedForegroundColor == null) ? null : _SegmentedButtonDefaultsM3.resolveStateColor(foregroundColor, selectedForegroundColor); return TextButton.styleFrom( textStyle: textStyle, shadowColor: shadowColor, surfaceTintColor: surfaceTintColor, elevation: elevation, padding: padding, minimumSize: minimumSize, fixedSize: fixedSize, maximumSize: maximumSize, side: side, shape: shape, enabledMouseCursor: enabledMouseCursor, disabledMouseCursor: disabledMouseCursor, visualDensity: visualDensity, tapTargetSize: tapTargetSize, animationDuration: animationDuration, enableFeedback: enableFeedback, alignment: alignment, splashFactory: splashFactory, ).copyWith( foregroundColor: foregroundColorProp, backgroundColor: backgroundColorProp, overlayColor: overlayColor, ); } /// Customizes this button's appearance. /// /// The following style properties apply to the entire segmented button: /// /// * [ButtonStyle.shadowColor] /// * [ButtonStyle.elevation] /// * [ButtonStyle.side] - which is used for both the outer shape and /// dividers between segments. /// * [ButtonStyle.shape] /// /// The following style properties are applied to each of the individual /// button segments. For properties that are a [MaterialStateProperty], /// they will be resolved with the current state of the segment: /// /// * [ButtonStyle.textStyle] /// * [ButtonStyle.backgroundColor] /// * [ButtonStyle.foregroundColor] /// * [ButtonStyle.overlayColor] /// * [ButtonStyle.surfaceTintColor] /// * [ButtonStyle.elevation] /// * [ButtonStyle.padding] /// * [ButtonStyle.iconColor] /// * [ButtonStyle.iconSize] /// * [ButtonStyle.mouseCursor] /// * [ButtonStyle.visualDensity] /// * [ButtonStyle.tapTargetSize] /// * [ButtonStyle.animationDuration] /// * [ButtonStyle.enableFeedback] /// * [ButtonStyle.alignment] /// * [ButtonStyle.splashFactory] final ButtonStyle? style; /// Determines if the [selectedIcon] (usually an icon using [Icons.check]) /// is displayed on the selected segments. /// /// If true, the [selectedIcon] will be displayed at the start of the segment. /// If both the [ButtonSegment.label] and [ButtonSegment.icon] are provided, /// then the icon will be replaced with the [selectedIcon]. If only the icon /// or the label is present then the [selectedIcon] will be shown at the start /// of the segment. /// /// If false, then the [selectedIcon] is not used and will not be displayed /// on selected segments. /// /// The default is true, meaning the [selectedIcon] will be shown on selected /// segments. final bool showSelectedIcon; /// An icon that is used to indicate a segment is selected. /// /// If [showSelectedIcon] is true then for selected segments this icon /// will be shown before the [ButtonSegment.label], replacing the /// [ButtonSegment.icon] if it is specified. /// /// Defaults to an [Icon] with [Icons.check]. final Widget? selectedIcon; @override State<SegmentedButton<T>> createState() => SegmentedButtonState<T>(); } /// State for [SegmentedButton]. @visibleForTesting class SegmentedButtonState<T> extends State<SegmentedButton<T>> { bool get _enabled => widget.onSelectionChanged != null; /// Controllers for the [ButtonSegment]s. @visibleForTesting final Map<ButtonSegment<T>, MaterialStatesController> statesControllers = <ButtonSegment<T>, MaterialStatesController>{}; @override void didUpdateWidget(covariant SegmentedButton<T> oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget != widget) { statesControllers.removeWhere((ButtonSegment<T> segment, MaterialStatesController controller) { if (widget.segments.contains(segment)) { return false; } else { controller.dispose(); return true; } }); } } void _handleOnPressed(T segmentValue) { if (!_enabled) { return; } final bool onlySelectedSegment = widget.selected.length == 1 && widget.selected.contains(segmentValue); final bool validChange = widget.emptySelectionAllowed || !onlySelectedSegment; if (validChange) { final bool toggle = widget.multiSelectionEnabled || (widget.emptySelectionAllowed && onlySelectedSegment); final Set<T> pressedSegment = <T>{segmentValue}; late final Set<T> updatedSelection; if (toggle) { updatedSelection = widget.selected.contains(segmentValue) ? widget.selected.difference(pressedSegment) : widget.selected.union(pressedSegment); } else { updatedSelection = pressedSegment; } if (!setEquals(updatedSelection, widget.selected)) { widget.onSelectionChanged!(updatedSelection); } } } @override Widget build(BuildContext context) { final SegmentedButtonThemeData theme = SegmentedButtonTheme.of(context); final SegmentedButtonThemeData defaults = _SegmentedButtonDefaultsM3(context); final TextDirection direction = Directionality.of(context); const Set<MaterialState> enabledState = <MaterialState>{}; const Set<MaterialState> disabledState = <MaterialState>{ MaterialState.disabled }; final Set<MaterialState> currentState = _enabled ? enabledState : disabledState; P? effectiveValue<P>(P? Function(ButtonStyle? style) getProperty) { late final P? widgetValue = getProperty(widget.style); late final P? themeValue = getProperty(theme.style); late final P? defaultValue = getProperty(defaults.style); return widgetValue ?? themeValue ?? defaultValue; } P? resolve<P>(MaterialStateProperty<P>? Function(ButtonStyle? style) getProperty, [Set<MaterialState>? states]) { return effectiveValue( (ButtonStyle? style) => getProperty(style)?.resolve(states ?? currentState), ); } ButtonStyle segmentStyleFor(ButtonStyle? style) { return ButtonStyle( textStyle: style?.textStyle, backgroundColor: style?.backgroundColor, foregroundColor: style?.foregroundColor, overlayColor: style?.overlayColor, surfaceTintColor: style?.surfaceTintColor, elevation: style?.elevation, padding: style?.padding, iconColor: style?.iconColor, iconSize: style?.iconSize, shape: const MaterialStatePropertyAll<OutlinedBorder>(RoundedRectangleBorder()), mouseCursor: style?.mouseCursor, visualDensity: style?.visualDensity, tapTargetSize: style?.tapTargetSize, animationDuration: style?.animationDuration, enableFeedback: style?.enableFeedback, alignment: style?.alignment, splashFactory: style?.splashFactory, ); } final ButtonStyle segmentStyle = segmentStyleFor(widget.style); final ButtonStyle segmentThemeStyle = segmentStyleFor(theme.style).merge(segmentStyleFor(defaults.style)); final Widget? selectedIcon = widget.showSelectedIcon ? widget.selectedIcon ?? theme.selectedIcon ?? defaults.selectedIcon : null; Widget buttonFor(ButtonSegment<T> segment) { final Widget label = segment.label ?? segment.icon ?? const SizedBox.shrink(); final bool segmentSelected = widget.selected.contains(segment.value); final Widget? icon = (segmentSelected && widget.showSelectedIcon) ? selectedIcon : segment.label != null ? segment.icon : null; final MaterialStatesController controller = statesControllers.putIfAbsent(segment, () => MaterialStatesController()); controller.update(MaterialState.selected, segmentSelected); final Widget button = icon != null ? TextButton.icon( style: segmentStyle, statesController: controller, onPressed: (_enabled && segment.enabled) ? () => _handleOnPressed(segment.value) : null, icon: icon, label: label, ) : TextButton( style: segmentStyle, statesController: controller, onPressed: (_enabled && segment.enabled) ? () => _handleOnPressed(segment.value) : null, child: label, ); final Widget buttonWithTooltip = segment.tooltip != null ? Tooltip( message: segment.tooltip, child: button, ) : button; return MergeSemantics( child: Semantics( checked: segmentSelected, inMutuallyExclusiveGroup: widget.multiSelectionEnabled ? null : true, child: buttonWithTooltip, ), ); } final OutlinedBorder resolvedEnabledBorder = resolve<OutlinedBorder?>((ButtonStyle? style) => style?.shape, disabledState) ?? const RoundedRectangleBorder(); final OutlinedBorder resolvedDisabledBorder = resolve<OutlinedBorder?>((ButtonStyle? style) => style?.shape, disabledState)?? const RoundedRectangleBorder(); final BorderSide enabledSide = resolve<BorderSide?>((ButtonStyle? style) => style?.side, enabledState) ?? BorderSide.none; final BorderSide disabledSide = resolve<BorderSide?>((ButtonStyle? style) => style?.side, disabledState) ?? BorderSide.none; final OutlinedBorder enabledBorder = resolvedEnabledBorder.copyWith(side: enabledSide); final OutlinedBorder disabledBorder = resolvedDisabledBorder.copyWith(side: disabledSide); final VisualDensity resolvedVisualDensity = segmentStyle.visualDensity ?? segmentThemeStyle.visualDensity ?? Theme.of(context).visualDensity; final EdgeInsetsGeometry resolvedPadding = resolve<EdgeInsetsGeometry?>((ButtonStyle? style) => style?.padding, enabledState) ?? EdgeInsets.zero; final MaterialTapTargetSize resolvedTapTargetSize = segmentStyle.tapTargetSize ?? segmentThemeStyle.tapTargetSize ?? Theme.of(context).materialTapTargetSize; final double fontSize = resolve<TextStyle?>((ButtonStyle? style) => style?.textStyle, enabledState)?.fontSize ?? 20.0; final List<Widget> buttons = widget.segments.map(buttonFor).toList(); final Offset densityAdjustment = resolvedVisualDensity.baseSizeAdjustment; const double textButtonMinHeight = 40.0; final double adjustButtonMinHeight = textButtonMinHeight + densityAdjustment.dy; final double effectiveVerticalPadding = resolvedPadding.vertical + densityAdjustment.dy * 2; final double effectedButtonHeight = max(fontSize + effectiveVerticalPadding, adjustButtonMinHeight); final double tapTargetVerticalPadding = switch (resolvedTapTargetSize) { MaterialTapTargetSize.shrinkWrap => 0.0, MaterialTapTargetSize.padded => max(0, kMinInteractiveDimension + densityAdjustment.dy - effectedButtonHeight) }; return Material( type: MaterialType.transparency, elevation: resolve<double?>((ButtonStyle? style) => style?.elevation)!, shadowColor: resolve<Color?>((ButtonStyle? style) => style?.shadowColor), surfaceTintColor: resolve<Color?>((ButtonStyle? style) => style?.surfaceTintColor), child: TextButtonTheme( data: TextButtonThemeData(style: segmentThemeStyle), child: _SegmentedButtonRenderWidget<T>( tapTargetVerticalPadding: tapTargetVerticalPadding, segments: widget.segments, enabledBorder: _enabled ? enabledBorder : disabledBorder, disabledBorder: disabledBorder, direction: direction, children: buttons, ), ), ); } @override void dispose() { for (final MaterialStatesController controller in statesControllers.values) { controller.dispose(); } super.dispose(); } } @immutable class _SegmentButtonDefaultColor extends MaterialStateProperty<Color?> with Diagnosticable { _SegmentButtonDefaultColor(this.color, this.disabled, this.selected); final Color? color; final Color? disabled; final Color? selected; @override Color? resolve(Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return disabled; } if (states.contains(MaterialState.selected)) { return selected; } return color; } } class _SegmentedButtonRenderWidget<T> extends MultiChildRenderObjectWidget { const _SegmentedButtonRenderWidget({ super.key, required this.segments, required this.enabledBorder, required this.disabledBorder, required this.direction, required this.tapTargetVerticalPadding, required super.children, }) : assert(children.length == segments.length); final List<ButtonSegment<T>> segments; final OutlinedBorder enabledBorder; final OutlinedBorder disabledBorder; final TextDirection direction; final double tapTargetVerticalPadding; @override RenderObject createRenderObject(BuildContext context) { return _RenderSegmentedButton<T>( segments: segments, enabledBorder: enabledBorder, disabledBorder: disabledBorder, textDirection: direction, tapTargetVerticalPadding: tapTargetVerticalPadding, ); } @override void updateRenderObject(BuildContext context, _RenderSegmentedButton<T> renderObject) { renderObject ..segments = segments ..enabledBorder = enabledBorder ..disabledBorder = disabledBorder ..textDirection = direction; } } class _SegmentedButtonContainerBoxParentData extends ContainerBoxParentData<RenderBox> { RRect? surroundingRect; } typedef _NextChild = RenderBox? Function(RenderBox child); class _RenderSegmentedButton<T> extends RenderBox with ContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>, RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>> { _RenderSegmentedButton({ required List<ButtonSegment<T>> segments, required OutlinedBorder enabledBorder, required OutlinedBorder disabledBorder, required TextDirection textDirection, required double tapTargetVerticalPadding, }) : _segments = segments, _enabledBorder = enabledBorder, _disabledBorder = disabledBorder, _textDirection = textDirection, _tapTargetVerticalPadding = tapTargetVerticalPadding; List<ButtonSegment<T>> get segments => _segments; List<ButtonSegment<T>> _segments; set segments(List<ButtonSegment<T>> value) { if (listEquals(segments, value)) { return; } _segments = value; markNeedsLayout(); } OutlinedBorder get enabledBorder => _enabledBorder; OutlinedBorder _enabledBorder; set enabledBorder(OutlinedBorder value) { if (_enabledBorder == value) { return; } _enabledBorder = value; markNeedsLayout(); } OutlinedBorder get disabledBorder => _disabledBorder; OutlinedBorder _disabledBorder; set disabledBorder(OutlinedBorder value) { if (_disabledBorder == value) { return; } _disabledBorder = value; markNeedsLayout(); } TextDirection get textDirection => _textDirection; TextDirection _textDirection; set textDirection(TextDirection value) { if (value == _textDirection) { return; } _textDirection = value; markNeedsLayout(); } double get tapTargetVerticalPadding => _tapTargetVerticalPadding; double _tapTargetVerticalPadding; set tapTargetVerticalPadding(double value) { if (value == _tapTargetVerticalPadding) { return; } _tapTargetVerticalPadding = value; markNeedsLayout(); } @override double computeMinIntrinsicWidth(double height) { RenderBox? child = firstChild; double minWidth = 0.0; while (child != null) { final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; final double childWidth = child.getMinIntrinsicWidth(height); minWidth = math.max(minWidth, childWidth); child = childParentData.nextSibling; } return minWidth * childCount; } @override double computeMaxIntrinsicWidth(double height) { RenderBox? child = firstChild; double maxWidth = 0.0; while (child != null) { final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; final double childWidth = child.getMaxIntrinsicWidth(height); maxWidth = math.max(maxWidth, childWidth); child = childParentData.nextSibling; } return maxWidth * childCount; } @override double computeMinIntrinsicHeight(double width) { RenderBox? child = firstChild; double minHeight = 0.0; while (child != null) { final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; final double childHeight = child.getMinIntrinsicHeight(width); minHeight = math.max(minHeight, childHeight); child = childParentData.nextSibling; } return minHeight; } @override double computeMaxIntrinsicHeight(double width) { RenderBox? child = firstChild; double maxHeight = 0.0; while (child != null) { final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; final double childHeight = child.getMaxIntrinsicHeight(width); maxHeight = math.max(maxHeight, childHeight); child = childParentData.nextSibling; } return maxHeight; } @override double? computeDistanceToActualBaseline(TextBaseline baseline) { return defaultComputeDistanceToHighestActualBaseline(baseline); } @override void setupParentData(RenderBox child) { if (child.parentData is! _SegmentedButtonContainerBoxParentData) { child.parentData = _SegmentedButtonContainerBoxParentData(); } } void _layoutRects(_NextChild nextChild, RenderBox? leftChild, RenderBox? rightChild) { RenderBox? child = leftChild; double start = 0.0; while (child != null) { final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; final Offset childOffset = Offset(start, 0.0); childParentData.offset = childOffset; final Rect childRect = Rect.fromLTWH(start, 0.0, child.size.width, child.size.height); final RRect rChildRect = RRect.fromRectAndCorners(childRect); childParentData.surroundingRect = rChildRect; start += child.size.width; child = nextChild(child); } } Size _calculateChildSize(BoxConstraints constraints) { double maxHeight = 0; double childWidth = constraints.minWidth / childCount; RenderBox? child = firstChild; while (child != null) { childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity)); child = childAfter(child); } childWidth = math.min(childWidth, constraints.maxWidth / childCount); child = firstChild; while (child != null) { final double boxHeight = child.getMaxIntrinsicHeight(childWidth); maxHeight = math.max(maxHeight, boxHeight); child = childAfter(child); } return Size(childWidth, maxHeight); } Size _computeOverallSizeFromChildSize(Size childSize) { return constraints.constrain(Size(childSize.width * childCount, childSize.height)); } @override Size computeDryLayout(BoxConstraints constraints) { final Size childSize = _calculateChildSize(constraints); return _computeOverallSizeFromChildSize(childSize); } @override void performLayout() { final BoxConstraints constraints = this.constraints; final Size childSize = _calculateChildSize(constraints); final BoxConstraints childConstraints = BoxConstraints.tightFor( width: childSize.width, height: childSize.height, ); RenderBox? child = firstChild; while (child != null) { child.layout(childConstraints, parentUsesSize: true); child = childAfter(child); } switch (textDirection) { case TextDirection.rtl: _layoutRects( childBefore, lastChild, firstChild, ); case TextDirection.ltr: _layoutRects( childAfter, firstChild, lastChild, ); } size = _computeOverallSizeFromChildSize(childSize); } @override void paint(PaintingContext context, Offset offset) { final Rect borderRect = (offset + Offset(0, tapTargetVerticalPadding / 2)) & (Size(size.width, size.height - tapTargetVerticalPadding)); final Path borderClipPath = enabledBorder.getInnerPath(borderRect, textDirection: textDirection); RenderBox? child = firstChild; RenderBox? previousChild; int index = 0; Path? enabledClipPath; Path? disabledClipPath; context.canvas..save()..clipPath(borderClipPath); while (child != null) { final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; final Rect childRect = childParentData.surroundingRect!.outerRect.shift(offset); context.canvas..save()..clipRect(childRect); context.paintChild(child, childParentData.offset + offset); context.canvas.restore(); // Compute a clip rect for the outer border of the child. late final double segmentLeft; late final double segmentRight; late final double dividerPos; final double borderOutset = math.max(enabledBorder.side.strokeOutset, disabledBorder.side.strokeOutset); switch (textDirection) { case TextDirection.rtl: segmentLeft = child == lastChild ? borderRect.left - borderOutset : childRect.left; segmentRight = child == firstChild ? borderRect.right + borderOutset : childRect.right; dividerPos = segmentRight; case TextDirection.ltr: segmentLeft = child == firstChild ? borderRect.left - borderOutset : childRect.left; segmentRight = child == lastChild ? borderRect.right + borderOutset : childRect.right; dividerPos = segmentLeft; } final Rect segmentClipRect = Rect.fromLTRB( segmentLeft, borderRect.top - borderOutset, segmentRight, borderRect.bottom + borderOutset); // Add the clip rect to the appropriate border clip path if (segments[index].enabled) { enabledClipPath = (enabledClipPath ?? Path())..addRect(segmentClipRect); } else { disabledClipPath = (disabledClipPath ?? Path())..addRect(segmentClipRect); } // Paint the divider between this segment and the previous one. if (previousChild != null) { final BorderSide divider = segments[index - 1].enabled || segments[index].enabled ? enabledBorder.side.copyWith(strokeAlign: 0.0) : disabledBorder.side.copyWith(strokeAlign: 0.0); final Offset top = Offset(dividerPos, childRect.top); final Offset bottom = Offset(dividerPos, childRect.bottom); context.canvas.drawLine(top, bottom, divider.toPaint()); } previousChild = child; child = childAfter(child); index += 1; } context.canvas.restore(); // Paint the outer border for both disabled and enabled clip rect if needed. if (disabledClipPath == null) { // Just paint the enabled border with no clip. enabledBorder.paint(context.canvas, borderRect, textDirection: textDirection); } else if (enabledClipPath == null) { // Just paint the disabled border with no. disabledBorder.paint(context.canvas, borderRect, textDirection: textDirection); } else { // Paint both of them clipped appropriately for the children segments. context.canvas..save()..clipPath(enabledClipPath); enabledBorder.paint(context.canvas, borderRect, textDirection: textDirection); context.canvas..restore()..save()..clipPath(disabledClipPath); disabledBorder.paint(context.canvas, borderRect, textDirection: textDirection); context.canvas.restore(); } } @override bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { RenderBox? child = lastChild; while (child != null) { final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; if (childParentData.surroundingRect!.contains(position)) { return result.addWithPaintOffset( offset: childParentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset localOffset) { assert(localOffset == position - childParentData.offset); return child!.hitTest(result, position: localOffset); }, ); } child = childParentData.previousSibling; } return false; } } // BEGIN GENERATED TOKEN PROPERTIES - SegmentedButton // 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 _SegmentedButtonDefaultsM3 extends SegmentedButtonThemeData { _SegmentedButtonDefaultsM3(this.context); final BuildContext context; late final ThemeData _theme = Theme.of(context); late final ColorScheme _colors = _theme.colorScheme; @override ButtonStyle? get style { return ButtonStyle( textStyle: MaterialStatePropertyAll<TextStyle?>(Theme.of(context).textTheme.labelLarge), backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return null; } if (states.contains(MaterialState.selected)) { return _colors.secondaryContainer; } return null; }), foregroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return _colors.onSurface.withOpacity(0.38); } if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { return _colors.onSecondaryContainer; } if (states.contains(MaterialState.hovered)) { return _colors.onSecondaryContainer; } if (states.contains(MaterialState.focused)) { return _colors.onSecondaryContainer; } return _colors.onSecondaryContainer; } else { if (states.contains(MaterialState.pressed)) { return _colors.onSurface; } if (states.contains(MaterialState.hovered)) { return _colors.onSurface; } if (states.contains(MaterialState.focused)) { return _colors.onSurface; } return _colors.onSurface; } }), overlayColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { return _colors.onSecondaryContainer.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSecondaryContainer.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { return _colors.onSecondaryContainer.withOpacity(0.1); } } else { if (states.contains(MaterialState.pressed)) { return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { return _colors.onSurface.withOpacity(0.1); } } return null; }), surfaceTintColor: const MaterialStatePropertyAll<Color>(Colors.transparent), elevation: const MaterialStatePropertyAll<double>(0), iconSize: const MaterialStatePropertyAll<double?>(18.0), side: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return BorderSide(color: _colors.onSurface.withOpacity(0.12)); } return BorderSide(color: _colors.outline); }), shape: const MaterialStatePropertyAll<OutlinedBorder>(StadiumBorder()), minimumSize: const MaterialStatePropertyAll<Size?>(Size.fromHeight(40.0)), ); } @override Widget? get selectedIcon => const Icon(Icons.check); static MaterialStateProperty<Color?> resolveStateColor(Color? unselectedColor, Color? selectedColor){ return MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { return selectedColor?.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return selectedColor?.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { return selectedColor?.withOpacity(0.1); } } else { if (states.contains(MaterialState.pressed)) { return unselectedColor?.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return unselectedColor?.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { return unselectedColor?.withOpacity(0.1); } } return Colors.transparent; }); } } // END GENERATED TOKEN PROPERTIES - SegmentedButton
flutter/packages/flutter/lib/src/material/segmented_button.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/segmented_button.dart", "repo_id": "flutter", "token_count": 13781 }
678
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'ink_well.dart'; import 'material_state.dart'; import 'tabs.dart'; import 'theme.dart'; /// Defines a theme for [TabBar] widgets. /// /// A tab bar theme describes the color of the tab label and the size/shape of /// the [TabBar.indicator]. /// /// Descendant widgets obtain the current theme's [TabBarTheme] object using /// `TabBarTheme.of(context)`. Instances of [TabBarTheme] can be customized with /// [TabBarTheme.copyWith]. /// /// See also: /// /// * [TabBar], a widget that displays a horizontal row of tabs. /// * [ThemeData], which describes the overall theme information for the /// application. @immutable class TabBarTheme with Diagnosticable { /// Creates a tab bar theme that can be used with [ThemeData.tabBarTheme]. const TabBarTheme({ this.indicator, this.indicatorColor, this.indicatorSize, this.dividerColor, this.dividerHeight, this.labelColor, this.labelPadding, this.labelStyle, this.unselectedLabelColor, this.unselectedLabelStyle, this.overlayColor, this.splashFactory, this.mouseCursor, this.tabAlignment, }); /// Overrides the default value for [TabBar.indicator]. final Decoration? indicator; /// Overrides the default value for [TabBar.indicatorColor]. final Color? indicatorColor; /// Overrides the default value for [TabBar.indicatorSize]. final TabBarIndicatorSize? indicatorSize; /// Overrides the default value for [TabBar.dividerColor]. final Color? dividerColor; /// Overrides the default value for [TabBar.dividerHeight]. final double? dividerHeight; /// Overrides the default value for [TabBar.labelColor]. /// /// If [labelColor] is a [MaterialStateColor], then the effective color will /// depend on the [MaterialState.selected] state, i.e. if the [Tab] is /// selected or not. In case of unselected state, this [MaterialStateColor]'s /// resolved color will be used even if [TabBar.unselectedLabelColor] or /// [unselectedLabelColor] is non-null. final Color? labelColor; /// Overrides the default value for [TabBar.labelPadding]. /// /// If there are few tabs with both icon and text and few /// tabs with only icon or text, this padding is vertically /// adjusted to provide uniform padding to all tabs. final EdgeInsetsGeometry? labelPadding; /// Overrides the default value for [TabBar.labelStyle]. final TextStyle? labelStyle; /// Overrides the default value for [TabBar.unselectedLabelColor]. final Color? unselectedLabelColor; /// Overrides the default value for [TabBar.unselectedLabelStyle]. final TextStyle? unselectedLabelStyle; /// Overrides the default value for [TabBar.overlayColor]. final MaterialStateProperty<Color?>? overlayColor; /// Overrides the default value for [TabBar.splashFactory]. final InteractiveInkFeatureFactory? splashFactory; /// {@macro flutter.material.tabs.mouseCursor} /// /// If specified, overrides the default value of [TabBar.mouseCursor]. final MaterialStateProperty<MouseCursor?>? mouseCursor; /// Overrides the default value for [TabBar.tabAlignment]. final TabAlignment? tabAlignment; /// Creates a copy of this object but with the given fields replaced with the /// new values. TabBarTheme copyWith({ Decoration? indicator, Color? indicatorColor, TabBarIndicatorSize? indicatorSize, Color? dividerColor, double? dividerHeight, Color? labelColor, EdgeInsetsGeometry? labelPadding, TextStyle? labelStyle, Color? unselectedLabelColor, TextStyle? unselectedLabelStyle, MaterialStateProperty<Color?>? overlayColor, InteractiveInkFeatureFactory? splashFactory, MaterialStateProperty<MouseCursor?>? mouseCursor, TabAlignment? tabAlignment, }) { return TabBarTheme( indicator: indicator ?? this.indicator, indicatorColor: indicatorColor ?? this.indicatorColor, indicatorSize: indicatorSize ?? this.indicatorSize, dividerColor: dividerColor ?? this.dividerColor, dividerHeight: dividerHeight ?? this.dividerHeight, labelColor: labelColor ?? this.labelColor, labelPadding: labelPadding ?? this.labelPadding, labelStyle: labelStyle ?? this.labelStyle, unselectedLabelColor: unselectedLabelColor ?? this.unselectedLabelColor, unselectedLabelStyle: unselectedLabelStyle ?? this.unselectedLabelStyle, overlayColor: overlayColor ?? this.overlayColor, splashFactory: splashFactory ?? this.splashFactory, mouseCursor: mouseCursor ?? this.mouseCursor, tabAlignment: tabAlignment ?? this.tabAlignment, ); } /// The data from the closest [TabBarTheme] instance given the build context. static TabBarTheme of(BuildContext context) { return Theme.of(context).tabBarTheme; } /// Linearly interpolate between two tab bar themes. /// /// {@macro dart.ui.shadow.lerp} static TabBarTheme lerp(TabBarTheme a, TabBarTheme b, double t) { if (identical(a, b)) { return a; } return TabBarTheme( indicator: Decoration.lerp(a.indicator, b.indicator, t), indicatorColor: Color.lerp(a.indicatorColor, b.indicatorColor, t), indicatorSize: t < 0.5 ? a.indicatorSize : b.indicatorSize, dividerColor: Color.lerp(a.dividerColor, b.dividerColor, t), dividerHeight: t < 0.5 ? a.dividerHeight : b.dividerHeight, labelColor: Color.lerp(a.labelColor, b.labelColor, t), labelPadding: EdgeInsetsGeometry.lerp(a.labelPadding, b.labelPadding, t), labelStyle: TextStyle.lerp(a.labelStyle, b.labelStyle, t), unselectedLabelColor: Color.lerp(a.unselectedLabelColor, b.unselectedLabelColor, t), unselectedLabelStyle: TextStyle.lerp(a.unselectedLabelStyle, b.unselectedLabelStyle, t), overlayColor: MaterialStateProperty.lerp<Color?>(a.overlayColor, b.overlayColor, t, Color.lerp), splashFactory: t < 0.5 ? a.splashFactory : b.splashFactory, mouseCursor: t < 0.5 ? a.mouseCursor : b.mouseCursor, tabAlignment: t < 0.5 ? a.tabAlignment : b.tabAlignment, ); } @override int get hashCode => Object.hash( indicator, indicatorColor, indicatorSize, dividerColor, dividerHeight, labelColor, labelPadding, labelStyle, unselectedLabelColor, unselectedLabelStyle, overlayColor, splashFactory, mouseCursor, tabAlignment, ); @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is TabBarTheme && other.indicator == indicator && other.indicatorColor == indicatorColor && other.indicatorSize == indicatorSize && other.dividerColor == dividerColor && other.dividerHeight == dividerHeight && other.labelColor == labelColor && other.labelPadding == labelPadding && other.labelStyle == labelStyle && other.unselectedLabelColor == unselectedLabelColor && other.unselectedLabelStyle == unselectedLabelStyle && other.overlayColor == overlayColor && other.splashFactory == splashFactory && other.mouseCursor == mouseCursor && other.tabAlignment == tabAlignment; } }
flutter/packages/flutter/lib/src/material/tab_bar_theme.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/tab_bar_theme.dart", "repo_id": "flutter", "token_count": 2517 }
679
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:math' as math; import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'button_style.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'curves.dart'; import 'debug.dart'; import 'dialog.dart'; import 'feedback.dart'; import 'icon_button.dart'; import 'icons.dart'; import 'ink_well.dart'; import 'input_border.dart'; import 'input_decorator.dart'; import 'material.dart'; import 'material_localizations.dart'; import 'material_state.dart'; import 'text_button.dart'; import 'text_form_field.dart'; import 'text_theme.dart'; import 'theme.dart'; import 'theme_data.dart'; import 'time.dart'; import 'time_picker_theme.dart'; // Examples can assume: // late BuildContext context; const Duration _kDialogSizeAnimationDuration = Duration(milliseconds: 200); const Duration _kDialAnimateDuration = Duration(milliseconds: 200); const double _kTwoPi = 2 * math.pi; const Duration _kVibrateCommitDelay = Duration(milliseconds: 100); const double _kTimePickerHeaderLandscapeWidth = 216; const double _kTimePickerInnerDialOffset = 28; const double _kTimePickerDialMinRadius = 50; const double _kTimePickerDialPadding = 28; /// Interactive input mode of the time picker dialog. /// /// In [TimePickerEntryMode.dial] mode, a clock dial is displayed and the user /// taps or drags the time they wish to select. In TimePickerEntryMode.input] /// mode, [TextField]s are displayed and the user types in the time they wish to /// select. /// /// See also: /// /// * [showTimePicker], a function that shows a [TimePickerDialog] and returns /// the selected time as a [Future]. enum TimePickerEntryMode { /// User picks time from a clock dial. /// /// Can switch to [input] by activating a mode button in the dialog. dial, /// User can input the time by typing it into text fields. /// /// Can switch to [dial] by activating a mode button in the dialog. input, /// User can only pick time from a clock dial. /// /// There is no user interface to switch to another mode. dialOnly, /// User can only input the time by typing it into text fields. /// /// There is no user interface to switch to another mode. inputOnly } // Whether the dial-mode time picker is currently selecting the hour or the // minute. enum _HourMinuteMode { hour, minute } // Aspects of _TimePickerModel that can be depended upon. enum _TimePickerAspect { use24HourFormat, useMaterial3, entryMode, hourMinuteMode, onHourMinuteModeChanged, onHourDoubleTapped, onMinuteDoubleTapped, hourDialType, selectedTime, onSelectedTimeChanged, orientation, theme, defaultTheme, } class _TimePickerModel extends InheritedModel<_TimePickerAspect> { const _TimePickerModel({ required this.entryMode, required this.hourMinuteMode, required this.onHourMinuteModeChanged, required this.onHourDoubleTapped, required this.onMinuteDoubleTapped, required this.selectedTime, required this.onSelectedTimeChanged, required this.use24HourFormat, required this.useMaterial3, required this.hourDialType, required this.orientation, required this.theme, required this.defaultTheme, required super.child, }); final TimePickerEntryMode entryMode; final _HourMinuteMode hourMinuteMode; final ValueChanged<_HourMinuteMode> onHourMinuteModeChanged; final GestureTapCallback onHourDoubleTapped; final GestureTapCallback onMinuteDoubleTapped; final TimeOfDay selectedTime; final ValueChanged<TimeOfDay> onSelectedTimeChanged; final bool use24HourFormat; final bool useMaterial3; final _HourDialType hourDialType; final Orientation orientation; final TimePickerThemeData theme; final _TimePickerDefaults defaultTheme; static _TimePickerModel of(BuildContext context, [_TimePickerAspect? aspect]) => InheritedModel.inheritFrom<_TimePickerModel>(context, aspect: aspect)!; static TimePickerEntryMode entryModeOf(BuildContext context) => of(context, _TimePickerAspect.entryMode).entryMode; static _HourMinuteMode hourMinuteModeOf(BuildContext context) => of(context, _TimePickerAspect.hourMinuteMode).hourMinuteMode; static TimeOfDay selectedTimeOf(BuildContext context) => of(context, _TimePickerAspect.selectedTime).selectedTime; static bool use24HourFormatOf(BuildContext context) => of(context, _TimePickerAspect.use24HourFormat).use24HourFormat; static bool useMaterial3Of(BuildContext context) => of(context, _TimePickerAspect.useMaterial3).useMaterial3; static _HourDialType hourDialTypeOf(BuildContext context) => of(context, _TimePickerAspect.hourDialType).hourDialType; static Orientation orientationOf(BuildContext context) => of(context, _TimePickerAspect.orientation).orientation; static TimePickerThemeData themeOf(BuildContext context) => of(context, _TimePickerAspect.theme).theme; static _TimePickerDefaults defaultThemeOf(BuildContext context) => of(context, _TimePickerAspect.defaultTheme).defaultTheme; static void setSelectedTime(BuildContext context, TimeOfDay value) => of(context, _TimePickerAspect.onSelectedTimeChanged).onSelectedTimeChanged(value); static void setHourMinuteMode(BuildContext context, _HourMinuteMode value) => of(context, _TimePickerAspect.onHourMinuteModeChanged).onHourMinuteModeChanged(value); @override bool updateShouldNotifyDependent(_TimePickerModel oldWidget, Set<_TimePickerAspect> dependencies) { if (use24HourFormat != oldWidget.use24HourFormat && dependencies.contains(_TimePickerAspect.use24HourFormat)) { return true; } if (useMaterial3 != oldWidget.useMaterial3 && dependencies.contains(_TimePickerAspect.useMaterial3)) { return true; } if (entryMode != oldWidget.entryMode && dependencies.contains(_TimePickerAspect.entryMode)) { return true; } if (hourMinuteMode != oldWidget.hourMinuteMode && dependencies.contains(_TimePickerAspect.hourMinuteMode)) { return true; } if (onHourMinuteModeChanged != oldWidget.onHourMinuteModeChanged && dependencies.contains(_TimePickerAspect.onHourMinuteModeChanged)) { return true; } if (onHourMinuteModeChanged != oldWidget.onHourDoubleTapped && dependencies.contains(_TimePickerAspect.onHourDoubleTapped)) { return true; } if (onHourMinuteModeChanged != oldWidget.onMinuteDoubleTapped && dependencies.contains(_TimePickerAspect.onMinuteDoubleTapped)) { return true; } if (hourDialType != oldWidget.hourDialType && dependencies.contains(_TimePickerAspect.hourDialType)) { return true; } if (selectedTime != oldWidget.selectedTime && dependencies.contains(_TimePickerAspect.selectedTime)) { return true; } if (onSelectedTimeChanged != oldWidget.onSelectedTimeChanged && dependencies.contains(_TimePickerAspect.onSelectedTimeChanged)) { return true; } if (orientation != oldWidget.orientation && dependencies.contains(_TimePickerAspect.orientation)) { return true; } if (theme != oldWidget.theme && dependencies.contains(_TimePickerAspect.theme)) { return true; } if (defaultTheme != oldWidget.defaultTheme && dependencies.contains(_TimePickerAspect.defaultTheme)) { return true; } return false; } @override bool updateShouldNotify(_TimePickerModel oldWidget) { return use24HourFormat != oldWidget.use24HourFormat || useMaterial3 != oldWidget.useMaterial3 || entryMode != oldWidget.entryMode || hourMinuteMode != oldWidget.hourMinuteMode || onHourMinuteModeChanged != oldWidget.onHourMinuteModeChanged || onHourDoubleTapped != oldWidget.onHourDoubleTapped || onMinuteDoubleTapped != oldWidget.onMinuteDoubleTapped || hourDialType != oldWidget.hourDialType || selectedTime != oldWidget.selectedTime || onSelectedTimeChanged != oldWidget.onSelectedTimeChanged || orientation != oldWidget.orientation || theme != oldWidget.theme || defaultTheme != oldWidget.defaultTheme; } } class _TimePickerHeader extends StatelessWidget { const _TimePickerHeader({ required this.helpText }); final String helpText; @override Widget build(BuildContext context) { final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat( alwaysUse24HourFormat: _TimePickerModel.use24HourFormatOf(context), ); final _HourDialType hourDialType = _TimePickerModel.hourDialTypeOf(context); switch (_TimePickerModel.orientationOf(context)) { case Orientation.portrait: return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding(padding: EdgeInsetsDirectional.only(bottom: _TimePickerModel.useMaterial3Of(context) ? 20 : 24), child: Text( helpText, style: _TimePickerModel.themeOf(context).helpTextStyle ?? _TimePickerModel.defaultThemeOf(context).helpTextStyle, ), ), Row( children: <Widget>[ if (hourDialType == _HourDialType.twelveHour && timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) const _DayPeriodControl(), Expanded( child: Row( // Hour/minutes should not change positions in RTL locales. textDirection: TextDirection.ltr, children: <Widget>[ const Expanded(child: _HourControl()), _TimeSelectorSeparator(timeOfDayFormat: timeOfDayFormat), const Expanded(child: _MinuteControl()), ], ), ), if (hourDialType == _HourDialType.twelveHour && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) ...<Widget>[ const SizedBox(width: 12), const _DayPeriodControl(), ], ], ), ], ); case Orientation.landscape: return SizedBox( width: _kTimePickerHeaderLandscapeWidth, child: Stack( children: <Widget>[ Text( helpText, style: _TimePickerModel.themeOf(context).helpTextStyle ?? _TimePickerModel.defaultThemeOf(context).helpTextStyle, ), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ if (hourDialType == _HourDialType.twelveHour && timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) const _DayPeriodControl(), Padding( padding: EdgeInsets.only(bottom: hourDialType == _HourDialType.twelveHour ? 12 : 0), child: Row( // Hour/minutes should not change positions in RTL locales. textDirection: TextDirection.ltr, children: <Widget>[ const Expanded(child: _HourControl()), _TimeSelectorSeparator(timeOfDayFormat: timeOfDayFormat), const Expanded(child: _MinuteControl()), ], ), ), if (hourDialType == _HourDialType.twelveHour && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) const _DayPeriodControl(), ], ), ], ), ); } } } class _HourMinuteControl extends StatelessWidget { const _HourMinuteControl({ required this.text, required this.onTap, required this.onDoubleTap, required this.isSelected, }); final String text; final GestureTapCallback onTap; final GestureTapCallback onDoubleTap; final bool isSelected; @override Widget build(BuildContext context) { final TimePickerThemeData timePickerTheme = _TimePickerModel.themeOf(context); final _TimePickerDefaults defaultTheme = _TimePickerModel.defaultThemeOf(context); final Color backgroundColor = timePickerTheme.hourMinuteColor ?? defaultTheme.hourMinuteColor; final ShapeBorder shape = timePickerTheme.hourMinuteShape ?? defaultTheme.hourMinuteShape; final Set<MaterialState> states = <MaterialState>{ if (isSelected) MaterialState.selected, }; final Color effectiveTextColor = MaterialStateProperty.resolveAs<Color>( _TimePickerModel.themeOf(context).hourMinuteTextColor ?? _TimePickerModel.defaultThemeOf(context).hourMinuteTextColor, states, ); final TextStyle effectiveStyle = MaterialStateProperty.resolveAs<TextStyle>( timePickerTheme.hourMinuteTextStyle ?? defaultTheme.hourMinuteTextStyle, states, ).copyWith(color: effectiveTextColor); final double height; switch (_TimePickerModel.entryModeOf(context)) { case TimePickerEntryMode.dial: case TimePickerEntryMode.dialOnly: height = defaultTheme.hourMinuteSize.height; case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: height = defaultTheme.hourMinuteInputSize.height; } return SizedBox( height: height, child: Material( color: MaterialStateProperty.resolveAs(backgroundColor, states), clipBehavior: Clip.antiAlias, shape: shape, child: InkWell( onTap: onTap, onDoubleTap: isSelected ? onDoubleTap : null, child: Center( child: Text( text, style: effectiveStyle, textScaler: TextScaler.noScaling, ), ), ), ), ); } } /// Displays the hour fragment. /// /// When tapped changes time picker dial mode to [_HourMinuteMode.hour]. class _HourControl extends StatelessWidget { const _HourControl(); @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); final bool alwaysUse24HourFormat = MediaQuery.alwaysUse24HourFormatOf(context); final TimeOfDay selectedTime = _TimePickerModel.selectedTimeOf(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context); final String formattedHour = localizations.formatHour( selectedTime, alwaysUse24HourFormat: _TimePickerModel.use24HourFormatOf(context), ); TimeOfDay hoursFromSelected(int hoursToAdd) { switch (_TimePickerModel.hourDialTypeOf(context)) { case _HourDialType.twentyFourHour: case _HourDialType.twentyFourHourDoubleRing: final int selectedHour = selectedTime.hour; return selectedTime.replacing( hour: (selectedHour + hoursToAdd) % TimeOfDay.hoursPerDay, ); case _HourDialType.twelveHour: // Cycle 1 through 12 without changing day period. final int periodOffset = selectedTime.periodOffset; final int hours = selectedTime.hourOfPeriod; return selectedTime.replacing( hour: periodOffset + (hours + hoursToAdd) % TimeOfDay.hoursPerPeriod, ); } } final TimeOfDay nextHour = hoursFromSelected(1); final String formattedNextHour = localizations.formatHour( nextHour, alwaysUse24HourFormat: alwaysUse24HourFormat, ); final TimeOfDay previousHour = hoursFromSelected(-1); final String formattedPreviousHour = localizations.formatHour( previousHour, alwaysUse24HourFormat: alwaysUse24HourFormat, ); return Semantics( value: '${localizations.timePickerHourModeAnnouncement} $formattedHour', excludeSemantics: true, increasedValue: formattedNextHour, onIncrease: () { _TimePickerModel.setSelectedTime(context, nextHour); }, decreasedValue: formattedPreviousHour, onDecrease: () { _TimePickerModel.setSelectedTime(context, previousHour); }, child: _HourMinuteControl( isSelected: _TimePickerModel.hourMinuteModeOf(context) == _HourMinuteMode.hour, text: formattedHour, onTap: Feedback.wrapForTap(() => _TimePickerModel.setHourMinuteMode(context, _HourMinuteMode.hour), context)!, onDoubleTap: _TimePickerModel.of(context, _TimePickerAspect.onHourDoubleTapped).onHourDoubleTapped, ), ); } } /// A passive fragment showing a string value. /// /// Used to display the appropriate separator between the input fields. class _TimeSelectorSeparator extends StatelessWidget { const _TimeSelectorSeparator({ required this.timeOfDayFormat }); final TimeOfDayFormat timeOfDayFormat; String _timeSelectorSeparatorValue(TimeOfDayFormat timeOfDayFormat) { switch (timeOfDayFormat) { case TimeOfDayFormat.h_colon_mm_space_a: case TimeOfDayFormat.a_space_h_colon_mm: case TimeOfDayFormat.H_colon_mm: case TimeOfDayFormat.HH_colon_mm: return ':'; case TimeOfDayFormat.HH_dot_mm: return '.'; case TimeOfDayFormat.frenchCanadian: return 'h'; } } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context); final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); final Set<MaterialState> states = <MaterialState>{}; final Color effectiveTextColor = MaterialStateProperty.resolveAs<Color>( timePickerTheme.timeSelectorSeparatorColor?.resolve(states) ?? timePickerTheme.hourMinuteTextColor ?? defaultTheme.timeSelectorSeparatorColor?.resolve(states) ?? defaultTheme.hourMinuteTextColor, states, ); final TextStyle effectiveStyle = MaterialStateProperty.resolveAs<TextStyle>( timePickerTheme.timeSelectorSeparatorTextStyle?.resolve(states) ?? timePickerTheme.hourMinuteTextStyle ?? defaultTheme.timeSelectorSeparatorTextStyle?.resolve(states) ?? defaultTheme.hourMinuteTextStyle, states, ).copyWith(color: effectiveTextColor); final double height; switch (_TimePickerModel.entryModeOf(context)) { case TimePickerEntryMode.dial: case TimePickerEntryMode.dialOnly: height = defaultTheme.hourMinuteSize.height; case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: height = defaultTheme.hourMinuteInputSize.height; } return ExcludeSemantics( child: SizedBox( width: timeOfDayFormat == TimeOfDayFormat.frenchCanadian ? 36 : 24, height: height, child: Text( _timeSelectorSeparatorValue(timeOfDayFormat), style: effectiveStyle, textScaler: TextScaler.noScaling, textAlign: TextAlign.center, ), ), ); } } /// Displays the minute fragment. /// /// When tapped changes time picker dial mode to [_HourMinuteMode.minute]. class _MinuteControl extends StatelessWidget { const _MinuteControl(); @override Widget build(BuildContext context) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); final TimeOfDay selectedTime = _TimePickerModel.selectedTimeOf(context); final String formattedMinute = localizations.formatMinute(selectedTime); final TimeOfDay nextMinute = selectedTime.replacing( minute: (selectedTime.minute + 1) % TimeOfDay.minutesPerHour, ); final String formattedNextMinute = localizations.formatMinute(nextMinute); final TimeOfDay previousMinute = selectedTime.replacing( minute: (selectedTime.minute - 1) % TimeOfDay.minutesPerHour, ); final String formattedPreviousMinute = localizations.formatMinute(previousMinute); return Semantics( excludeSemantics: true, value: '${localizations.timePickerMinuteModeAnnouncement} $formattedMinute', increasedValue: formattedNextMinute, onIncrease: () { _TimePickerModel.setSelectedTime(context, nextMinute); }, decreasedValue: formattedPreviousMinute, onDecrease: () { _TimePickerModel.setSelectedTime(context, previousMinute); }, child: _HourMinuteControl( isSelected: _TimePickerModel.hourMinuteModeOf(context) == _HourMinuteMode.minute, text: formattedMinute, onTap: Feedback.wrapForTap(() => _TimePickerModel.setHourMinuteMode(context, _HourMinuteMode.minute), context)!, onDoubleTap: _TimePickerModel.of(context, _TimePickerAspect.onMinuteDoubleTapped).onMinuteDoubleTapped, ), ); } } /// Displays the am/pm fragment and provides controls for switching between am /// and pm. class _DayPeriodControl extends StatelessWidget { const _DayPeriodControl({ this.onPeriodChanged }); final ValueChanged<TimeOfDay>? onPeriodChanged; void _togglePeriod(BuildContext context) { final TimeOfDay selectedTime = _TimePickerModel.selectedTimeOf(context); final int newHour = (selectedTime.hour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay; final TimeOfDay newTime = selectedTime.replacing(hour: newHour); if (onPeriodChanged != null) { onPeriodChanged!.call(newTime); } else { _TimePickerModel.setSelectedTime(context, newTime); } } void _setAm(BuildContext context) { final TimeOfDay selectedTime = _TimePickerModel.selectedTimeOf(context); if (selectedTime.period == DayPeriod.am) { return; } switch (Theme.of(context).platform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: _announceToAccessibility(context, MaterialLocalizations.of(context).anteMeridiemAbbreviation); case TargetPlatform.iOS: case TargetPlatform.macOS: break; } _togglePeriod(context); } void _setPm(BuildContext context) { final TimeOfDay selectedTime = _TimePickerModel.selectedTimeOf(context); if (selectedTime.period == DayPeriod.pm) { return; } switch (Theme.of(context).platform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: _announceToAccessibility(context, MaterialLocalizations.of(context).postMeridiemAbbreviation); case TargetPlatform.iOS: case TargetPlatform.macOS: break; } _togglePeriod(context); } @override Widget build(BuildContext context) { final MaterialLocalizations materialLocalizations = MaterialLocalizations.of(context); final TimePickerThemeData timePickerTheme = _TimePickerModel.themeOf(context); final _TimePickerDefaults defaultTheme = _TimePickerModel.defaultThemeOf(context); final TimeOfDay selectedTime = _TimePickerModel.selectedTimeOf(context); final bool amSelected = selectedTime.period == DayPeriod.am; final bool pmSelected = !amSelected; final BorderSide resolvedSide = timePickerTheme.dayPeriodBorderSide ?? defaultTheme.dayPeriodBorderSide; final OutlinedBorder resolvedShape = (timePickerTheme.dayPeriodShape ?? defaultTheme.dayPeriodShape) .copyWith(side: resolvedSide); final Widget amButton = _AmPmButton( selected: amSelected, onPressed: () => _setAm(context), label: materialLocalizations.anteMeridiemAbbreviation, ); final Widget pmButton = _AmPmButton( selected: pmSelected, onPressed: () => _setPm(context), label: materialLocalizations.postMeridiemAbbreviation, ); Size dayPeriodSize; final Orientation orientation; switch (_TimePickerModel.entryModeOf(context)) { case TimePickerEntryMode.dial: case TimePickerEntryMode.dialOnly: orientation = _TimePickerModel.orientationOf(context); dayPeriodSize = switch (orientation) { Orientation.portrait => defaultTheme.dayPeriodPortraitSize, Orientation.landscape => defaultTheme.dayPeriodLandscapeSize, }; case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: orientation = Orientation.portrait; dayPeriodSize = defaultTheme.dayPeriodInputSize; } final Widget result; switch (orientation) { case Orientation.portrait: result = _DayPeriodInputPadding( minSize: dayPeriodSize, orientation: orientation, child: SizedBox.fromSize( size: dayPeriodSize, child: Material( clipBehavior: Clip.antiAlias, color: Colors.transparent, shape: resolvedShape, child: Column( children: <Widget>[ Expanded(child: amButton), Container( decoration: BoxDecoration(border: Border(top: resolvedSide)), height: 1, ), Expanded(child: pmButton), ], ), ), ), ); case Orientation.landscape: result = _DayPeriodInputPadding( minSize: dayPeriodSize, orientation: orientation, child: SizedBox( height: dayPeriodSize.height, child: Material( clipBehavior: Clip.antiAlias, color: Colors.transparent, shape: resolvedShape, child: Row( children: <Widget>[ Expanded(child: amButton), Container( decoration: BoxDecoration(border: Border(left: resolvedSide)), width: 1, ), Expanded(child: pmButton), ], ), ), ), ); } return result; } } class _AmPmButton extends StatelessWidget { const _AmPmButton({ required this.onPressed, required this.selected, required this.label, }); final bool selected; final VoidCallback onPressed; final String label; @override Widget build(BuildContext context) { final Set<MaterialState> states = <MaterialState>{ if (selected) MaterialState.selected }; final TimePickerThemeData timePickerTheme = _TimePickerModel.themeOf(context); final _TimePickerDefaults defaultTheme = _TimePickerModel.defaultThemeOf(context); final Color resolvedBackgroundColor = MaterialStateProperty.resolveAs<Color>(timePickerTheme.dayPeriodColor ?? defaultTheme.dayPeriodColor, states); final Color resolvedTextColor = MaterialStateProperty.resolveAs<Color>(timePickerTheme.dayPeriodTextColor ?? defaultTheme.dayPeriodTextColor, states); final TextStyle? resolvedTextStyle = MaterialStateProperty.resolveAs<TextStyle?>(timePickerTheme.dayPeriodTextStyle ?? defaultTheme.dayPeriodTextStyle, states)?.copyWith(color: resolvedTextColor); final TextScaler buttonTextScaler = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 2.0); return Material( color: resolvedBackgroundColor, child: InkWell( onTap: Feedback.wrapForTap(onPressed, context), child: Semantics( checked: selected, inMutuallyExclusiveGroup: true, button: true, child: Center( child: Text( label, style: resolvedTextStyle, textScaler: buttonTextScaler, ), ), ), ), ); } } /// A widget to pad the area around the [_DayPeriodControl]'s inner [Material]. class _DayPeriodInputPadding extends SingleChildRenderObjectWidget { const _DayPeriodInputPadding({ required Widget super.child, required this.minSize, required this.orientation, }); final Size minSize; final Orientation orientation; @override RenderObject createRenderObject(BuildContext context) { return _RenderInputPadding(minSize, orientation); } @override void updateRenderObject(BuildContext context, covariant _RenderInputPadding renderObject) { renderObject ..minSize = minSize ..orientation = orientation; } } class _RenderInputPadding extends RenderShiftedBox { _RenderInputPadding(this._minSize, this._orientation, [RenderBox? child]) : super(child); Size get minSize => _minSize; Size _minSize; set minSize(Size value) { if (_minSize == value) { return; } _minSize = value; markNeedsLayout(); } Orientation get orientation => _orientation; Orientation _orientation; set orientation(Orientation value) { if (_orientation == value) { return; } _orientation = value; markNeedsLayout(); } @override double computeMinIntrinsicWidth(double height) { if (child != null) { return math.max(child!.getMinIntrinsicWidth(height), minSize.width); } return 0; } @override double computeMinIntrinsicHeight(double width) { if (child != null) { return math.max(child!.getMinIntrinsicHeight(width), minSize.height); } return 0; } @override double computeMaxIntrinsicWidth(double height) { if (child != null) { return math.max(child!.getMaxIntrinsicWidth(height), minSize.width); } return 0; } @override double computeMaxIntrinsicHeight(double width) { if (child != null) { return math.max(child!.getMaxIntrinsicHeight(width), minSize.height); } return 0; } Size _computeSize({required BoxConstraints constraints, required ChildLayouter layoutChild}) { if (child != null) { final Size childSize = layoutChild(child!, constraints); final double width = math.max(childSize.width, minSize.width); final double height = math.max(childSize.height, minSize.height); return constraints.constrain(Size(width, height)); } return Size.zero; } @override Size computeDryLayout(BoxConstraints constraints) { return _computeSize( constraints: constraints, layoutChild: ChildLayoutHelper.dryLayoutChild, ); } @override void performLayout() { size = _computeSize( constraints: constraints, layoutChild: ChildLayoutHelper.layoutChild, ); if (child != null) { final BoxParentData childParentData = child!.parentData! as BoxParentData; childParentData.offset = Alignment.center.alongOffset(size - child!.size as Offset); } } @override bool hitTest(BoxHitTestResult result, { required Offset position }) { if (super.hitTest(result, position: position)) { return true; } if (position.dx < 0 || position.dx > math.max(child!.size.width, minSize.width) || position.dy < 0 || position.dy > math.max(child!.size.height, minSize.height)) { return false; } Offset newPosition = child!.size.center(Offset.zero); newPosition += switch (orientation) { Orientation.portrait when position.dy > newPosition.dy => const Offset(0, 1), Orientation.landscape when position.dx > newPosition.dx => const Offset(1, 0), Orientation.portrait => const Offset(0, -1), Orientation.landscape => const Offset(-1, 0), }; return result.addWithRawTransform( transform: MatrixUtils.forceToPoint(newPosition), position: newPosition, hitTest: (BoxHitTestResult result, Offset position) { assert(position == newPosition); return child!.hitTest(result, position: newPosition); }, ); } } class _TappableLabel { _TappableLabel({ required this.value, required this.inner, required this.painter, required this.onTap, }); /// The value this label is displaying. final int value; /// This value is part of the "inner" ring of values on the dial, used for 24 /// hour input. final bool inner; /// Paints the text of the label. final TextPainter painter; /// Called when a tap gesture is detected on the label. final VoidCallback onTap; } class _DialPainter extends CustomPainter { _DialPainter({ required this.primaryLabels, required this.selectedLabels, required this.backgroundColor, required this.handColor, required this.handWidth, required this.dotColor, required this.dotRadius, required this.centerRadius, required this.theta, required this.radius, required this.textDirection, required this.selectedValue, }) : super(repaint: PaintingBinding.instance.systemFonts) { // TODO(polina-c): stop duplicating code across disposables // https://github.com/flutter/flutter/issues/137435 if (kFlutterMemoryAllocationsEnabled) { FlutterMemoryAllocations.instance.dispatchObjectCreated( library: 'package:flutter/material.dart', className: '$_DialPainter', object: this, ); } } final List<_TappableLabel> primaryLabels; final List<_TappableLabel> selectedLabels; final Color backgroundColor; final Color handColor; final double handWidth; final Color dotColor; final double dotRadius; final double centerRadius; final double theta; final double radius; final TextDirection textDirection; final int selectedValue; void dispose() { if (kFlutterMemoryAllocationsEnabled) { FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); } for (final _TappableLabel label in primaryLabels) { label.painter.dispose(); } for (final _TappableLabel label in selectedLabels) { label.painter.dispose(); } primaryLabels.clear(); selectedLabels.clear(); } @override void paint(Canvas canvas, Size size) { final double dialRadius = clampDouble(size.shortestSide / 2, _kTimePickerDialMinRadius + dotRadius, double.infinity); final double labelRadius = clampDouble(dialRadius - _kTimePickerDialPadding, _kTimePickerDialMinRadius, double.infinity); final double innerLabelRadius = clampDouble(labelRadius - _kTimePickerInnerDialOffset, 0, double.infinity); final double handleRadius = clampDouble(labelRadius - (radius < 0.5 ? 1 : 0) * (labelRadius - innerLabelRadius), _kTimePickerDialMinRadius, double.infinity); final Offset center = Offset(size.width / 2, size.height / 2); final Offset centerPoint = center; canvas.drawCircle(centerPoint, dialRadius, Paint()..color = backgroundColor); Offset getOffsetForTheta(double theta, double radius) { return center + Offset(radius * math.cos(theta), -radius * math.sin(theta)); } void paintLabels(List<_TappableLabel> labels, double radius) { if (labels.isEmpty) { return; } final double labelThetaIncrement = -_kTwoPi / labels.length; double labelTheta = math.pi / 2; for (final _TappableLabel label in labels) { final TextPainter labelPainter = label.painter; final Offset labelOffset = Offset(-labelPainter.width / 2, -labelPainter.height / 2); labelPainter.paint(canvas, getOffsetForTheta(labelTheta, radius) + labelOffset); labelTheta += labelThetaIncrement; } } void paintInnerOuterLabels(List<_TappableLabel>? labels) { if (labels == null) { return; } paintLabels(labels.where((_TappableLabel label) => !label.inner).toList(), labelRadius); paintLabels(labels.where((_TappableLabel label) => label.inner).toList(), innerLabelRadius); } paintInnerOuterLabels(primaryLabels); final Paint selectorPaint = Paint()..color = handColor; final Offset focusedPoint = getOffsetForTheta(theta, handleRadius); canvas.drawCircle(centerPoint, centerRadius, selectorPaint); canvas.drawCircle(focusedPoint, dotRadius, selectorPaint); selectorPaint.strokeWidth = handWidth; canvas.drawLine(centerPoint, focusedPoint, selectorPaint); // Add a dot inside the selector but only when it isn't over the labels. // This checks that the selector's theta is between two labels. A remainder // between 0.1 and 0.45 indicates that the selector is roughly not above any // labels. The values were derived by manually testing the dial. final double labelThetaIncrement = -_kTwoPi / primaryLabels.length; if (theta % labelThetaIncrement > 0.1 && theta % labelThetaIncrement < 0.45) { canvas.drawCircle(focusedPoint, 2, selectorPaint..color = dotColor); } final Rect focusedRect = Rect.fromCircle( center: focusedPoint, radius: dotRadius, ); canvas ..save() ..clipPath(Path()..addOval(focusedRect)); paintInnerOuterLabels(selectedLabels); canvas.restore(); } @override bool shouldRepaint(_DialPainter oldPainter) { return oldPainter.primaryLabels != primaryLabels || oldPainter.selectedLabels != selectedLabels || oldPainter.backgroundColor != backgroundColor || oldPainter.handColor != handColor || oldPainter.theta != theta; } } // Which kind of hour dial being presented. enum _HourDialType { twentyFourHour, twentyFourHourDoubleRing, twelveHour, } class _Dial extends StatefulWidget { const _Dial({ required this.selectedTime, required this.hourMinuteMode, required this.hourDialType, required this.onChanged, required this.onHourSelected, }); final TimeOfDay selectedTime; final _HourMinuteMode hourMinuteMode; final _HourDialType hourDialType; final ValueChanged<TimeOfDay>? onChanged; final VoidCallback? onHourSelected; @override _DialState createState() => _DialState(); } class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { late ThemeData themeData; late MaterialLocalizations localizations; _DialPainter? painter; late AnimationController _animationController; late Tween<double> _thetaTween; late Animation<double> _theta; late Tween<double> _radiusTween; late Animation<double> _radius; bool _dragging = false; @override void initState() { super.initState(); _animationController = AnimationController( duration: _kDialAnimateDuration, vsync: this, ); _thetaTween = Tween<double>(begin: _getThetaForTime(widget.selectedTime)); _radiusTween = Tween<double>(begin: _getRadiusForTime(widget.selectedTime)); _theta = _animationController .drive(CurveTween(curve: standardEasing)) .drive(_thetaTween) ..addListener(() => setState(() { /* _theta.value has changed */ })); _radius = _animationController .drive(CurveTween(curve: standardEasing)) .drive(_radiusTween) ..addListener(() => setState(() { /* _radius.value has changed */ })); } @override void didChangeDependencies() { super.didChangeDependencies(); assert(debugCheckHasMediaQuery(context)); themeData = Theme.of(context); localizations = MaterialLocalizations.of(context); } @override void didUpdateWidget(_Dial oldWidget) { super.didUpdateWidget(oldWidget); if (widget.hourMinuteMode != oldWidget.hourMinuteMode || widget.selectedTime != oldWidget.selectedTime) { if (!_dragging) { _animateTo(_getThetaForTime(widget.selectedTime), _getRadiusForTime(widget.selectedTime)); } } } @override void dispose() { _animationController.dispose(); painter?.dispose(); super.dispose(); } static double _nearest(double target, double a, double b) { return ((target - a).abs() < (target - b).abs()) ? a : b; } void _animateTo(double targetTheta, double targetRadius) { void animateToValue({ required double target, required Animation<double> animation, required Tween<double> tween, required AnimationController controller, required double min, required double max, }) { double beginValue = _nearest(target, animation.value, max); beginValue = _nearest(target, beginValue, min); tween ..begin = beginValue ..end = target; controller ..value = 0 ..forward(); } animateToValue( target: targetTheta, animation: _theta, tween: _thetaTween, controller: _animationController, min: _theta.value - _kTwoPi, max: _theta.value + _kTwoPi, ); animateToValue( target: targetRadius, animation: _radius, tween: _radiusTween, controller: _animationController, min: 0, max: 1, ); } double _getRadiusForTime(TimeOfDay time) { switch (widget.hourMinuteMode) { case _HourMinuteMode.hour: return switch (widget.hourDialType) { _HourDialType.twentyFourHourDoubleRing => time.hour >= 12 ? 0 : 1, _HourDialType.twentyFourHour || _HourDialType.twelveHour => 1, }; case _HourMinuteMode.minute: return 1; } } double _getThetaForTime(TimeOfDay time) { final int hoursFactor = switch (widget.hourDialType) { _HourDialType.twentyFourHour => TimeOfDay.hoursPerDay, _HourDialType.twentyFourHourDoubleRing => TimeOfDay.hoursPerPeriod, _HourDialType.twelveHour => TimeOfDay.hoursPerPeriod, }; final double fraction = switch (widget.hourMinuteMode) { _HourMinuteMode.hour => (time.hour / hoursFactor) % hoursFactor, _HourMinuteMode.minute => (time.minute / TimeOfDay.minutesPerHour) % TimeOfDay.minutesPerHour, }; return (math.pi / 2 - fraction * _kTwoPi) % _kTwoPi; } TimeOfDay _getTimeForTheta(double theta, {bool roundMinutes = false, required double radius}) { final double fraction = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1; switch (widget.hourMinuteMode) { case _HourMinuteMode.hour: int newHour; switch (widget.hourDialType) { case _HourDialType.twentyFourHour: newHour = (fraction * TimeOfDay.hoursPerDay).round() % TimeOfDay.hoursPerDay; case _HourDialType.twentyFourHourDoubleRing: newHour = (fraction * TimeOfDay.hoursPerPeriod).round() % TimeOfDay.hoursPerPeriod; if (radius < 0.5) { newHour = newHour + TimeOfDay.hoursPerPeriod; } case _HourDialType.twelveHour: newHour = (fraction * TimeOfDay.hoursPerPeriod).round() % TimeOfDay.hoursPerPeriod; newHour = newHour + widget.selectedTime.periodOffset; } return widget.selectedTime.replacing(hour: newHour); case _HourMinuteMode.minute: int minute = (fraction * TimeOfDay.minutesPerHour).round() % TimeOfDay.minutesPerHour; if (roundMinutes) { // Round the minutes to nearest 5 minute interval. minute = ((minute + 2) ~/ 5) * 5 % TimeOfDay.minutesPerHour; } return widget.selectedTime.replacing(minute: minute); } } TimeOfDay _notifyOnChangedIfNeeded({ bool roundMinutes = false }) { final TimeOfDay current = _getTimeForTheta(_theta.value, roundMinutes: roundMinutes, radius: _radius.value); if (widget.onChanged == null) { return current; } if (current != widget.selectedTime) { widget.onChanged!(current); } return current; } void _updateThetaForPan({ bool roundMinutes = false }) { setState(() { final Offset offset = _position! - _center!; final double labelRadius = _dialSize!.shortestSide / 2 - _kTimePickerDialPadding; final double innerRadius = labelRadius - _kTimePickerInnerDialOffset; double angle = (math.atan2(offset.dx, offset.dy) - math.pi / 2) % _kTwoPi; final double radius = clampDouble((offset.distance - innerRadius) / _kTimePickerInnerDialOffset, 0, 1); if (roundMinutes) { angle = _getThetaForTime(_getTimeForTheta(angle, roundMinutes: roundMinutes, radius: radius)); } // The controller doesn't animate during the pan gesture. _thetaTween ..begin = angle ..end = angle; _radiusTween ..begin = radius ..end = radius; }); } Offset? _position; Offset? _center; Size? _dialSize; void _handlePanStart(DragStartDetails details) { assert(!_dragging); _dragging = true; final RenderBox box = context.findRenderObject()! as RenderBox; _position = box.globalToLocal(details.globalPosition); _dialSize = box.size; _center = _dialSize!.center(Offset.zero); _updateThetaForPan(); _notifyOnChangedIfNeeded(); } void _handlePanUpdate(DragUpdateDetails details) { _position = _position! + details.delta; _updateThetaForPan(); _notifyOnChangedIfNeeded(); } void _handlePanEnd(DragEndDetails details) { assert(_dragging); _dragging = false; _position = null; _center = null; _dialSize = null; _animateTo(_getThetaForTime(widget.selectedTime), _getRadiusForTime(widget.selectedTime)); if (widget.hourMinuteMode == _HourMinuteMode.hour) { widget.onHourSelected?.call(); } } void _handleTapUp(TapUpDetails details) { final RenderBox box = context.findRenderObject()! as RenderBox; _position = box.globalToLocal(details.globalPosition); _center = box.size.center(Offset.zero); _dialSize = box.size; _updateThetaForPan(roundMinutes: true); final TimeOfDay newTime = _notifyOnChangedIfNeeded(roundMinutes: true); if (widget.hourMinuteMode == _HourMinuteMode.hour) { switch (widget.hourDialType) { case _HourDialType.twentyFourHour: case _HourDialType.twentyFourHourDoubleRing: _announceToAccessibility(context, localizations.formatDecimal(newTime.hour)); case _HourDialType.twelveHour: _announceToAccessibility(context, localizations.formatDecimal(newTime.hourOfPeriod)); } widget.onHourSelected?.call(); } else { _announceToAccessibility(context, localizations.formatDecimal(newTime.minute)); } final TimeOfDay time = _getTimeForTheta(_theta.value, roundMinutes: true, radius: _radius.value); _animateTo(_getThetaForTime(time), _getRadiusForTime(time)); _dragging = false; _position = null; _center = null; _dialSize = null; } void _selectHour(int hour) { _announceToAccessibility(context, localizations.formatDecimal(hour)); final TimeOfDay time; TimeOfDay getAmPmTime() { return switch (widget.selectedTime.period) { DayPeriod.am => TimeOfDay(hour: hour, minute: widget.selectedTime.minute), DayPeriod.pm => TimeOfDay(hour: hour + TimeOfDay.hoursPerPeriod, minute: widget.selectedTime.minute), }; } switch (widget.hourMinuteMode) { case _HourMinuteMode.hour: switch (widget.hourDialType) { case _HourDialType.twentyFourHour: case _HourDialType.twentyFourHourDoubleRing: time = TimeOfDay(hour: hour, minute: widget.selectedTime.minute); case _HourDialType.twelveHour: time = getAmPmTime(); } case _HourMinuteMode.minute: time = getAmPmTime(); } final double angle = _getThetaForTime(time); _thetaTween ..begin = angle ..end = angle; _notifyOnChangedIfNeeded(); } void _selectMinute(int minute) { _announceToAccessibility(context, localizations.formatDecimal(minute)); final TimeOfDay time = TimeOfDay( hour: widget.selectedTime.hour, minute: minute, ); final double angle = _getThetaForTime(time); _thetaTween ..begin = angle ..end = angle; _notifyOnChangedIfNeeded(); } static const List<TimeOfDay> _amHours = <TimeOfDay>[ TimeOfDay(hour: 12, minute: 0), TimeOfDay(hour: 1, minute: 0), TimeOfDay(hour: 2, minute: 0), TimeOfDay(hour: 3, minute: 0), TimeOfDay(hour: 4, minute: 0), TimeOfDay(hour: 5, minute: 0), TimeOfDay(hour: 6, minute: 0), TimeOfDay(hour: 7, minute: 0), TimeOfDay(hour: 8, minute: 0), TimeOfDay(hour: 9, minute: 0), TimeOfDay(hour: 10, minute: 0), TimeOfDay(hour: 11, minute: 0), ]; // On M2, there's no inner ring of numbers. static const List<TimeOfDay> _twentyFourHoursM2 = <TimeOfDay>[ TimeOfDay(hour: 0, minute: 0), TimeOfDay(hour: 2, minute: 0), TimeOfDay(hour: 4, minute: 0), TimeOfDay(hour: 6, minute: 0), TimeOfDay(hour: 8, minute: 0), TimeOfDay(hour: 10, minute: 0), TimeOfDay(hour: 12, minute: 0), TimeOfDay(hour: 14, minute: 0), TimeOfDay(hour: 16, minute: 0), TimeOfDay(hour: 18, minute: 0), TimeOfDay(hour: 20, minute: 0), TimeOfDay(hour: 22, minute: 0), ]; static const List<TimeOfDay> _twentyFourHours = <TimeOfDay>[ TimeOfDay(hour: 0, minute: 0), TimeOfDay(hour: 1, minute: 0), TimeOfDay(hour: 2, minute: 0), TimeOfDay(hour: 3, minute: 0), TimeOfDay(hour: 4, minute: 0), TimeOfDay(hour: 5, minute: 0), TimeOfDay(hour: 6, minute: 0), TimeOfDay(hour: 7, minute: 0), TimeOfDay(hour: 8, minute: 0), TimeOfDay(hour: 9, minute: 0), TimeOfDay(hour: 10, minute: 0), TimeOfDay(hour: 11, minute: 0), TimeOfDay(hour: 12, minute: 0), TimeOfDay(hour: 13, minute: 0), TimeOfDay(hour: 14, minute: 0), TimeOfDay(hour: 15, minute: 0), TimeOfDay(hour: 16, minute: 0), TimeOfDay(hour: 17, minute: 0), TimeOfDay(hour: 18, minute: 0), TimeOfDay(hour: 19, minute: 0), TimeOfDay(hour: 20, minute: 0), TimeOfDay(hour: 21, minute: 0), TimeOfDay(hour: 22, minute: 0), TimeOfDay(hour: 23, minute: 0), ]; _TappableLabel _buildTappableLabel({ required TextStyle? textStyle, required int selectedValue, required int value, required bool inner, required String label, required VoidCallback onTap, }) { return _TappableLabel( value: value, inner: inner, painter: TextPainter( text: TextSpan(style: textStyle, text: label), textDirection: TextDirection.ltr, textScaler: MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 2.0), )..layout(), onTap: onTap, ); } List<_TappableLabel> _build24HourRing({ required TextStyle? textStyle, required int selectedValue, }) { return <_TappableLabel>[ if (themeData.useMaterial3) for (final TimeOfDay timeOfDay in _twentyFourHours) _buildTappableLabel( textStyle: textStyle, selectedValue: selectedValue, inner: timeOfDay.hour >= 12, value: timeOfDay.hour, label: timeOfDay.hour != 0 ? '${timeOfDay.hour}' : localizations.formatHour(timeOfDay, alwaysUse24HourFormat: true), onTap: () { _selectHour(timeOfDay.hour); }, ), if (!themeData.useMaterial3) for (final TimeOfDay timeOfDay in _twentyFourHoursM2) _buildTappableLabel( textStyle: textStyle, selectedValue: selectedValue, inner: false, value: timeOfDay.hour, label: localizations.formatHour(timeOfDay, alwaysUse24HourFormat: true), onTap: () { _selectHour(timeOfDay.hour); }, ), ]; } List<_TappableLabel> _build12HourRing({ required TextStyle? textStyle, required int selectedValue, }) { return <_TappableLabel>[ for (final TimeOfDay timeOfDay in _amHours) _buildTappableLabel( textStyle: textStyle, selectedValue: selectedValue, inner: false, value: timeOfDay.hour, label: localizations.formatHour(timeOfDay, alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)), onTap: () { _selectHour(timeOfDay.hour); }, ), ]; } List<_TappableLabel> _buildMinutes({ required TextStyle? textStyle, required int selectedValue, }) { const List<TimeOfDay> minuteMarkerValues = <TimeOfDay>[ TimeOfDay(hour: 0, minute: 0), TimeOfDay(hour: 0, minute: 5), TimeOfDay(hour: 0, minute: 10), TimeOfDay(hour: 0, minute: 15), TimeOfDay(hour: 0, minute: 20), TimeOfDay(hour: 0, minute: 25), TimeOfDay(hour: 0, minute: 30), TimeOfDay(hour: 0, minute: 35), TimeOfDay(hour: 0, minute: 40), TimeOfDay(hour: 0, minute: 45), TimeOfDay(hour: 0, minute: 50), TimeOfDay(hour: 0, minute: 55), ]; return <_TappableLabel>[ for (final TimeOfDay timeOfDay in minuteMarkerValues) _buildTappableLabel( textStyle: textStyle, selectedValue: selectedValue, inner: false, value: timeOfDay.minute, label: localizations.formatMinute(timeOfDay), onTap: () { _selectMinute(timeOfDay.minute); }, ), ]; } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context); final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); final Color backgroundColor = timePickerTheme.dialBackgroundColor ?? defaultTheme.dialBackgroundColor; final Color dialHandColor = timePickerTheme.dialHandColor ?? defaultTheme.dialHandColor; final TextStyle labelStyle = timePickerTheme.dialTextStyle ?? defaultTheme.dialTextStyle; final Color dialTextUnselectedColor = MaterialStateProperty .resolveAs<Color>(timePickerTheme.dialTextColor ?? defaultTheme.dialTextColor, <MaterialState>{ }); final Color dialTextSelectedColor = MaterialStateProperty .resolveAs<Color>(timePickerTheme.dialTextColor ?? defaultTheme.dialTextColor, <MaterialState>{ MaterialState.selected }); final TextStyle resolvedUnselectedLabelStyle = labelStyle.copyWith(color: dialTextUnselectedColor); final TextStyle resolvedSelectedLabelStyle = labelStyle.copyWith(color: dialTextSelectedColor); final Color dotColor = dialTextSelectedColor; List<_TappableLabel> primaryLabels; List<_TappableLabel> selectedLabels; final int selectedDialValue; final double radiusValue; switch (widget.hourMinuteMode) { case _HourMinuteMode.hour: switch (widget.hourDialType) { case _HourDialType.twentyFourHour: case _HourDialType.twentyFourHourDoubleRing: selectedDialValue = widget.selectedTime.hour; primaryLabels = _build24HourRing( textStyle: resolvedUnselectedLabelStyle, selectedValue: selectedDialValue, ); selectedLabels = _build24HourRing( textStyle: resolvedSelectedLabelStyle, selectedValue: selectedDialValue, ); radiusValue = theme.useMaterial3 ? _radius.value : 1; case _HourDialType.twelveHour: selectedDialValue = widget.selectedTime.hourOfPeriod; primaryLabels = _build12HourRing( textStyle: resolvedUnselectedLabelStyle, selectedValue: selectedDialValue, ); selectedLabels = _build12HourRing( textStyle: resolvedSelectedLabelStyle, selectedValue: selectedDialValue, ); radiusValue = 1; } case _HourMinuteMode.minute: selectedDialValue = widget.selectedTime.minute; primaryLabels = _buildMinutes( textStyle: resolvedUnselectedLabelStyle, selectedValue: selectedDialValue, ); selectedLabels = _buildMinutes( textStyle: resolvedSelectedLabelStyle, selectedValue: selectedDialValue, ); radiusValue = 1; } painter?.dispose(); painter = _DialPainter( selectedValue: selectedDialValue, primaryLabels: primaryLabels, selectedLabels: selectedLabels, backgroundColor: backgroundColor, handColor: dialHandColor, handWidth: defaultTheme.handWidth, dotColor: dotColor, dotRadius: defaultTheme.dotRadius, centerRadius: defaultTheme.centerRadius, theta: _theta.value, radius: radiusValue, textDirection: Directionality.of(context), ); return GestureDetector( excludeFromSemantics: true, onPanStart: _handlePanStart, onPanUpdate: _handlePanUpdate, onPanEnd: _handlePanEnd, onTapUp: _handleTapUp, child: CustomPaint( key: const ValueKey<String>('time-picker-dial'), painter: painter, ), ); } } class _TimePickerInput extends StatefulWidget { const _TimePickerInput({ required this.initialSelectedTime, required this.errorInvalidText, required this.hourLabelText, required this.minuteLabelText, required this.helpText, required this.autofocusHour, required this.autofocusMinute, this.restorationId, }); /// The time initially selected when the dialog is shown. final TimeOfDay initialSelectedTime; /// Optionally provide your own validation error text. final String? errorInvalidText; /// Optionally provide your own hour label text. final String? hourLabelText; /// Optionally provide your own minute label text. final String? minuteLabelText; final String helpText; final bool? autofocusHour; final bool? autofocusMinute; /// Restoration ID to save and restore the state of the time picker input /// widget. /// /// If it is non-null, the widget will persist and restore its state /// /// The state of this widget is persisted in a [RestorationBucket] claimed /// from the surrounding [RestorationScope] using the provided restoration ID. final String? restorationId; @override _TimePickerInputState createState() => _TimePickerInputState(); } class _TimePickerInputState extends State<_TimePickerInput> with RestorationMixin { late final RestorableTimeOfDay _selectedTime = RestorableTimeOfDay(widget.initialSelectedTime); final RestorableBool hourHasError = RestorableBool(false); final RestorableBool minuteHasError = RestorableBool(false); @override void dispose() { _selectedTime.dispose(); hourHasError.dispose(); minuteHasError.dispose(); super.dispose(); } @override String? get restorationId => widget.restorationId; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_selectedTime, 'selected_time'); registerForRestoration(hourHasError, 'hour_has_error'); registerForRestoration(minuteHasError, 'minute_has_error'); } int? _parseHour(String? value) { if (value == null) { return null; } int? newHour = int.tryParse(value); if (newHour == null) { return null; } if (MediaQuery.alwaysUse24HourFormatOf(context)) { if (newHour >= 0 && newHour < 24) { return newHour; } } else { if (newHour > 0 && newHour < 13) { if ((_selectedTime.value.period == DayPeriod.pm && newHour != 12) || (_selectedTime.value.period == DayPeriod.am && newHour == 12)) { newHour = (newHour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay; } return newHour; } } return null; } int? _parseMinute(String? value) { if (value == null) { return null; } final int? newMinute = int.tryParse(value); if (newMinute == null) { return null; } if (newMinute >= 0 && newMinute < 60) { return newMinute; } return null; } void _handleHourSavedSubmitted(String? value) { final int? newHour = _parseHour(value); if (newHour != null) { _selectedTime.value = TimeOfDay(hour: newHour, minute: _selectedTime.value.minute); _TimePickerModel.setSelectedTime(context, _selectedTime.value); FocusScope.of(context).requestFocus(); } } void _handleHourChanged(String value) { final int? newHour = _parseHour(value); if (newHour != null && value.length == 2) { // If a valid hour is typed, move focus to the minute TextField. FocusScope.of(context).nextFocus(); } } void _handleMinuteSavedSubmitted(String? value) { final int? newMinute = _parseMinute(value); if (newMinute != null) { _selectedTime.value = TimeOfDay(hour: _selectedTime.value.hour, minute: int.parse(value!)); _TimePickerModel.setSelectedTime(context, _selectedTime.value); FocusScope.of(context).unfocus(); } } void _handleDayPeriodChanged(TimeOfDay value) { _selectedTime.value = value; _TimePickerModel.setSelectedTime(context, _selectedTime.value); } String? _validateHour(String? value) { final int? newHour = _parseHour(value); setState(() { hourHasError.value = newHour == null; }); // This is used as the validator for the [TextFormField]. // Returning an empty string allows the field to go into an error state. // Returning null means no error in the validation of the entered text. return newHour == null ? '' : null; } String? _validateMinute(String? value) { final int? newMinute = _parseMinute(value); setState(() { minuteHasError.value = newMinute == null; }); // This is used as the validator for the [TextFormField]. // Returning an empty string allows the field to go into an error state. // Returning null means no error in the validation of the entered text. return newMinute == null ? '' : null; } @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat(alwaysUse24HourFormat: _TimePickerModel.use24HourFormatOf(context)); final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h; final ThemeData theme = Theme.of(context); final TimePickerThemeData timePickerTheme = _TimePickerModel.themeOf(context); final _TimePickerDefaults defaultTheme = _TimePickerModel.defaultThemeOf(context); final TextStyle hourMinuteStyle = timePickerTheme.hourMinuteTextStyle ?? defaultTheme.hourMinuteTextStyle; return Padding( padding: _TimePickerModel.useMaterial3Of(context) ? EdgeInsets.zero : const EdgeInsets.symmetric(horizontal: 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding(padding: EdgeInsetsDirectional.only(bottom: _TimePickerModel.useMaterial3Of(context) ? 20 : 24), child: Text( widget.helpText, style: _TimePickerModel.themeOf(context).helpTextStyle ?? _TimePickerModel.defaultThemeOf(context).helpTextStyle, ), ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ if (!use24HourDials && timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) ...<Widget>[ Padding( padding: const EdgeInsetsDirectional.only(end: 12), child: _DayPeriodControl(onPeriodChanged: _handleDayPeriodChanged), ), ], Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.start, // Hour/minutes should not change positions in RTL locales. textDirection: TextDirection.ltr, children: <Widget>[ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.only(bottom: 10), child: _HourTextField( restorationId: 'hour_text_field', selectedTime: _selectedTime.value, style: hourMinuteStyle, autofocus: widget.autofocusHour, inputAction: TextInputAction.next, validator: _validateHour, onSavedSubmitted: _handleHourSavedSubmitted, onChanged: _handleHourChanged, hourLabelText: widget.hourLabelText, ), ), if (!hourHasError.value && !minuteHasError.value) ExcludeSemantics( child: Text( widget.hourLabelText ?? MaterialLocalizations.of(context).timePickerHourLabel, style: theme.textTheme.bodySmall, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ), _TimeSelectorSeparator(timeOfDayFormat: timeOfDayFormat), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.only(bottom: 10), child: _MinuteTextField( restorationId: 'minute_text_field', selectedTime: _selectedTime.value, style: hourMinuteStyle, autofocus: widget.autofocusMinute, inputAction: TextInputAction.done, validator: _validateMinute, onSavedSubmitted: _handleMinuteSavedSubmitted, minuteLabelText: widget.minuteLabelText, ), ), if (!hourHasError.value && !minuteHasError.value) ExcludeSemantics( child: Text( widget.minuteLabelText ?? MaterialLocalizations.of(context).timePickerMinuteLabel, style: theme.textTheme.bodySmall, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ), ], ), ), if (!use24HourDials && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) ...<Widget>[ Padding( padding: const EdgeInsetsDirectional.only(start: 12), child: _DayPeriodControl(onPeriodChanged: _handleDayPeriodChanged), ), ], ], ), if (hourHasError.value || minuteHasError.value) Text( widget.errorInvalidText ?? MaterialLocalizations.of(context).invalidTimeLabel, style: theme.textTheme.bodyMedium!.copyWith(color: theme.colorScheme.error), ) else const SizedBox(height: 2), ], ), ); } } class _HourTextField extends StatelessWidget { const _HourTextField({ required this.selectedTime, required this.style, required this.autofocus, required this.inputAction, required this.validator, required this.onSavedSubmitted, required this.onChanged, required this.hourLabelText, this.restorationId, }); final TimeOfDay selectedTime; final TextStyle style; final bool? autofocus; final TextInputAction inputAction; final FormFieldValidator<String> validator; final ValueChanged<String?> onSavedSubmitted; final ValueChanged<String> onChanged; final String? hourLabelText; final String? restorationId; @override Widget build(BuildContext context) { return _HourMinuteTextField( restorationId: restorationId, selectedTime: selectedTime, isHour: true, autofocus: autofocus, inputAction: inputAction, style: style, semanticHintText: hourLabelText ?? MaterialLocalizations.of(context).timePickerHourLabel, validator: validator, onSavedSubmitted: onSavedSubmitted, onChanged: onChanged, ); } } class _MinuteTextField extends StatelessWidget { const _MinuteTextField({ required this.selectedTime, required this.style, required this.autofocus, required this.inputAction, required this.validator, required this.onSavedSubmitted, required this.minuteLabelText, this.restorationId, }); final TimeOfDay selectedTime; final TextStyle style; final bool? autofocus; final TextInputAction inputAction; final FormFieldValidator<String> validator; final ValueChanged<String?> onSavedSubmitted; final String? minuteLabelText; final String? restorationId; @override Widget build(BuildContext context) { return _HourMinuteTextField( restorationId: restorationId, selectedTime: selectedTime, isHour: false, autofocus: autofocus, inputAction: inputAction, style: style, semanticHintText: minuteLabelText ?? MaterialLocalizations.of(context).timePickerMinuteLabel, validator: validator, onSavedSubmitted: onSavedSubmitted, ); } } class _HourMinuteTextField extends StatefulWidget { const _HourMinuteTextField({ required this.selectedTime, required this.isHour, required this.autofocus, required this.inputAction, required this.style, required this.semanticHintText, required this.validator, required this.onSavedSubmitted, this.restorationId, this.onChanged, }); final TimeOfDay selectedTime; final bool isHour; final bool? autofocus; final TextInputAction inputAction; final TextStyle style; final String semanticHintText; final FormFieldValidator<String> validator; final ValueChanged<String?> onSavedSubmitted; final ValueChanged<String>? onChanged; final String? restorationId; @override _HourMinuteTextFieldState createState() => _HourMinuteTextFieldState(); } class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with RestorationMixin { final RestorableTextEditingController controller = RestorableTextEditingController(); final RestorableBool controllerHasBeenSet = RestorableBool(false); late FocusNode focusNode; @override void initState() { super.initState(); focusNode = FocusNode() ..addListener(() { setState(() { // Rebuild when focus changes. }); }); } @override void didChangeDependencies() { super.didChangeDependencies(); // Only set the text value if it has not been populated with a localized // version yet. if (!controllerHasBeenSet.value) { controllerHasBeenSet.value = true; controller.value.text = _formattedValue; } } @override void dispose() { controller.dispose(); controllerHasBeenSet.dispose(); focusNode.dispose(); super.dispose(); } @override String? get restorationId => widget.restorationId; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(controller, 'text_editing_controller'); registerForRestoration(controllerHasBeenSet, 'has_controller_been_set'); } String get _formattedValue { final bool alwaysUse24HourFormat = MediaQuery.alwaysUse24HourFormatOf(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context); return !widget.isHour ? localizations.formatMinute(widget.selectedTime) : localizations.formatHour( widget.selectedTime, alwaysUse24HourFormat: alwaysUse24HourFormat, ); } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context); final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); final bool alwaysUse24HourFormat = MediaQuery.alwaysUse24HourFormatOf(context); final InputDecorationTheme inputDecorationTheme = timePickerTheme.inputDecorationTheme ?? defaultTheme.inputDecorationTheme; InputDecoration inputDecoration = const InputDecoration().applyDefaults(inputDecorationTheme); // Remove the hint text when focused because the centered cursor // appears odd above the hint text. final String? hintText = focusNode.hasFocus ? null : _formattedValue; // Because the fill color is specified in both the inputDecorationTheme and // the TimePickerTheme, if there's one in the user's input decoration theme, // use that. If not, but there's one in the user's // timePickerTheme.hourMinuteColor, use that, and otherwise use the default. // We ignore the value in the fillColor of the input decoration in the // default theme here, but it's the same as the hourMinuteColor. final Color startingFillColor = timePickerTheme.inputDecorationTheme?.fillColor ?? timePickerTheme.hourMinuteColor ?? defaultTheme.hourMinuteColor; final Color fillColor; if (theme.useMaterial3) { fillColor = MaterialStateProperty.resolveAs<Color>( startingFillColor, <MaterialState>{ if (focusNode.hasFocus) MaterialState.focused, if (focusNode.hasFocus) MaterialState.selected, }, ); } else { fillColor = focusNode.hasFocus ? Colors.transparent : startingFillColor; } inputDecoration = inputDecoration.copyWith( hintText: hintText, fillColor: fillColor, ); final Set<MaterialState> states = <MaterialState>{ if (focusNode.hasFocus) MaterialState.focused, if (focusNode.hasFocus) MaterialState.selected, }; final Color effectiveTextColor = MaterialStateProperty.resolveAs<Color>( timePickerTheme.hourMinuteTextColor ?? defaultTheme.hourMinuteTextColor, states, ); final TextStyle effectiveStyle = MaterialStateProperty.resolveAs<TextStyle>(widget.style, states) .copyWith(color: effectiveTextColor); return SizedBox.fromSize( size: alwaysUse24HourFormat ? defaultTheme.hourMinuteInputSize24Hour : defaultTheme.hourMinuteInputSize, child: MediaQuery.withNoTextScaling( child: UnmanagedRestorationScope( bucket: bucket, child: Semantics( label: widget.semanticHintText, child: TextFormField( restorationId: 'hour_minute_text_form_field', autofocus: widget.autofocus ?? false, expands: true, maxLines: null, inputFormatters: <TextInputFormatter>[ LengthLimitingTextInputFormatter(2), ], focusNode: focusNode, textAlign: TextAlign.center, textInputAction: widget.inputAction, keyboardType: TextInputType.number, style: effectiveStyle, controller: controller.value, decoration: inputDecoration, validator: widget.validator, onEditingComplete: () => widget.onSavedSubmitted(controller.value.text), onSaved: widget.onSavedSubmitted, onFieldSubmitted: widget.onSavedSubmitted, onChanged: widget.onChanged, ), ), ), ), ); } } /// Signature for when the time picker entry mode is changed. typedef EntryModeChangeCallback = void Function(TimePickerEntryMode mode); /// A Material Design time picker designed to appear inside a popup dialog. /// /// Pass this widget to [showDialog]. The value returned by [showDialog] is the /// selected [TimeOfDay] if the user taps the "OK" button, or null if the user /// taps the "CANCEL" button. The selected time is reported by calling /// [Navigator.pop]. /// /// Use [showTimePicker] to show a dialog already containing a [TimePickerDialog]. class TimePickerDialog extends StatefulWidget { /// Creates a Material Design time picker. const TimePickerDialog({ super.key, required this.initialTime, this.cancelText, this.confirmText, this.helpText, this.errorInvalidText, this.hourLabelText, this.minuteLabelText, this.restorationId, this.initialEntryMode = TimePickerEntryMode.dial, this.orientation, this.onEntryModeChanged, }); /// The time initially selected when the dialog is shown. final TimeOfDay initialTime; /// Optionally provide your own text for the cancel button. /// /// If null, the button uses [MaterialLocalizations.cancelButtonLabel]. final String? cancelText; /// Optionally provide your own text for the confirm button. /// /// If null, the button uses [MaterialLocalizations.okButtonLabel]. final String? confirmText; /// Optionally provide your own help text to the header of the time picker. final String? helpText; /// Optionally provide your own validation error text. final String? errorInvalidText; /// Optionally provide your own hour label text. final String? hourLabelText; /// Optionally provide your own minute label text. final String? minuteLabelText; /// Restoration ID to save and restore the state of the [TimePickerDialog]. /// /// If it is non-null, the time picker will persist and restore the /// dialog's state. /// /// The state of this widget is persisted in a [RestorationBucket] claimed /// from the surrounding [RestorationScope] using the provided restoration ID. /// /// See also: /// /// * [RestorationManager], which explains how state restoration works in /// Flutter. final String? restorationId; /// The entry mode for the picker. Whether it's text input or a dial. final TimePickerEntryMode initialEntryMode; /// The optional [orientation] parameter sets the [Orientation] to use when /// displaying the dialog. /// /// By default, the orientation is derived from the [MediaQueryData.size] of /// the ambient [MediaQuery]. If the aspect of the size is tall, then /// [Orientation.portrait] is used, if the size is wide, then /// [Orientation.landscape] is used. /// /// Use this parameter to override the default and force the dialog to appear /// in either portrait or landscape mode regardless of the aspect of the /// [MediaQueryData.size]. final Orientation? orientation; /// Callback called when the selected entry mode is changed. final EntryModeChangeCallback? onEntryModeChanged; @override State<TimePickerDialog> createState() => _TimePickerDialogState(); } class _TimePickerDialogState extends State<TimePickerDialog> with RestorationMixin { late final RestorableEnum<TimePickerEntryMode> _entryMode = RestorableEnum<TimePickerEntryMode>(widget.initialEntryMode, values: TimePickerEntryMode.values); late final RestorableTimeOfDay _selectedTime = RestorableTimeOfDay(widget.initialTime); final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final RestorableEnum<AutovalidateMode> _autovalidateMode = RestorableEnum<AutovalidateMode>(AutovalidateMode.disabled, values: AutovalidateMode.values); late final RestorableEnumN<Orientation> _orientation = RestorableEnumN<Orientation>(widget.orientation, values: Orientation.values); // Base sizes static const Size _kTimePickerPortraitSize = Size(310, 468); static const Size _kTimePickerLandscapeSize = Size(524, 342); static const Size _kTimePickerLandscapeSizeM2 = Size(508, 300); static const Size _kTimePickerInputSize = Size(312, 216); // Absolute minimum dialog sizes, which is the point at which it begins // scrolling to fit everything in. static const Size _kTimePickerMinPortraitSize = Size(238, 326); static const Size _kTimePickerMinLandscapeSize = Size(416, 248); static const Size _kTimePickerMinInputSize = Size(312, 196); @override void dispose() { _selectedTime.dispose(); _entryMode.dispose(); _autovalidateMode.dispose(); _orientation.dispose(); super.dispose(); } @override String? get restorationId => widget.restorationId; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_selectedTime, 'selected_time'); registerForRestoration(_entryMode, 'entry_mode'); registerForRestoration(_autovalidateMode, 'autovalidate_mode'); registerForRestoration(_orientation, 'orientation'); } void _handleTimeChanged(TimeOfDay value) { if (value != _selectedTime.value) { setState(() { _selectedTime.value = value; }); } } void _handleEntryModeChanged(TimePickerEntryMode value) { if (value != _entryMode.value) { setState(() { switch (_entryMode.value) { case TimePickerEntryMode.dial: _autovalidateMode.value = AutovalidateMode.disabled; case TimePickerEntryMode.input: _formKey.currentState!.save(); case TimePickerEntryMode.dialOnly: break; case TimePickerEntryMode.inputOnly: break; } _entryMode.value = value; widget.onEntryModeChanged?.call(value); }); } } void _toggleEntryMode() { switch (_entryMode.value) { case TimePickerEntryMode.dial: _handleEntryModeChanged(TimePickerEntryMode.input); case TimePickerEntryMode.input: _handleEntryModeChanged(TimePickerEntryMode.dial); case TimePickerEntryMode.dialOnly: case TimePickerEntryMode.inputOnly: FlutterError('Can not change entry mode from $_entryMode'); } } void _handleCancel() { Navigator.pop(context); } void _handleOk() { if (_entryMode.value == TimePickerEntryMode.input || _entryMode.value == TimePickerEntryMode.inputOnly) { final FormState form = _formKey.currentState!; if (!form.validate()) { setState(() { _autovalidateMode.value = AutovalidateMode.always; }); return; } form.save(); } Navigator.pop(context, _selectedTime.value); } Size _minDialogSize(BuildContext context, {required bool useMaterial3}) { final Orientation orientation = _orientation.value ?? MediaQuery.orientationOf(context); switch (_entryMode.value) { case TimePickerEntryMode.dial: case TimePickerEntryMode.dialOnly: return switch (orientation) { Orientation.portrait => _kTimePickerMinPortraitSize, Orientation.landscape => _kTimePickerMinLandscapeSize, }; case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: final MaterialLocalizations localizations = MaterialLocalizations.of(context); final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)); final double timePickerWidth; switch (timeOfDayFormat) { case TimeOfDayFormat.HH_colon_mm: case TimeOfDayFormat.HH_dot_mm: case TimeOfDayFormat.frenchCanadian: case TimeOfDayFormat.H_colon_mm: final _TimePickerDefaults defaultTheme = useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); timePickerWidth = _kTimePickerMinInputSize.width - defaultTheme.dayPeriodPortraitSize.width - 12; case TimeOfDayFormat.a_space_h_colon_mm: case TimeOfDayFormat.h_colon_mm_space_a: timePickerWidth = _kTimePickerMinInputSize.width - (useMaterial3 ? 32 : 0); } return Size(timePickerWidth, _kTimePickerMinInputSize.height); } } Size _dialogSize(BuildContext context, {required bool useMaterial3}) { final Orientation orientation = _orientation.value ?? MediaQuery.orientationOf(context); // Constrain the textScaleFactor to prevent layout issues. Since only some // parts of the time picker scale up with textScaleFactor, we cap the factor // to 1.1 as that provides enough space to reasonably fit all the content. // // 14 is a common font size used to compute the effective text scale. const double fontSizeToScale = 14.0; final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 1.1).scale(fontSizeToScale) / fontSizeToScale; final Size timePickerSize; switch (_entryMode.value) { case TimePickerEntryMode.dial: case TimePickerEntryMode.dialOnly: switch (orientation) { case Orientation.portrait: timePickerSize = _kTimePickerPortraitSize; case Orientation.landscape: timePickerSize = Size( _kTimePickerLandscapeSize.width * textScaleFactor, useMaterial3 ? _kTimePickerLandscapeSize.height : _kTimePickerLandscapeSizeM2.height ); } case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: final MaterialLocalizations localizations = MaterialLocalizations.of(context); final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)); final double timePickerWidth; switch (timeOfDayFormat) { case TimeOfDayFormat.HH_colon_mm: case TimeOfDayFormat.HH_dot_mm: case TimeOfDayFormat.frenchCanadian: case TimeOfDayFormat.H_colon_mm: final _TimePickerDefaults defaultTheme = useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); timePickerWidth = _kTimePickerInputSize.width - defaultTheme.dayPeriodPortraitSize.width - 12; case TimeOfDayFormat.a_space_h_colon_mm: case TimeOfDayFormat.h_colon_mm_space_a: timePickerWidth = _kTimePickerInputSize.width - (useMaterial3 ? 32 : 0); } timePickerSize = Size(timePickerWidth, _kTimePickerInputSize.height); } return Size(timePickerSize.width, timePickerSize.height * textScaleFactor); } @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); final ThemeData theme = Theme.of(context); final TimePickerThemeData pickerTheme = TimePickerTheme.of(context); final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); final ShapeBorder shape = pickerTheme.shape ?? defaultTheme.shape; final Color entryModeIconColor = pickerTheme.entryModeIconColor ?? defaultTheme.entryModeIconColor; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final Widget actions = Padding( padding: EdgeInsetsDirectional.only(start: theme.useMaterial3 ? 0 : 4), child: Row( children: <Widget>[ if (_entryMode.value == TimePickerEntryMode.dial || _entryMode.value == TimePickerEntryMode.input) IconButton( // In material3 mode, we want to use the color as part of the // button style which applies its own opacity. In material2 mode, // we want to use the color as the color, which already includes // the opacity. color: theme.useMaterial3 ? null : entryModeIconColor, style: theme.useMaterial3 ? IconButton.styleFrom(foregroundColor: entryModeIconColor) : null, onPressed: _toggleEntryMode, icon: Icon(_entryMode.value == TimePickerEntryMode.dial ? Icons.keyboard_outlined : Icons.access_time), tooltip: _entryMode.value == TimePickerEntryMode.dial ? MaterialLocalizations.of(context).inputTimeModeButtonLabel : MaterialLocalizations.of(context).dialModeButtonLabel, ), Expanded( child: Container( alignment: AlignmentDirectional.centerEnd, constraints: const BoxConstraints(minHeight: 36), child: OverflowBar( spacing: 8, overflowAlignment: OverflowBarAlignment.end, children: <Widget>[ TextButton( style: pickerTheme.cancelButtonStyle ?? defaultTheme.cancelButtonStyle, onPressed: _handleCancel, child: Text(widget.cancelText ?? (theme.useMaterial3 ? localizations.cancelButtonLabel : localizations.cancelButtonLabel.toUpperCase())), ), TextButton( style: pickerTheme.confirmButtonStyle ?? defaultTheme.confirmButtonStyle, onPressed: _handleOk, child: Text(widget.confirmText ?? localizations.okButtonLabel), ), ], ), ), ), ], ), ); final Offset tapTargetSizeOffset = switch (theme.materialTapTargetSize) { MaterialTapTargetSize.padded => Offset.zero, // _dialogSize returns "padded" sizes. MaterialTapTargetSize.shrinkWrap => const Offset(0, -12), }; final Size dialogSize = _dialogSize(context, useMaterial3: theme.useMaterial3) + tapTargetSizeOffset; final Size minDialogSize = _minDialogSize(context, useMaterial3: theme.useMaterial3) + tapTargetSizeOffset; return Dialog( shape: shape, elevation: pickerTheme.elevation ?? defaultTheme.elevation, backgroundColor: pickerTheme.backgroundColor ?? defaultTheme.backgroundColor, insetPadding: EdgeInsets.symmetric( horizontal: 16, vertical: (_entryMode.value == TimePickerEntryMode.input || _entryMode.value == TimePickerEntryMode.inputOnly) ? 0 : 24, ), child: Padding( padding: pickerTheme.padding ?? defaultTheme.padding, child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { final Size constrainedSize = constraints.constrain(dialogSize); final Size allowedSize = Size( constrainedSize.width < minDialogSize.width ? minDialogSize.width : constrainedSize.width, constrainedSize.height < minDialogSize.height ? minDialogSize.height : constrainedSize.height, ); return SingleChildScrollView( restorationId: 'time_picker_scroll_view_horizontal', scrollDirection: Axis.horizontal, child: SingleChildScrollView( restorationId: 'time_picker_scroll_view_vertical', child: AnimatedContainer( width: allowedSize.width, height: allowedSize.height, duration: _kDialogSizeAnimationDuration, curve: Curves.easeIn, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Expanded( child: Form( key: _formKey, autovalidateMode: _autovalidateMode.value, child: _TimePicker( time: widget.initialTime, onTimeChanged: _handleTimeChanged, helpText: widget.helpText, cancelText: widget.cancelText, confirmText: widget.confirmText, errorInvalidText: widget.errorInvalidText, hourLabelText: widget.hourLabelText, minuteLabelText: widget.minuteLabelText, restorationId: 'time_picker', entryMode: _entryMode.value, orientation: widget.orientation, onEntryModeChanged: _handleEntryModeChanged, ), ), ), actions, ], ), ), ), ); }), ), ); } } // The _TimePicker widget is constructed so that in the future we could expose // this as a public API for embedding time pickers into other non-dialog // widgets, once we're sure we want to support that. /// A Time Picker widget that can be embedded into another widget. class _TimePicker extends StatefulWidget { /// Creates a const Material Design time picker. const _TimePicker({ required this.time, required this.onTimeChanged, this.helpText, this.cancelText, this.confirmText, this.errorInvalidText, this.hourLabelText, this.minuteLabelText, this.restorationId, this.entryMode = TimePickerEntryMode.dial, this.orientation, this.onEntryModeChanged, }); /// Optionally provide your own text for the help text at the top of the /// control. /// /// If null, the widget uses [MaterialLocalizations.timePickerDialHelpText] /// when the [entryMode] is [TimePickerEntryMode.dial], and /// [MaterialLocalizations.timePickerInputHelpText] when the [entryMode] is /// [TimePickerEntryMode.input]. final String? helpText; /// Optionally provide your own text for the cancel button. /// /// If null, the button uses [MaterialLocalizations.cancelButtonLabel]. final String? cancelText; /// Optionally provide your own text for the confirm button. /// /// If null, the button uses [MaterialLocalizations.okButtonLabel]. final String? confirmText; /// Optionally provide your own validation error text. final String? errorInvalidText; /// Optionally provide your own hour label text. final String? hourLabelText; /// Optionally provide your own minute label text. final String? minuteLabelText; /// Restoration ID to save and restore the state of the [TimePickerDialog]. /// /// If it is non-null, the time picker will persist and restore the /// dialog's state. /// /// The state of this widget is persisted in a [RestorationBucket] claimed /// from the surrounding [RestorationScope] using the provided restoration ID. /// /// See also: /// /// * [RestorationManager], which explains how state restoration works in /// Flutter. final String? restorationId; /// The initial entry mode for the picker. Whether it's text input or a dial. final TimePickerEntryMode entryMode; /// The currently selected time of day. final TimeOfDay time; final ValueChanged<TimeOfDay>? onTimeChanged; /// The optional [orientation] parameter sets the [Orientation] to use when /// displaying the dialog. /// /// By default, the orientation is derived from the [MediaQueryData.size] of /// the ambient [MediaQuery]. If the aspect of the size is tall, then /// [Orientation.portrait] is used, if the size is wide, then /// [Orientation.landscape] is used. /// /// Use this parameter to override the default and force the dialog to appear /// in either portrait or landscape mode regardless of the aspect of the /// [MediaQueryData.size]. final Orientation? orientation; /// Callback called when the selected entry mode is changed. final EntryModeChangeCallback? onEntryModeChanged; @override State<_TimePicker> createState() => _TimePickerState(); } class _TimePickerState extends State<_TimePicker> with RestorationMixin { Timer? _vibrateTimer; late MaterialLocalizations localizations; final RestorableEnum<_HourMinuteMode> _hourMinuteMode = RestorableEnum<_HourMinuteMode>(_HourMinuteMode.hour, values: _HourMinuteMode.values); final RestorableEnumN<_HourMinuteMode> _lastModeAnnounced = RestorableEnumN<_HourMinuteMode>(null, values: _HourMinuteMode.values); final RestorableBoolN _autofocusHour = RestorableBoolN(null); final RestorableBoolN _autofocusMinute = RestorableBoolN(null); final RestorableBool _announcedInitialTime = RestorableBool(false); late final RestorableEnumN<Orientation> _orientation = RestorableEnumN<Orientation>(widget.orientation, values: Orientation.values); RestorableTimeOfDay get selectedTime => _selectedTime; late final RestorableTimeOfDay _selectedTime = RestorableTimeOfDay(widget.time); @override void dispose() { _vibrateTimer?.cancel(); _vibrateTimer = null; _orientation.dispose(); _selectedTime.dispose(); _hourMinuteMode.dispose(); _lastModeAnnounced.dispose(); _autofocusHour.dispose(); _autofocusMinute.dispose(); _announcedInitialTime.dispose(); super.dispose(); } @override void didChangeDependencies() { super.didChangeDependencies(); localizations = MaterialLocalizations.of(context); _announceInitialTimeOnce(); _announceModeOnce(); } @override void didUpdateWidget (_TimePicker oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.orientation != widget.orientation) { _orientation.value = widget.orientation; } if (oldWidget.time != widget.time) { _selectedTime.value = widget.time; } } void _setEntryMode(TimePickerEntryMode mode){ widget.onEntryModeChanged?.call(mode); } @override String? get restorationId => widget.restorationId; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_hourMinuteMode, 'hour_minute_mode'); registerForRestoration(_lastModeAnnounced, 'last_mode_announced'); registerForRestoration(_autofocusHour, 'autofocus_hour'); registerForRestoration(_autofocusMinute, 'autofocus_minute'); registerForRestoration(_announcedInitialTime, 'announced_initial_time'); registerForRestoration(_selectedTime, 'selected_time'); registerForRestoration(_orientation, 'orientation'); } void _vibrate() { switch (Theme.of(context).platform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: _vibrateTimer?.cancel(); _vibrateTimer = Timer(_kVibrateCommitDelay, () { HapticFeedback.vibrate(); _vibrateTimer = null; }); case TargetPlatform.iOS: case TargetPlatform.macOS: break; } } void _handleHourMinuteModeChanged(_HourMinuteMode mode) { _vibrate(); setState(() { _hourMinuteMode.value = mode; _announceModeOnce(); }); } void _handleEntryModeToggle() { setState(() { TimePickerEntryMode newMode = widget.entryMode; switch (widget.entryMode) { case TimePickerEntryMode.dial: newMode = TimePickerEntryMode.input; case TimePickerEntryMode.input: _autofocusHour.value = false; _autofocusMinute.value = false; newMode = TimePickerEntryMode.dial; case TimePickerEntryMode.dialOnly: case TimePickerEntryMode.inputOnly: FlutterError('Can not change entry mode from ${widget.entryMode}'); } _setEntryMode(newMode); }); } void _announceModeOnce() { if (_lastModeAnnounced.value == _hourMinuteMode.value) { // Already announced it. return; } switch (_hourMinuteMode.value) { case _HourMinuteMode.hour: _announceToAccessibility(context, localizations.timePickerHourModeAnnouncement); case _HourMinuteMode.minute: _announceToAccessibility(context, localizations.timePickerMinuteModeAnnouncement); } _lastModeAnnounced.value = _hourMinuteMode.value; } void _announceInitialTimeOnce() { if (_announcedInitialTime.value) { return; } final MaterialLocalizations localizations = MaterialLocalizations.of(context); _announceToAccessibility( context, localizations.formatTimeOfDay(_selectedTime.value, alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)), ); _announcedInitialTime.value = true; } void _handleTimeChanged(TimeOfDay value) { _vibrate(); setState(() { _selectedTime.value = value; widget.onTimeChanged?.call(value); }); } void _handleHourDoubleTapped() { _autofocusHour.value = true; _handleEntryModeToggle(); } void _handleMinuteDoubleTapped() { _autofocusMinute.value = true; _handleEntryModeToggle(); } void _handleHourSelected() { setState(() { _hourMinuteMode.value = _HourMinuteMode.minute; }); } @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)); final ThemeData theme = Theme.of(context); final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context, entryMode: widget.entryMode) : _TimePickerDefaultsM2(context); final Orientation orientation = _orientation.value ?? MediaQuery.orientationOf(context); final HourFormat timeOfDayHour = hourFormat(of: timeOfDayFormat); final _HourDialType hourMode = switch (timeOfDayHour) { HourFormat.HH || HourFormat.H when theme.useMaterial3 => _HourDialType.twentyFourHourDoubleRing, HourFormat.HH || HourFormat.H => _HourDialType.twentyFourHour, HourFormat.h => _HourDialType.twelveHour, }; final String helpText; final Widget picker; switch (widget.entryMode) { case TimePickerEntryMode.dial: case TimePickerEntryMode.dialOnly: helpText = widget.helpText ?? (theme.useMaterial3 ? localizations.timePickerDialHelpText : localizations.timePickerDialHelpText.toUpperCase()); final EdgeInsetsGeometry dialPadding = switch (orientation) { Orientation.portrait => const EdgeInsets.only(left: 12, right: 12, top: 36), Orientation.landscape => const EdgeInsetsDirectional.only(start: 64), }; final Widget dial = Padding( padding: dialPadding, child: ExcludeSemantics( child: SizedBox.fromSize( size: defaultTheme.dialSize, child: AspectRatio( aspectRatio: 1, child: _Dial( hourMinuteMode: _hourMinuteMode.value, hourDialType: hourMode, selectedTime: _selectedTime.value, onChanged: _handleTimeChanged, onHourSelected: _handleHourSelected, ), ), ), ), ); switch (orientation) { case Orientation.portrait: picker = Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Padding( padding: EdgeInsets.symmetric(horizontal: theme.useMaterial3 ? 0 : 16), child: _TimePickerHeader(helpText: helpText), ), Expanded( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ // Dial grows and shrinks with the available space. Expanded( child: Padding( padding: EdgeInsets.symmetric(horizontal: theme.useMaterial3 ? 0 : 16), child: dial, ), ), ], ), ), ], ); case Orientation.landscape: picker = Column( children: <Widget>[ Expanded( child: Padding( padding: EdgeInsets.symmetric(horizontal: theme.useMaterial3 ? 0 : 16), child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ _TimePickerHeader(helpText: helpText), Expanded(child: dial), ], ), ), ), ], ); } case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: final String helpText = widget.helpText ?? (theme.useMaterial3 ? localizations.timePickerInputHelpText : localizations.timePickerInputHelpText.toUpperCase()); picker = Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ _TimePickerInput( initialSelectedTime: _selectedTime.value, errorInvalidText: widget.errorInvalidText, hourLabelText: widget.hourLabelText, minuteLabelText: widget.minuteLabelText, helpText: helpText, autofocusHour: _autofocusHour.value, autofocusMinute: _autofocusMinute.value, restorationId: 'time_picker_input', ), ], ); } return _TimePickerModel( entryMode: widget.entryMode, selectedTime: _selectedTime.value, hourMinuteMode: _hourMinuteMode.value, orientation: orientation, onHourMinuteModeChanged: _handleHourMinuteModeChanged, onHourDoubleTapped: _handleHourDoubleTapped, onMinuteDoubleTapped: _handleMinuteDoubleTapped, hourDialType: hourMode, onSelectedTimeChanged: _handleTimeChanged, useMaterial3: theme.useMaterial3, use24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context), theme: TimePickerTheme.of(context), defaultTheme: defaultTheme, child: picker, ); } } /// Shows a dialog containing a Material Design time picker. /// /// The returned Future resolves to the time selected by the user when the user /// closes the dialog. If the user cancels the dialog, null is returned. /// /// {@tool snippet} Show a dialog with [initialTime] equal to the current time. /// /// ```dart /// Future<TimeOfDay?> selectedTime = showTimePicker( /// initialTime: TimeOfDay.now(), /// context: context, /// ); /// ``` /// {@end-tool} /// /// The [context], [barrierDismissible], [barrierColor], [barrierLabel], /// [useRootNavigator] and [routeSettings] arguments are passed to [showDialog], /// the documentation for which discusses how it is used. /// /// The [builder] parameter can be used to wrap the dialog widget to add /// inherited widgets like [Localizations.override], [Directionality], or /// [MediaQuery]. /// /// The `initialEntryMode` parameter can be used to determine the initial time /// entry selection of the picker (either a clock dial or text input). /// /// Optional strings for the [helpText], [cancelText], [errorInvalidText], /// [hourLabelText], [minuteLabelText] and [confirmText] can be provided to /// override the default values. /// /// The optional [orientation] parameter sets the [Orientation] to use when /// displaying the dialog. By default, the orientation is derived from the /// [MediaQueryData.size] of the ambient [MediaQuery]: wide sizes use the /// landscape orientation, and tall sizes use the portrait orientation. Use this /// parameter to override the default and force the dialog to appear in either /// portrait or landscape mode. /// /// {@macro flutter.widgets.RawDialogRoute} /// /// By default, the time picker gets its colors from the overall theme's /// [ColorScheme]. The time picker can be further customized by providing a /// [TimePickerThemeData] to the overall theme. /// /// {@tool snippet} Show a dialog with the text direction overridden to be /// [TextDirection.rtl]. /// /// ```dart /// Future<TimeOfDay?> selectedTimeRTL = showTimePicker( /// context: context, /// initialTime: TimeOfDay.now(), /// builder: (BuildContext context, Widget? child) { /// return Directionality( /// textDirection: TextDirection.rtl, /// child: child!, /// ); /// }, /// ); /// ``` /// {@end-tool} /// /// {@tool snippet} Show a dialog with time unconditionally displayed in 24 hour /// format. /// /// ```dart /// Future<TimeOfDay?> selectedTime24Hour = showTimePicker( /// context: context, /// initialTime: const TimeOfDay(hour: 10, minute: 47), /// builder: (BuildContext context, Widget? child) { /// return MediaQuery( /// data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true), /// child: child!, /// ); /// }, /// ); /// ``` /// {@end-tool} /// /// {@tool dartpad} /// This example illustrates how to open a time picker, and allows exploring /// some of the variations in the types of time pickers that may be shown. /// /// ** See code in examples/api/lib/material/time_picker/show_time_picker.0.dart ** /// {@end-tool} /// /// See also: /// /// * [showDatePicker], which shows a dialog that contains a Material Design /// date picker. /// * [TimePickerThemeData], which allows you to customize the colors, /// typography, and shape of the time picker. /// * [DisplayFeatureSubScreen], which documents the specifics of how /// [DisplayFeature]s can split the screen into sub-screens. Future<TimeOfDay?> showTimePicker({ required BuildContext context, required TimeOfDay initialTime, TransitionBuilder? builder, bool barrierDismissible = true, Color? barrierColor, String? barrierLabel, bool useRootNavigator = true, TimePickerEntryMode initialEntryMode = TimePickerEntryMode.dial, String? cancelText, String? confirmText, String? helpText, String? errorInvalidText, String? hourLabelText, String? minuteLabelText, RouteSettings? routeSettings, EntryModeChangeCallback? onEntryModeChanged, Offset? anchorPoint, Orientation? orientation, }) async { assert(debugCheckHasMaterialLocalizations(context)); final Widget dialog = TimePickerDialog( initialTime: initialTime, initialEntryMode: initialEntryMode, cancelText: cancelText, confirmText: confirmText, helpText: helpText, errorInvalidText: errorInvalidText, hourLabelText: hourLabelText, minuteLabelText: minuteLabelText, orientation: orientation, onEntryModeChanged: onEntryModeChanged, ); return showDialog<TimeOfDay>( context: context, barrierDismissible: barrierDismissible, barrierColor: barrierColor, barrierLabel: barrierLabel, useRootNavigator: useRootNavigator, builder: (BuildContext context) { return builder == null ? dialog : builder(context, dialog); }, routeSettings: routeSettings, anchorPoint: anchorPoint, ); } void _announceToAccessibility(BuildContext context, String message) { SemanticsService.announce(message, Directionality.of(context)); } // An abstract base class for the M2 and M3 defaults below, so that their return // types can be non-nullable. abstract class _TimePickerDefaults extends TimePickerThemeData { @override Color get backgroundColor; @override ButtonStyle get cancelButtonStyle; @override ButtonStyle get confirmButtonStyle; @override BorderSide get dayPeriodBorderSide; @override Color get dayPeriodColor; @override OutlinedBorder get dayPeriodShape; Size get dayPeriodInputSize; Size get dayPeriodLandscapeSize; Size get dayPeriodPortraitSize; @override Color get dayPeriodTextColor; @override TextStyle get dayPeriodTextStyle; @override Color get dialBackgroundColor; @override Color get dialHandColor; // Sizes that are generated from the tokens, but these aren't ones we're ready // to expose in the theme. Size get dialSize; double get handWidth; double get dotRadius; double get centerRadius; @override Color get dialTextColor; @override TextStyle get dialTextStyle; @override double get elevation; @override Color get entryModeIconColor; @override TextStyle get helpTextStyle; @override Color get hourMinuteColor; @override ShapeBorder get hourMinuteShape; Size get hourMinuteSize; Size get hourMinuteSize24Hour; Size get hourMinuteInputSize; Size get hourMinuteInputSize24Hour; @override Color get hourMinuteTextColor; @override TextStyle get hourMinuteTextStyle; @override InputDecorationTheme get inputDecorationTheme; @override EdgeInsetsGeometry get padding; @override ShapeBorder get shape; } // These theme defaults are not auto-generated: they match the values for the // Material 2 spec, which are not expected to change. class _TimePickerDefaultsM2 extends _TimePickerDefaults { _TimePickerDefaultsM2(this.context) : super(); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; static const OutlinedBorder _kDefaultShape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4))); @override Color get backgroundColor { return _colors.surface; } @override ButtonStyle get cancelButtonStyle { return TextButton.styleFrom(); } @override ButtonStyle get confirmButtonStyle { return TextButton.styleFrom(); } @override BorderSide get dayPeriodBorderSide { return BorderSide( color: Color.alphaBlend(_colors.onSurface.withOpacity(0.38), _colors.surface), ); } @override Color get dayPeriodColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return _colors.primary.withOpacity(_colors.brightness == Brightness.dark ? 0.24 : 0.12); } // The unselected day period should match the overall picker dialog color. // Making it transparent enables that without being redundant and allows // the optional elevation overlay for dark mode to be visible. return Colors.transparent; }); } @override OutlinedBorder get dayPeriodShape { return _kDefaultShape; } @override Size get dayPeriodPortraitSize { return const Size(52, 80); } @override Size get dayPeriodLandscapeSize { return const Size(0, 40); } @override Size get dayPeriodInputSize { return const Size(52, 70); } @override Color get dayPeriodTextColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { return states.contains(MaterialState.selected) ? _colors.primary : _colors.onSurface.withOpacity(0.60); }); } @override TextStyle get dayPeriodTextStyle { return _textTheme.titleMedium!.copyWith(color: dayPeriodTextColor); } @override Color get dialBackgroundColor { return _colors.onSurface.withOpacity(_colors.brightness == Brightness.dark ? 0.12 : 0.08); } @override Color get dialHandColor { return _colors.primary; } @override Size get dialSize { return const Size.square(280); } @override double get handWidth { return 2; } @override double get dotRadius { return 22; } @override double get centerRadius { return 4; } @override Color get dialTextColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return _colors.surface; } return _colors.onSurface; }); } @override TextStyle get dialTextStyle { return _textTheme.bodyLarge!; } @override double get elevation { return 6; } @override Color get entryModeIconColor { return _colors.onSurface.withOpacity(_colors.brightness == Brightness.dark ? 1.0 : 0.6); } @override TextStyle get helpTextStyle { return _textTheme.labelSmall!; } @override Color get hourMinuteColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { return states.contains(MaterialState.selected) ? _colors.primary.withOpacity(_colors.brightness == Brightness.dark ? 0.24 : 0.12) : _colors.onSurface.withOpacity(0.12); }); } @override ShapeBorder get hourMinuteShape { return _kDefaultShape; } @override Size get hourMinuteSize { return const Size(96, 80); } @override Size get hourMinuteSize24Hour { return const Size(114, 80); } @override Size get hourMinuteInputSize { return const Size(96, 70); } @override Size get hourMinuteInputSize24Hour { return const Size(114, 70); } @override Color get hourMinuteTextColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { return states.contains(MaterialState.selected) ? _colors.primary : _colors.onSurface; }); } @override TextStyle get hourMinuteTextStyle { return _textTheme.displayMedium!; } Color get _hourMinuteInputColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { return states.contains(MaterialState.selected) ? Colors.transparent : _colors.onSurface.withOpacity(0.12); }); } @override InputDecorationTheme get inputDecorationTheme { return InputDecorationTheme( contentPadding: EdgeInsets.zero, filled: true, fillColor: _hourMinuteInputColor, focusColor: Colors.transparent, enabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.transparent), ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: _colors.error, width: 2), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: _colors.primary, width: 2), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: _colors.error, width: 2), ), hintStyle: hourMinuteTextStyle.copyWith(color: _colors.onSurface.withOpacity(0.36)), // Prevent the error text from appearing. // TODO(rami-a): Remove this workaround once // https://github.com/flutter/flutter/issues/54104 // is fixed. errorStyle: const TextStyle(fontSize: 0, height: 0), ); } @override EdgeInsetsGeometry get padding { return const EdgeInsets.fromLTRB(8, 18, 8, 8); } @override ShapeBorder get shape { return _kDefaultShape; } } // BEGIN GENERATED TOKEN PROPERTIES - TimePicker // 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 _TimePickerDefaultsM3 extends _TimePickerDefaults { _TimePickerDefaultsM3(this.context, { this.entryMode = TimePickerEntryMode.dial }); final BuildContext context; final TimePickerEntryMode entryMode; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; @override Color get backgroundColor { return _colors.surfaceContainerHigh; } @override ButtonStyle get cancelButtonStyle { return TextButton.styleFrom(); } @override ButtonStyle get confirmButtonStyle { return TextButton.styleFrom(); } @override BorderSide get dayPeriodBorderSide { return BorderSide(color: _colors.outline); } @override Color get dayPeriodColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return _colors.tertiaryContainer; } // The unselected day period should match the overall picker dialog color. // Making it transparent enables that without being redundant and allows // the optional elevation overlay for dark mode to be visible. return Colors.transparent; }); } @override OutlinedBorder get dayPeriodShape { return const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))).copyWith(side: dayPeriodBorderSide); } @override Size get dayPeriodPortraitSize { return const Size(52, 80); } @override Size get dayPeriodLandscapeSize { return const Size(216, 38); } @override Size get dayPeriodInputSize { // Input size is eight pixels smaller than the portrait size in the spec, // but there's not token for it yet. return Size(dayPeriodPortraitSize.width, dayPeriodPortraitSize.height - 8); } @override Color get dayPeriodTextColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.focused)) { return _colors.onTertiaryContainer; } if (states.contains(MaterialState.hovered)) { return _colors.onTertiaryContainer; } if (states.contains(MaterialState.pressed)) { return _colors.onTertiaryContainer; } return _colors.onTertiaryContainer; } if (states.contains(MaterialState.focused)) { return _colors.onSurfaceVariant; } if (states.contains(MaterialState.hovered)) { return _colors.onSurfaceVariant; } if (states.contains(MaterialState.pressed)) { return _colors.onSurfaceVariant; } return _colors.onSurfaceVariant; }); } @override TextStyle get dayPeriodTextStyle { return _textTheme.titleMedium!.copyWith(color: dayPeriodTextColor); } @override Color get dialBackgroundColor { return _colors.surfaceContainerHighest; } @override Color get dialHandColor { return _colors.primary; } @override Size get dialSize { return const Size.square(256.0); } @override double get handWidth { return const Size(2, double.infinity).width; } @override double get dotRadius { return const Size.square(48.0).width / 2; } @override double get centerRadius { return const Size.square(8.0).width / 2; } @override Color get dialTextColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return _colors.onPrimary; } return _colors.onSurface; }); } @override TextStyle get dialTextStyle { return _textTheme.bodyLarge!; } @override double get elevation { return 6.0; } @override Color get entryModeIconColor { return _colors.onSurface; } @override TextStyle get helpTextStyle { return MaterialStateTextStyle.resolveWith((Set<MaterialState> states) { final TextStyle textStyle = _textTheme.labelMedium!; return textStyle.copyWith(color: _colors.onSurfaceVariant); }); } @override EdgeInsetsGeometry get padding { return const EdgeInsets.all(24); } @override Color get hourMinuteColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { Color overlayColor = _colors.primaryContainer; if (states.contains(MaterialState.pressed)) { overlayColor = _colors.onPrimaryContainer; } else if (states.contains(MaterialState.hovered)) { const double hoverOpacity = 0.08; overlayColor = _colors.onPrimaryContainer.withOpacity(hoverOpacity); } else if (states.contains(MaterialState.focused)) { const double focusOpacity = 0.1; overlayColor = _colors.onPrimaryContainer.withOpacity(focusOpacity); } return Color.alphaBlend(overlayColor, _colors.primaryContainer); } else { Color overlayColor = _colors.surfaceContainerHighest; if (states.contains(MaterialState.pressed)) { overlayColor = _colors.onSurface; } else if (states.contains(MaterialState.hovered)) { const double hoverOpacity = 0.08; overlayColor = _colors.onSurface.withOpacity(hoverOpacity); } else if (states.contains(MaterialState.focused)) { const double focusOpacity = 0.1; overlayColor = _colors.onSurface.withOpacity(focusOpacity); } return Color.alphaBlend(overlayColor, _colors.surfaceContainerHighest); } }); } @override ShapeBorder get hourMinuteShape { return const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))); } @override Size get hourMinuteSize { return const Size(96, 80); } @override Size get hourMinuteSize24Hour { return Size(const Size(114, double.infinity).width, hourMinuteSize.height); } @override Size get hourMinuteInputSize { // Input size is eight pixels smaller than the regular size in the spec, but // there's not token for it yet. return Size(hourMinuteSize.width, hourMinuteSize.height - 8); } @override Size get hourMinuteInputSize24Hour { // Input size is eight pixels smaller than the regular size in the spec, but // there's not token for it yet. return Size(hourMinuteSize24Hour.width, hourMinuteSize24Hour.height - 8); } @override Color get hourMinuteTextColor { return MaterialStateColor.resolveWith((Set<MaterialState> states) { return _hourMinuteTextColor.resolve(states); }); } MaterialStateProperty<Color> get _hourMinuteTextColor { return MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { return _colors.onPrimaryContainer; } if (states.contains(MaterialState.hovered)) { return _colors.onPrimaryContainer; } if (states.contains(MaterialState.focused)) { return _colors.onPrimaryContainer; } return _colors.onPrimaryContainer; } else { // unselected if (states.contains(MaterialState.pressed)) { return _colors.onSurface; } if (states.contains(MaterialState.hovered)) { return _colors.onSurface; } if (states.contains(MaterialState.focused)) { return _colors.onSurface; } return _colors.onSurface; } }); } @override TextStyle get hourMinuteTextStyle { return MaterialStateTextStyle.resolveWith((Set<MaterialState> states) { // TODO(tahatesser): Update this when https://github.com/flutter/flutter/issues/131247 is fixed. // This is using the correct text style from Material 3 spec. // https://m3.material.io/components/time-pickers/specs#fd0b6939-edab-4058-82e1-93d163945215 return switch (entryMode) { TimePickerEntryMode.dial || TimePickerEntryMode.dialOnly => _textTheme.displayLarge!.copyWith(color: _hourMinuteTextColor.resolve(states)), TimePickerEntryMode.input || TimePickerEntryMode.inputOnly => _textTheme.displayMedium!.copyWith(color: _hourMinuteTextColor.resolve(states)), }; }); } @override InputDecorationTheme get inputDecorationTheme { // This is NOT correct, but there's no token for // 'time-input.container.shape', so this is using the radius from the shape // for the hour/minute selector. It's a BorderRadiusGeometry, so we have to // resolve it before we can use it. final BorderRadius selectorRadius = const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))) .borderRadius .resolve(Directionality.of(context)); return InputDecorationTheme( contentPadding: EdgeInsets.zero, filled: true, // This should be derived from a token, but there isn't one for 'time-input'. fillColor: hourMinuteColor, // This should be derived from a token, but there isn't one for 'time-input'. focusColor: _colors.primaryContainer, enabledBorder: OutlineInputBorder( borderRadius: selectorRadius, borderSide: const BorderSide(color: Colors.transparent), ), errorBorder: OutlineInputBorder( borderRadius: selectorRadius, borderSide: BorderSide(color: _colors.error, width: 2), ), focusedBorder: OutlineInputBorder( borderRadius: selectorRadius, borderSide: BorderSide(color: _colors.primary, width: 2), ), focusedErrorBorder: OutlineInputBorder( borderRadius: selectorRadius, borderSide: BorderSide(color: _colors.error, width: 2), ), hintStyle: hourMinuteTextStyle.copyWith(color: _colors.onSurface.withOpacity(0.36)), // Prevent the error text from appearing. // TODO(rami-a): Remove this workaround once // https://github.com/flutter/flutter/issues/54104 // is fixed. errorStyle: const TextStyle(fontSize: 0, height: 0), ); } @override ShapeBorder get shape { return const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))); } @override MaterialStateProperty<Color?>? get timeSelectorSeparatorColor { // TODO(tahatesser): Update this when tokens are available. // This is taken from https://m3.material.io/components/time-pickers/specs. return MaterialStatePropertyAll<Color>(_colors.onSurface); } @override MaterialStateProperty<TextStyle?>? get timeSelectorSeparatorTextStyle { // TODO(tahatesser): Update this when tokens are available. // This is taken from https://m3.material.io/components/time-pickers/specs. return MaterialStatePropertyAll<TextStyle?>(_textTheme.displayLarge); } } // END GENERATED TOKEN PROPERTIES - TimePicker
flutter/packages/flutter/lib/src/material/time_picker.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/time_picker.dart", "repo_id": "flutter", "token_count": 49890 }
680
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'basic_types.dart'; /// Base class for [BorderRadius] that allows for text-direction aware resolution. /// /// A property or argument of this type accepts classes created either with [ /// BorderRadius.only] and its variants, or [BorderRadiusDirectional.only] /// and its variants. /// /// To convert a [BorderRadiusGeometry] object of indeterminate type into a /// [BorderRadius] object, call the [resolve] method. @immutable abstract class BorderRadiusGeometry { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const BorderRadiusGeometry(); Radius get _topLeft; Radius get _topRight; Radius get _bottomLeft; Radius get _bottomRight; Radius get _topStart; Radius get _topEnd; Radius get _bottomStart; Radius get _bottomEnd; /// Returns the difference between two [BorderRadiusGeometry] objects. /// /// If you know you are applying this to two [BorderRadius] or two /// [BorderRadiusDirectional] objects, consider using the binary infix `-` /// operator instead, which always returns an object of the same type as the /// operands, and is typed accordingly. /// /// If [subtract] is applied to two objects of the same type ([BorderRadius] or /// [BorderRadiusDirectional]), an object of that type will be returned (though /// this is not reflected in the type system). Otherwise, an object /// representing a combination of both is returned. That object can be turned /// into a concrete [BorderRadius] using [resolve]. /// /// This method returns the same result as [add] applied to the result of /// negating the argument (using the prefix unary `-` operator or multiplying /// the argument by -1.0 using the `*` operator). BorderRadiusGeometry subtract(BorderRadiusGeometry other) { return _MixedBorderRadius( _topLeft - other._topLeft, _topRight - other._topRight, _bottomLeft - other._bottomLeft, _bottomRight - other._bottomRight, _topStart - other._topStart, _topEnd - other._topEnd, _bottomStart - other._bottomStart, _bottomEnd - other._bottomEnd, ); } /// Returns the sum of two [BorderRadiusGeometry] objects. /// /// If you know you are adding two [BorderRadius] or two [BorderRadiusDirectional] /// objects, consider using the `+` operator instead, which always returns an /// object of the same type as the operands, and is typed accordingly. /// /// If [add] is applied to two objects of the same type ([BorderRadius] or /// [BorderRadiusDirectional]), an object of that type will be returned (though /// this is not reflected in the type system). Otherwise, an object /// representing a combination of both is returned. That object can be turned /// into a concrete [BorderRadius] using [resolve]. BorderRadiusGeometry add(BorderRadiusGeometry other) { return _MixedBorderRadius( _topLeft + other._topLeft, _topRight + other._topRight, _bottomLeft + other._bottomLeft, _bottomRight + other._bottomRight, _topStart + other._topStart, _topEnd + other._topEnd, _bottomStart + other._bottomStart, _bottomEnd + other._bottomEnd, ); } /// Returns the [BorderRadiusGeometry] object with each corner radius negated. /// /// This is the same as multiplying the object by -1.0. /// /// This operator returns an object of the same type as the operand. BorderRadiusGeometry operator -(); /// Scales the [BorderRadiusGeometry] object's corners by the given factor. /// /// This operator returns an object of the same type as the operand. BorderRadiusGeometry operator *(double other); /// Divides the [BorderRadiusGeometry] object's corners by the given factor. /// /// This operator returns an object of the same type as the operand. BorderRadiusGeometry operator /(double other); /// Integer divides the [BorderRadiusGeometry] object's corners by the given factor. /// /// This operator returns an object of the same type as the operand. /// /// This operator may have unexpected results when applied to a mixture of /// [BorderRadius] and [BorderRadiusDirectional] objects. BorderRadiusGeometry operator ~/(double other); /// Computes the remainder of each corner by the given factor. /// /// This operator returns an object of the same type as the operand. /// /// This operator may have unexpected results when applied to a mixture of /// [BorderRadius] and [BorderRadiusDirectional] objects. BorderRadiusGeometry operator %(double other); /// Linearly interpolate between two [BorderRadiusGeometry] objects. /// /// If either is null, this function interpolates from [BorderRadius.zero], /// and the result is an object of the same type as the non-null argument. (If /// both are null, this returns null.) /// /// If [lerp] is applied to two objects of the same type ([BorderRadius] or /// [BorderRadiusDirectional]), an object of that type will be returned (though /// this is not reflected in the type system). Otherwise, an object /// representing a combination of both is returned. That object can be turned /// into a concrete [BorderRadius] using [resolve]. /// /// {@macro dart.ui.shadow.lerp} static BorderRadiusGeometry? lerp(BorderRadiusGeometry? a, BorderRadiusGeometry? b, double t) { if (identical(a, b)) { return a; } a ??= BorderRadius.zero; b ??= BorderRadius.zero; return a.add((b.subtract(a)) * t); } /// Convert this instance into a [BorderRadius], so that the radii are /// expressed for specific physical corners (top-left, top-right, etc) rather /// than in a direction-dependent manner. /// /// See also: /// /// * [BorderRadius], for which this is a no-op (returns itself). /// * [BorderRadiusDirectional], which flips the horizontal direction /// based on the `direction` argument. BorderRadius resolve(TextDirection? direction); @override String toString() { String? visual, logical; if (_topLeft == _topRight && _topRight == _bottomLeft && _bottomLeft == _bottomRight) { if (_topLeft != Radius.zero) { if (_topLeft.x == _topLeft.y) { visual = 'BorderRadius.circular(${_topLeft.x.toStringAsFixed(1)})'; } else { visual = 'BorderRadius.all($_topLeft)'; } } } else { // visuals aren't the same and at least one isn't zero final StringBuffer result = StringBuffer(); result.write('BorderRadius.only('); bool comma = false; if (_topLeft != Radius.zero) { result.write('topLeft: $_topLeft'); comma = true; } if (_topRight != Radius.zero) { if (comma) { result.write(', '); } result.write('topRight: $_topRight'); comma = true; } if (_bottomLeft != Radius.zero) { if (comma) { result.write(', '); } result.write('bottomLeft: $_bottomLeft'); comma = true; } if (_bottomRight != Radius.zero) { if (comma) { result.write(', '); } result.write('bottomRight: $_bottomRight'); } result.write(')'); visual = result.toString(); } if (_topStart == _topEnd && _topEnd == _bottomEnd && _bottomEnd == _bottomStart) { if (_topStart != Radius.zero) { if (_topStart.x == _topStart.y) { logical = 'BorderRadiusDirectional.circular(${_topStart.x.toStringAsFixed(1)})'; } else { logical = 'BorderRadiusDirectional.all($_topStart)'; } } } else { // logicals aren't the same and at least one isn't zero final StringBuffer result = StringBuffer(); result.write('BorderRadiusDirectional.only('); bool comma = false; if (_topStart != Radius.zero) { result.write('topStart: $_topStart'); comma = true; } if (_topEnd != Radius.zero) { if (comma) { result.write(', '); } result.write('topEnd: $_topEnd'); comma = true; } if (_bottomStart != Radius.zero) { if (comma) { result.write(', '); } result.write('bottomStart: $_bottomStart'); comma = true; } if (_bottomEnd != Radius.zero) { if (comma) { result.write(', '); } result.write('bottomEnd: $_bottomEnd'); } result.write(')'); logical = result.toString(); } if (visual != null && logical != null) { return '$visual + $logical'; } return visual ?? logical ?? 'BorderRadius.zero'; } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is BorderRadiusGeometry && other._topLeft == _topLeft && other._topRight == _topRight && other._bottomLeft == _bottomLeft && other._bottomRight == _bottomRight && other._topStart == _topStart && other._topEnd == _topEnd && other._bottomStart == _bottomStart && other._bottomEnd == _bottomEnd; } @override int get hashCode => Object.hash( _topLeft, _topRight, _bottomLeft, _bottomRight, _topStart, _topEnd, _bottomStart, _bottomEnd, ); } /// An immutable set of radii for each corner of a rectangle. /// /// Used by [BoxDecoration] when the shape is a [BoxShape.rectangle]. /// /// The [BorderRadius] class specifies offsets in terms of visual corners, e.g. /// [topLeft]. These values are not affected by the [TextDirection]. To support /// both left-to-right and right-to-left layouts, consider using /// [BorderRadiusDirectional], which is expressed in terms that are relative to /// a [TextDirection] (typically obtained from the ambient [Directionality]). class BorderRadius extends BorderRadiusGeometry { /// Creates a border radius where all radii are [radius]. const BorderRadius.all(Radius radius) : this.only( topLeft: radius, topRight: radius, bottomLeft: radius, bottomRight: radius, ); /// Creates a border radius where all radii are [Radius.circular(radius)]. BorderRadius.circular(double radius) : this.all( Radius.circular(radius), ); /// Creates a vertically symmetric border radius where the top and bottom /// sides of the rectangle have the same radii. const BorderRadius.vertical({ Radius top = Radius.zero, Radius bottom = Radius.zero, }) : this.only( topLeft: top, topRight: top, bottomLeft: bottom, bottomRight: bottom, ); /// Creates a horizontally symmetrical border radius where the left and right /// sides of the rectangle have the same radii. const BorderRadius.horizontal({ Radius left = Radius.zero, Radius right = Radius.zero, }) : this.only( topLeft: left, topRight: right, bottomLeft: left, bottomRight: right, ); /// Creates a border radius with only the given non-zero values. The other /// corners will be right angles. const BorderRadius.only({ this.topLeft = Radius.zero, this.topRight = Radius.zero, this.bottomLeft = Radius.zero, this.bottomRight = Radius.zero, }); /// Returns a copy of this BorderRadius with the given fields replaced with /// the new values. BorderRadius copyWith({ Radius? topLeft, Radius? topRight, Radius? bottomLeft, Radius? bottomRight, }) { return BorderRadius.only( topLeft: topLeft ?? this.topLeft, topRight: topRight ?? this.topRight, bottomLeft: bottomLeft ?? this.bottomLeft, bottomRight: bottomRight ?? this.bottomRight, ); } /// A border radius with all zero radii. static const BorderRadius zero = BorderRadius.all(Radius.zero); /// The top-left [Radius]. final Radius topLeft; @override Radius get _topLeft => topLeft; /// The top-right [Radius]. final Radius topRight; @override Radius get _topRight => topRight; /// The bottom-left [Radius]. final Radius bottomLeft; @override Radius get _bottomLeft => bottomLeft; /// The bottom-right [Radius]. final Radius bottomRight; @override Radius get _bottomRight => bottomRight; @override Radius get _topStart => Radius.zero; @override Radius get _topEnd => Radius.zero; @override Radius get _bottomStart => Radius.zero; @override Radius get _bottomEnd => Radius.zero; /// Creates an [RRect] from the current border radius and a [Rect]. /// /// If any of the radii have negative values in x or y, those values will be /// clamped to zero in order to produce a valid [RRect]. RRect toRRect(Rect rect) { // Because the current radii could be negative, we must clamp them before // converting them to an RRect to be rendered, since negative radii on // RRects don't make sense. return RRect.fromRectAndCorners( rect, topLeft: topLeft.clamp(minimum: Radius.zero), topRight: topRight.clamp(minimum: Radius.zero), bottomLeft: bottomLeft.clamp(minimum: Radius.zero), bottomRight: bottomRight.clamp(minimum: Radius.zero), ); } @override BorderRadiusGeometry subtract(BorderRadiusGeometry other) { if (other is BorderRadius) { return this - other; } return super.subtract(other); } @override BorderRadiusGeometry add(BorderRadiusGeometry other) { if (other is BorderRadius) { return this + other; } return super.add(other); } /// Returns the difference between two [BorderRadius] objects. BorderRadius operator -(BorderRadius other) { return BorderRadius.only( topLeft: topLeft - other.topLeft, topRight: topRight - other.topRight, bottomLeft: bottomLeft - other.bottomLeft, bottomRight: bottomRight - other.bottomRight, ); } /// Returns the sum of two [BorderRadius] objects. BorderRadius operator +(BorderRadius other) { return BorderRadius.only( topLeft: topLeft + other.topLeft, topRight: topRight + other.topRight, bottomLeft: bottomLeft + other.bottomLeft, bottomRight: bottomRight + other.bottomRight, ); } /// Returns the [BorderRadius] object with each corner negated. /// /// This is the same as multiplying the object by -1.0. @override BorderRadius operator -() { return BorderRadius.only( topLeft: -topLeft, topRight: -topRight, bottomLeft: -bottomLeft, bottomRight: -bottomRight, ); } /// Scales each corner of the [BorderRadius] by the given factor. @override BorderRadius operator *(double other) { return BorderRadius.only( topLeft: topLeft * other, topRight: topRight * other, bottomLeft: bottomLeft * other, bottomRight: bottomRight * other, ); } /// Divides each corner of the [BorderRadius] by the given factor. @override BorderRadius operator /(double other) { return BorderRadius.only( topLeft: topLeft / other, topRight: topRight / other, bottomLeft: bottomLeft / other, bottomRight: bottomRight / other, ); } /// Integer divides each corner of the [BorderRadius] by the given factor. @override BorderRadius operator ~/(double other) { return BorderRadius.only( topLeft: topLeft ~/ other, topRight: topRight ~/ other, bottomLeft: bottomLeft ~/ other, bottomRight: bottomRight ~/ other, ); } /// Computes the remainder of each corner by the given factor. @override BorderRadius operator %(double other) { return BorderRadius.only( topLeft: topLeft % other, topRight: topRight % other, bottomLeft: bottomLeft % other, bottomRight: bottomRight % other, ); } /// Linearly interpolate between two [BorderRadius] objects. /// /// If either is null, this function interpolates from [BorderRadius.zero]. /// /// {@macro dart.ui.shadow.lerp} static BorderRadius? lerp(BorderRadius? a, BorderRadius? b, double t) { if (identical(a, b)) { return a; } if (a == null) { return b! * t; } if (b == null) { return a * (1.0 - t); } return BorderRadius.only( topLeft: Radius.lerp(a.topLeft, b.topLeft, t)!, topRight: Radius.lerp(a.topRight, b.topRight, t)!, bottomLeft: Radius.lerp(a.bottomLeft, b.bottomLeft, t)!, bottomRight: Radius.lerp(a.bottomRight, b.bottomRight, t)!, ); } @override BorderRadius resolve(TextDirection? direction) => this; } /// An immutable set of radii for each corner of a rectangle, but with the /// corners specified in a manner dependent on the writing direction. /// /// This can be used to specify a corner radius on the leading or trailing edge /// of a box, so that it flips to the other side when the text alignment flips /// (e.g. being on the top right in English text but the top left in Arabic /// text). /// /// See also: /// /// * [BorderRadius], a variant that uses physical labels (`topLeft` and /// `topRight` instead of `topStart` and `topEnd`). class BorderRadiusDirectional extends BorderRadiusGeometry { /// Creates a border radius where all radii are [radius]. const BorderRadiusDirectional.all(Radius radius) : this.only( topStart: radius, topEnd: radius, bottomStart: radius, bottomEnd: radius, ); /// Creates a border radius where all radii are [Radius.circular(radius)]. BorderRadiusDirectional.circular(double radius) : this.all( Radius.circular(radius), ); /// Creates a vertically symmetric border radius where the top and bottom /// sides of the rectangle have the same radii. const BorderRadiusDirectional.vertical({ Radius top = Radius.zero, Radius bottom = Radius.zero, }) : this.only( topStart: top, topEnd: top, bottomStart: bottom, bottomEnd: bottom, ); /// Creates a horizontally symmetrical border radius where the start and end /// sides of the rectangle have the same radii. const BorderRadiusDirectional.horizontal({ Radius start = Radius.zero, Radius end = Radius.zero, }) : this.only( topStart: start, topEnd: end, bottomStart: start, bottomEnd: end, ); /// Creates a border radius with only the given non-zero values. The other /// corners will be right angles. const BorderRadiusDirectional.only({ this.topStart = Radius.zero, this.topEnd = Radius.zero, this.bottomStart = Radius.zero, this.bottomEnd = Radius.zero, }); /// A border radius with all zero radii. /// /// Consider using [BorderRadius.zero] instead, since that object has the same /// effect, but will be cheaper to [resolve]. static const BorderRadiusDirectional zero = BorderRadiusDirectional.all(Radius.zero); /// The top-start [Radius]. final Radius topStart; @override Radius get _topStart => topStart; /// The top-end [Radius]. final Radius topEnd; @override Radius get _topEnd => topEnd; /// The bottom-start [Radius]. final Radius bottomStart; @override Radius get _bottomStart => bottomStart; /// The bottom-end [Radius]. final Radius bottomEnd; @override Radius get _bottomEnd => bottomEnd; @override Radius get _topLeft => Radius.zero; @override Radius get _topRight => Radius.zero; @override Radius get _bottomLeft => Radius.zero; @override Radius get _bottomRight => Radius.zero; @override BorderRadiusGeometry subtract(BorderRadiusGeometry other) { if (other is BorderRadiusDirectional) { return this - other; } return super.subtract(other); } @override BorderRadiusGeometry add(BorderRadiusGeometry other) { if (other is BorderRadiusDirectional) { return this + other; } return super.add(other); } /// Returns the difference between two [BorderRadiusDirectional] objects. BorderRadiusDirectional operator -(BorderRadiusDirectional other) { return BorderRadiusDirectional.only( topStart: topStart - other.topStart, topEnd: topEnd - other.topEnd, bottomStart: bottomStart - other.bottomStart, bottomEnd: bottomEnd - other.bottomEnd, ); } /// Returns the sum of two [BorderRadiusDirectional] objects. BorderRadiusDirectional operator +(BorderRadiusDirectional other) { return BorderRadiusDirectional.only( topStart: topStart + other.topStart, topEnd: topEnd + other.topEnd, bottomStart: bottomStart + other.bottomStart, bottomEnd: bottomEnd + other.bottomEnd, ); } /// Returns the [BorderRadiusDirectional] object with each corner negated. /// /// This is the same as multiplying the object by -1.0. @override BorderRadiusDirectional operator -() { return BorderRadiusDirectional.only( topStart: -topStart, topEnd: -topEnd, bottomStart: -bottomStart, bottomEnd: -bottomEnd, ); } /// Scales each corner of the [BorderRadiusDirectional] by the given factor. @override BorderRadiusDirectional operator *(double other) { return BorderRadiusDirectional.only( topStart: topStart * other, topEnd: topEnd * other, bottomStart: bottomStart * other, bottomEnd: bottomEnd * other, ); } /// Divides each corner of the [BorderRadiusDirectional] by the given factor. @override BorderRadiusDirectional operator /(double other) { return BorderRadiusDirectional.only( topStart: topStart / other, topEnd: topEnd / other, bottomStart: bottomStart / other, bottomEnd: bottomEnd / other, ); } /// Integer divides each corner of the [BorderRadiusDirectional] by the given factor. @override BorderRadiusDirectional operator ~/(double other) { return BorderRadiusDirectional.only( topStart: topStart ~/ other, topEnd: topEnd ~/ other, bottomStart: bottomStart ~/ other, bottomEnd: bottomEnd ~/ other, ); } /// Computes the remainder of each corner by the given factor. @override BorderRadiusDirectional operator %(double other) { return BorderRadiusDirectional.only( topStart: topStart % other, topEnd: topEnd % other, bottomStart: bottomStart % other, bottomEnd: bottomEnd % other, ); } /// Linearly interpolate between two [BorderRadiusDirectional] objects. /// /// If either is null, this function interpolates from [BorderRadiusDirectional.zero]. /// /// {@macro dart.ui.shadow.lerp} static BorderRadiusDirectional? lerp(BorderRadiusDirectional? a, BorderRadiusDirectional? b, double t) { if (identical(a, b)) { return a; } if (a == null) { return b! * t; } if (b == null) { return a * (1.0 - t); } return BorderRadiusDirectional.only( topStart: Radius.lerp(a.topStart, b.topStart, t)!, topEnd: Radius.lerp(a.topEnd, b.topEnd, t)!, bottomStart: Radius.lerp(a.bottomStart, b.bottomStart, t)!, bottomEnd: Radius.lerp(a.bottomEnd, b.bottomEnd, t)!, ); } @override BorderRadius resolve(TextDirection? direction) { assert(direction != null); switch (direction!) { case TextDirection.rtl: return BorderRadius.only( topLeft: topEnd, topRight: topStart, bottomLeft: bottomEnd, bottomRight: bottomStart, ); case TextDirection.ltr: return BorderRadius.only( topLeft: topStart, topRight: topEnd, bottomLeft: bottomStart, bottomRight: bottomEnd, ); } } } class _MixedBorderRadius extends BorderRadiusGeometry { const _MixedBorderRadius( this._topLeft, this._topRight, this._bottomLeft, this._bottomRight, this._topStart, this._topEnd, this._bottomStart, this._bottomEnd, ); @override final Radius _topLeft; @override final Radius _topRight; @override final Radius _bottomLeft; @override final Radius _bottomRight; @override final Radius _topStart; @override final Radius _topEnd; @override final Radius _bottomStart; @override final Radius _bottomEnd; @override _MixedBorderRadius operator -() { return _MixedBorderRadius( -_topLeft, -_topRight, -_bottomLeft, -_bottomRight, -_topStart, -_topEnd, -_bottomStart, -_bottomEnd, ); } /// Scales each corner of the [_MixedBorderRadius] by the given factor. @override _MixedBorderRadius operator *(double other) { return _MixedBorderRadius( _topLeft * other, _topRight * other, _bottomLeft * other, _bottomRight * other, _topStart * other, _topEnd * other, _bottomStart * other, _bottomEnd * other, ); } @override _MixedBorderRadius operator /(double other) { return _MixedBorderRadius( _topLeft / other, _topRight / other, _bottomLeft / other, _bottomRight / other, _topStart / other, _topEnd / other, _bottomStart / other, _bottomEnd / other, ); } @override _MixedBorderRadius operator ~/(double other) { return _MixedBorderRadius( _topLeft ~/ other, _topRight ~/ other, _bottomLeft ~/ other, _bottomRight ~/ other, _topStart ~/ other, _topEnd ~/ other, _bottomStart ~/ other, _bottomEnd ~/ other, ); } @override _MixedBorderRadius operator %(double other) { return _MixedBorderRadius( _topLeft % other, _topRight % other, _bottomLeft % other, _bottomRight % other, _topStart % other, _topEnd % other, _bottomStart % other, _bottomEnd % other, ); } @override BorderRadius resolve(TextDirection? direction) { assert(direction != null); switch (direction!) { case TextDirection.rtl: return BorderRadius.only( topLeft: _topLeft + _topEnd, topRight: _topRight + _topStart, bottomLeft: _bottomLeft + _bottomEnd, bottomRight: _bottomRight + _bottomStart, ); case TextDirection.ltr: return BorderRadius.only( topLeft: _topLeft + _topStart, topRight: _topRight + _topEnd, bottomLeft: _bottomLeft + _bottomStart, bottomRight: _bottomRight + _bottomEnd, ); } } }
flutter/packages/flutter/lib/src/painting/border_radius.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/painting/border_radius.dart", "repo_id": "flutter", "token_count": 9494 }
681
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/foundation.dart' show clampDouble; import 'basic_types.dart'; /// Position a child box within a container box, either above or below a target /// point. /// /// The container's size is described by `size`. /// /// The target point is specified by `target`, as an offset from the top left of /// the container. /// /// The child box's size is given by `childSize`. /// /// The return value is the suggested distance from the top left of the /// container box to the top left of the child box. /// /// The suggested position will be above the target point if `preferBelow` is /// false, and below the target point if it is true, unless it wouldn't fit on /// the preferred side but would fit on the other side. /// /// The suggested position will place the nearest side of the child to the /// target point `verticalOffset` from the target point (even if it cannot fit /// given that constraint). /// /// The suggested position will be at least `margin` away from the edge of the /// container. If possible, the child will be positioned so that its center is /// aligned with the target point. If the child cannot fit horizontally within /// the container given the margin, then the child will be centered in the /// container. /// /// Used by [Tooltip] to position a tooltip relative to its parent. Offset positionDependentBox({ required Size size, required Size childSize, required Offset target, required bool preferBelow, double verticalOffset = 0.0, double margin = 10.0, }) { // VERTICAL DIRECTION final bool fitsBelow = target.dy + verticalOffset + childSize.height <= size.height - margin; final bool fitsAbove = target.dy - verticalOffset - childSize.height >= margin; final bool tooltipBelow = fitsAbove == fitsBelow ? preferBelow : fitsBelow; final double y; if (tooltipBelow) { y = math.min(target.dy + verticalOffset, size.height - margin); } else { y = math.max(target.dy - verticalOffset - childSize.height, margin); } // HORIZONTAL DIRECTION final double flexibleSpace = size.width - childSize.width; final double x = flexibleSpace <= 2 * margin // If there's not enough horizontal space for margin + child, center the // child. ? flexibleSpace / 2.0 : clampDouble(target.dx - childSize.width / 2, margin, flexibleSpace - margin); return Offset(x, y); }
flutter/packages/flutter/lib/src/painting/geometry.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/painting/geometry.dart", "repo_id": "flutter", "token_count": 686 }
682
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'basic_types.dart'; import 'borders.dart'; import 'box_border.dart'; import 'box_decoration.dart'; import 'box_shadow.dart'; import 'circle_border.dart'; import 'colors.dart'; import 'decoration.dart'; import 'decoration_image.dart'; import 'edge_insets.dart'; import 'gradient.dart'; import 'image_provider.dart'; import 'rounded_rectangle_border.dart'; /// An immutable description of how to paint an arbitrary shape. /// /// The [ShapeDecoration] class provides a way to draw a [ShapeBorder], /// optionally filling it with a color or a gradient, optionally painting an /// image into it, and optionally casting a shadow. /// /// {@tool snippet} /// /// The following example uses the [Container] widget from the widgets layer to /// draw a white rectangle with a 24-pixel multicolor outline, with the text /// "RGB" inside it: /// /// ```dart /// Container( /// decoration: ShapeDecoration( /// color: Colors.white, /// shape: Border.all( /// color: Colors.red, /// width: 8.0, /// ) + Border.all( /// color: Colors.green, /// width: 8.0, /// ) + Border.all( /// color: Colors.blue, /// width: 8.0, /// ), /// ), /// child: const Text('RGB', textAlign: TextAlign.center), /// ) /// ``` /// {@end-tool} /// /// See also: /// /// * [DecoratedBox] and [Container], widgets that can be configured with /// [ShapeDecoration] objects. /// * [BoxDecoration], a similar [Decoration] that is optimized for rectangles /// specifically. /// * [ShapeBorder], the base class for the objects that are used in the /// [shape] property. class ShapeDecoration extends Decoration { /// Creates a shape decoration. /// /// * If [color] is null, this decoration does not paint a background color. /// * If [gradient] is null, this decoration does not paint gradients. /// * If [image] is null, this decoration does not paint a background image. /// * If [shadows] is null, this decoration does not paint a shadow. /// /// The [color] and [gradient] properties are mutually exclusive, one (or /// both) of them must be null. const ShapeDecoration({ this.color, this.image, this.gradient, this.shadows, required this.shape, }) : assert(!(color != null && gradient != null)); /// Creates a shape decoration configured to match a [BoxDecoration]. /// /// The [BoxDecoration] class is more efficient for shapes that it can /// describe than the [ShapeDecoration] class is for those same shapes, /// because [ShapeDecoration] has to be more general as it can support any /// shape. However, having a [ShapeDecoration] is sometimes necessary, for /// example when calling [ShapeDecoration.lerp] to transition between /// different shapes (e.g. from a [CircleBorder] to a /// [RoundedRectangleBorder]; the [BoxDecoration] class cannot animate the /// transition from a [BoxShape.circle] to [BoxShape.rectangle]). factory ShapeDecoration.fromBoxDecoration(BoxDecoration source) { final ShapeBorder shape; switch (source.shape) { case BoxShape.circle: if (source.border != null) { assert(source.border!.isUniform); shape = CircleBorder(side: source.border!.top); } else { shape = const CircleBorder(); } case BoxShape.rectangle: if (source.borderRadius != null) { assert(source.border == null || source.border!.isUniform); shape = RoundedRectangleBorder( side: source.border?.top ?? BorderSide.none, borderRadius: source.borderRadius!, ); } else { shape = source.border ?? const Border(); } } return ShapeDecoration( color: source.color, image: source.image, gradient: source.gradient, shadows: source.boxShadow, shape: shape, ); } @override Path getClipPath(Rect rect, TextDirection textDirection) { return shape.getOuterPath(rect, textDirection: textDirection); } /// The color to fill in the background of the shape. /// /// The color is under the [image]. /// /// If a [gradient] is specified, [color] must be null. final Color? color; /// A gradient to use when filling the shape. /// /// The gradient is under the [image]. /// /// If a [color] is specified, [gradient] must be null. final Gradient? gradient; /// An image to paint inside the shape (clipped to its outline). /// /// The image is drawn over the [color] or [gradient]. final DecorationImage? image; /// A list of shadows cast by the [shape]. /// /// See also: /// /// * [kElevationToShadow], for some predefined shadows used in Material /// Design. /// * [PhysicalModel], a widget for showing shadows. final List<BoxShadow>? shadows; /// The shape to fill the [color], [gradient], and [image] into and to cast as /// the [shadows]. /// /// Shapes can be stacked (using the `+` operator). The color, gradient, and /// image are drawn into the inner-most shape specified. /// /// The [shape] property specifies the outline (border) of the decoration. /// /// ## Directionality-dependent shapes /// /// Some [ShapeBorder] subclasses are sensitive to the [TextDirection]. The /// direction that is provided to the border (e.g. for its [ShapeBorder.paint] /// method) is the one specified in the [ImageConfiguration] /// ([ImageConfiguration.textDirection]) provided to the [BoxPainter] (via its /// [BoxPainter.paint method). The [BoxPainter] is obtained when /// [createBoxPainter] is called. /// /// When a [ShapeDecoration] is used with a [Container] widget or a /// [DecoratedBox] widget (which is what [Container] uses), the /// [TextDirection] specified in the [ImageConfiguration] is obtained from the /// ambient [Directionality], using [createLocalImageConfiguration]. final ShapeBorder shape; /// The inset space occupied by the [shape]'s border. /// /// This value may be misleading. See the discussion at [ShapeBorder.dimensions]. @override EdgeInsetsGeometry get padding => shape.dimensions; @override bool get isComplex => shadows != null; @override ShapeDecoration? lerpFrom(Decoration? a, double t) { if (a is BoxDecoration) { return ShapeDecoration.lerp(ShapeDecoration.fromBoxDecoration(a), this, t); } else if (a == null || a is ShapeDecoration) { return ShapeDecoration.lerp(a as ShapeDecoration?, this, t); } return super.lerpFrom(a, t) as ShapeDecoration?; } @override ShapeDecoration? lerpTo(Decoration? b, double t) { if (b is BoxDecoration) { return ShapeDecoration.lerp(this, ShapeDecoration.fromBoxDecoration(b), t); } else if (b == null || b is ShapeDecoration) { return ShapeDecoration.lerp(this, b as ShapeDecoration?, t); } return super.lerpTo(b, t) as ShapeDecoration?; } /// Linearly interpolate between two shapes. /// /// Interpolates each parameter of the decoration separately. /// /// If both values are null, this returns null. Otherwise, it returns a /// non-null value, with null arguments treated like a [ShapeDecoration] whose /// fields are all null (including the [shape], which cannot normally be /// null). /// /// {@macro dart.ui.shadow.lerp} /// /// See also: /// /// * [Decoration.lerp], which can interpolate between any two types of /// [Decoration]s, not just [ShapeDecoration]s. /// * [lerpFrom] and [lerpTo], which are used to implement [Decoration.lerp] /// and which use [ShapeDecoration.lerp] when interpolating two /// [ShapeDecoration]s or a [ShapeDecoration] to or from null. static ShapeDecoration? lerp(ShapeDecoration? a, ShapeDecoration? b, double t) { if (identical(a, b)) { return a; } if (a != null && b != null) { if (t == 0.0) { return a; } if (t == 1.0) { return b; } } return ShapeDecoration( color: Color.lerp(a?.color, b?.color, t), gradient: Gradient.lerp(a?.gradient, b?.gradient, t), image: DecorationImage.lerp(a?.image, b?.image, t), shadows: BoxShadow.lerpList(a?.shadows, b?.shadows, t), shape: ShapeBorder.lerp(a?.shape, b?.shape, t)!, ); } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is ShapeDecoration && other.color == color && other.gradient == gradient && other.image == image && listEquals<BoxShadow>(other.shadows, shadows) && other.shape == shape; } @override int get hashCode => Object.hash( color, gradient, image, shape, shadows == null ? null : Object.hashAll(shadows!), ); @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.defaultDiagnosticsTreeStyle = DiagnosticsTreeStyle.whitespace; properties.add(ColorProperty('color', color, defaultValue: null)); properties.add(DiagnosticsProperty<Gradient>('gradient', gradient, defaultValue: null)); properties.add(DiagnosticsProperty<DecorationImage>('image', image, defaultValue: null)); properties.add(IterableProperty<BoxShadow>('shadows', shadows, defaultValue: null, style: DiagnosticsTreeStyle.whitespace)); properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape)); } @override bool hitTest(Size size, Offset position, { TextDirection? textDirection }) { return shape.getOuterPath(Offset.zero & size, textDirection: textDirection).contains(position); } @override BoxPainter createBoxPainter([ VoidCallback? onChanged ]) { assert(onChanged != null || image == null); return _ShapeDecorationPainter(this, onChanged!); } } /// An object that paints a [ShapeDecoration] into a canvas. class _ShapeDecorationPainter extends BoxPainter { _ShapeDecorationPainter(this._decoration, VoidCallback onChanged) : super(onChanged); final ShapeDecoration _decoration; Rect? _lastRect; TextDirection? _lastTextDirection; late Path _outerPath; Path? _innerPath; Paint? _interiorPaint; int? _shadowCount; late List<Rect> _shadowBounds; late List<Path> _shadowPaths; late List<Paint> _shadowPaints; @override VoidCallback get onChanged => super.onChanged!; void _precache(Rect rect, TextDirection? textDirection) { if (rect == _lastRect && textDirection == _lastTextDirection) { return; } // We reach here in two cases: // - the very first time we paint, in which case everything except _decoration is null // - subsequent times, if the rect has changed, in which case we only need to update // the features that depend on the actual rect. if (_interiorPaint == null && (_decoration.color != null || _decoration.gradient != null)) { _interiorPaint = Paint(); if (_decoration.color != null) { _interiorPaint!.color = _decoration.color!; } } if (_decoration.gradient != null) { _interiorPaint!.shader = _decoration.gradient!.createShader(rect, textDirection: textDirection); } if (_decoration.shadows != null) { if (_shadowCount == null) { _shadowCount = _decoration.shadows!.length; _shadowPaints = <Paint>[ ..._decoration.shadows!.map((BoxShadow shadow) => shadow.toPaint()), ]; } if (_decoration.shape.preferPaintInterior) { _shadowBounds = <Rect>[ ..._decoration.shadows!.map((BoxShadow shadow) { return rect.shift(shadow.offset).inflate(shadow.spreadRadius); }), ]; } else { _shadowPaths = <Path>[ ..._decoration.shadows!.map((BoxShadow shadow) { return _decoration.shape.getOuterPath(rect.shift(shadow.offset).inflate(shadow.spreadRadius), textDirection: textDirection); }), ]; } } if (!_decoration.shape.preferPaintInterior && (_interiorPaint != null || _shadowCount != null)) { _outerPath = _decoration.shape.getOuterPath(rect, textDirection: textDirection); } if (_decoration.image != null) { _innerPath = _decoration.shape.getInnerPath(rect, textDirection: textDirection); } _lastRect = rect; _lastTextDirection = textDirection; } void _paintShadows(Canvas canvas, Rect rect, TextDirection? textDirection) { if (_shadowCount != null) { if (_decoration.shape.preferPaintInterior) { for (int index = 0; index < _shadowCount!; index += 1) { _decoration.shape.paintInterior(canvas, _shadowBounds[index], _shadowPaints[index], textDirection: textDirection); } } else { for (int index = 0; index < _shadowCount!; index += 1) { canvas.drawPath(_shadowPaths[index], _shadowPaints[index]); } } } } void _paintInterior(Canvas canvas, Rect rect, TextDirection? textDirection) { if (_interiorPaint != null) { if (_decoration.shape.preferPaintInterior) { _decoration.shape.paintInterior(canvas, rect, _interiorPaint!, textDirection: textDirection); } else { canvas.drawPath(_outerPath, _interiorPaint!); } } } DecorationImagePainter? _imagePainter; void _paintImage(Canvas canvas, ImageConfiguration configuration) { if (_decoration.image == null) { return; } _imagePainter ??= _decoration.image!.createPainter(onChanged); _imagePainter!.paint(canvas, _lastRect!, _innerPath, configuration); } @override void dispose() { _imagePainter?.dispose(); super.dispose(); } @override void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { assert(configuration.size != null); final Rect rect = offset & configuration.size!; final TextDirection? textDirection = configuration.textDirection; _precache(rect, textDirection); _paintShadows(canvas, rect, textDirection); _paintInterior(canvas, rect, textDirection); _paintImage(canvas, configuration); _decoration.shape.paint(canvas, rect, textDirection: textDirection); } }
flutter/packages/flutter/lib/src/painting/shape_decoration.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/painting/shape_decoration.dart", "repo_id": "flutter", "token_count": 5037 }
683
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' as ui show SemanticsUpdate; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/semantics.dart'; import 'package:flutter/services.dart'; import 'debug.dart'; import 'mouse_tracker.dart'; import 'object.dart'; import 'service_extensions.dart'; import 'view.dart'; export 'package:flutter/gestures.dart' show HitTestResult; // Examples can assume: // late BuildContext context; /// The glue between the render trees and the Flutter engine. /// /// The [RendererBinding] manages multiple independent render trees. Each render /// tree is rooted in a [RenderView] that must be added to the binding via /// [addRenderView] to be considered during frame production, hit testing, etc. /// Furthermore, the render tree must be managed by a [PipelineOwner] that is /// part of the pipeline owner tree rooted at [rootPipelineOwner]. /// /// Adding [PipelineOwner]s and [RenderView]s to this binding in the way /// described above is left as a responsibility for a higher level abstraction. /// The widgets library, for example, introduces the [View] widget, which /// registers its [RenderView] and [PipelineOwner] with this binding. mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureBinding, SemanticsBinding, HitTestable { @override void initInstances() { super.initInstances(); _instance = this; _rootPipelineOwner = createRootPipelineOwner(); platformDispatcher ..onMetricsChanged = handleMetricsChanged ..onTextScaleFactorChanged = handleTextScaleFactorChanged ..onPlatformBrightnessChanged = handlePlatformBrightnessChanged; addPersistentFrameCallback(_handlePersistentFrameCallback); initMouseTracker(); if (kIsWeb) { addPostFrameCallback(_handleWebFirstFrame, debugLabel: 'RendererBinding.webFirstFrame'); } rootPipelineOwner.attach(_manifold); } /// The current [RendererBinding], if one has been created. /// /// Provides access to the features exposed by this mixin. The binding must /// be initialized before using this getter; this is typically done by calling /// [runApp] or [WidgetsFlutterBinding.ensureInitialized]. static RendererBinding get instance => BindingBase.checkInstance(_instance); static RendererBinding? _instance; @override void initServiceExtensions() { super.initServiceExtensions(); assert(() { // these service extensions only work in debug mode registerBoolServiceExtension( name: RenderingServiceExtensions.invertOversizedImages.name, getter: () async => debugInvertOversizedImages, setter: (bool value) async { if (debugInvertOversizedImages != value) { debugInvertOversizedImages = value; return _forceRepaint(); } return Future<void>.value(); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugPaint.name, getter: () async => debugPaintSizeEnabled, setter: (bool value) { if (debugPaintSizeEnabled == value) { return Future<void>.value(); } debugPaintSizeEnabled = value; return _forceRepaint(); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugPaintBaselinesEnabled.name, getter: () async => debugPaintBaselinesEnabled, setter: (bool value) { if (debugPaintBaselinesEnabled == value) { return Future<void>.value(); } debugPaintBaselinesEnabled = value; return _forceRepaint(); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.repaintRainbow.name, getter: () async => debugRepaintRainbowEnabled, setter: (bool value) { final bool repaint = debugRepaintRainbowEnabled && !value; debugRepaintRainbowEnabled = value; if (repaint) { return _forceRepaint(); } return Future<void>.value(); }, ); registerServiceExtension( name: RenderingServiceExtensions.debugDumpLayerTree.name, callback: (Map<String, String> parameters) async { return <String, Object>{ 'data': _debugCollectLayerTrees(), }; }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugDisableClipLayers.name, getter: () async => debugDisableClipLayers, setter: (bool value) { if (debugDisableClipLayers == value) { return Future<void>.value(); } debugDisableClipLayers = value; return _forceRepaint(); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugDisablePhysicalShapeLayers.name, getter: () async => debugDisablePhysicalShapeLayers, setter: (bool value) { if (debugDisablePhysicalShapeLayers == value) { return Future<void>.value(); } debugDisablePhysicalShapeLayers = value; return _forceRepaint(); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugDisableOpacityLayers.name, getter: () async => debugDisableOpacityLayers, setter: (bool value) { if (debugDisableOpacityLayers == value) { return Future<void>.value(); } debugDisableOpacityLayers = value; return _forceRepaint(); }, ); return true; }()); if (!kReleaseMode) { // these service extensions work in debug or profile mode registerServiceExtension( name: RenderingServiceExtensions.debugDumpRenderTree.name, callback: (Map<String, String> parameters) async { return <String, Object>{ 'data': _debugCollectRenderTrees(), }; }, ); registerServiceExtension( name: RenderingServiceExtensions.debugDumpSemanticsTreeInTraversalOrder.name, callback: (Map<String, String> parameters) async { return <String, Object>{ 'data': _debugCollectSemanticsTrees(DebugSemanticsDumpOrder.traversalOrder), }; }, ); registerServiceExtension( name: RenderingServiceExtensions.debugDumpSemanticsTreeInInverseHitTestOrder.name, callback: (Map<String, String> parameters) async { return <String, Object>{ 'data': _debugCollectSemanticsTrees(DebugSemanticsDumpOrder.inverseHitTest), }; }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.profileRenderObjectPaints.name, getter: () async => debugProfilePaintsEnabled, setter: (bool value) async { if (debugProfilePaintsEnabled != value) { debugProfilePaintsEnabled = value; } }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.profileRenderObjectLayouts.name, getter: () async => debugProfileLayoutsEnabled, setter: (bool value) async { if (debugProfileLayoutsEnabled != value) { debugProfileLayoutsEnabled = value; } }, ); } } late final PipelineManifold _manifold = _BindingPipelineManifold(this); /// The object that manages state about currently connected mice, for hover /// notification. MouseTracker get mouseTracker => _mouseTracker!; MouseTracker? _mouseTracker; /// Deprecated. Will be removed in a future version of Flutter. /// /// This is typically the owner of the render tree bootstrapped by [runApp] /// and rooted in [renderView]. It maintains dirty state for layout, /// composite, paint, and accessibility semantics for that tree. /// /// However, by default, the [pipelineOwner] does not participate in frame /// production because it is not automatically attached to the /// [rootPipelineOwner] or any of its descendants. It is also not /// automatically associated with the [renderView]. This is left as a /// responsibility for a higher level abstraction. The [WidgetsBinding], for /// example, wires this up in [WidgetsBinding.wrapWithDefaultView], which is /// called indirectly from [runApp]. /// /// Apps, that don't use the [WidgetsBinding] or don't call [runApp] (or /// [WidgetsBinding.wrapWithDefaultView]) must manually add this pipeline owner /// to the pipeline owner tree rooted at [rootPipelineOwner] and assign a /// [RenderView] to it if the they want to use this deprecated property. /// /// Instead of accessing this deprecated property, consider interacting with /// the root of the [PipelineOwner] tree (exposed in [rootPipelineOwner]) or /// instead of accessing the [SemanticsOwner] of any [PipelineOwner] consider /// interacting with the [SemanticsBinding] (exposed via /// [SemanticsBinding.instance]) directly. @Deprecated( 'Interact with the pipelineOwner tree rooted at RendererBinding.rootPipelineOwner instead. ' 'Or instead of accessing the SemanticsOwner of any PipelineOwner interact with the SemanticsBinding directly. ' 'This feature was deprecated after v3.10.0-12.0.pre.' ) late final PipelineOwner pipelineOwner = PipelineOwner( onSemanticsOwnerCreated: () { (pipelineOwner.rootNode as RenderView?)?.scheduleInitialSemantics(); }, onSemanticsUpdate: (ui.SemanticsUpdate update) { (pipelineOwner.rootNode as RenderView?)?.updateSemantics(update); }, onSemanticsOwnerDisposed: () { (pipelineOwner.rootNode as RenderView?)?.clearSemantics(); } ); /// Deprecated. Will be removed in a future version of Flutter. /// /// This is typically the root of the render tree bootstrapped by [runApp]. /// /// However, by default this render view is not associated with any /// [PipelineOwner] and therefore isn't considered during frame production. /// It is also not registered with this binding via [addRenderView]. /// Wiring this up is left as a responsibility for a higher level. The /// [WidgetsBinding], for example, sets this up in /// [WidgetsBinding.wrapWithDefaultView], which is called indirectly from /// [runApp]. /// /// Apps that don't use the [WidgetsBinding] or don't call [runApp] (or /// [WidgetsBinding.wrapWithDefaultView]) must manually assign a /// [PipelineOwner] to this [RenderView], make sure the pipeline owner is part /// of the pipeline owner tree rooted at [rootPipelineOwner], and call /// [addRenderView] if they want to use this deprecated property. /// /// Instead of interacting with this deprecated property, consider using /// [renderViews] instead, which contains all [RenderView]s managed by the /// binding. @Deprecated( 'Consider using RendererBinding.renderViews instead as the binding may manage multiple RenderViews. ' 'This feature was deprecated after v3.10.0-12.0.pre.' ) // TODO(goderbauer): When this deprecated property is removed also delete the _ReusableRenderView class. late final RenderView renderView = _ReusableRenderView( view: platformDispatcher.implicitView!, ); /// Creates the [PipelineOwner] that serves as the root of the pipeline owner /// tree ([rootPipelineOwner]). /// /// {@template flutter.rendering.createRootPipelineOwner} /// By default, the root pipeline owner is not setup to manage a render tree /// and its [PipelineOwner.rootNode] must not be assigned. If necessary, /// [createRootPipelineOwner] may be overridden to create a root pipeline /// owner configured to manage its own render tree. /// /// In typical use, child pipeline owners are added to the root pipeline owner /// (via [PipelineOwner.adoptChild]). Those children typically do each manage /// their own [RenderView] and produce distinct render trees which render /// their content into the [FlutterView] associated with that [RenderView]. /// {@endtemplate} PipelineOwner createRootPipelineOwner() { return _DefaultRootPipelineOwner(); } /// The [PipelineOwner] that is the root of the PipelineOwner tree. /// /// {@macro flutter.rendering.createRootPipelineOwner} PipelineOwner get rootPipelineOwner => _rootPipelineOwner; late PipelineOwner _rootPipelineOwner; /// The [RenderView]s managed by this binding. /// /// A [RenderView] is added by [addRenderView] and removed by [removeRenderView]. Iterable<RenderView> get renderViews => _viewIdToRenderView.values; final Map<Object, RenderView> _viewIdToRenderView = <Object, RenderView>{}; /// Adds a [RenderView] to this binding. /// /// The binding will interact with the [RenderView] in the following ways: /// /// * setting and updating [RenderView.configuration], /// * calling [RenderView.compositeFrame] when it is time to produce a new /// frame, and /// * forwarding relevant pointer events to the [RenderView] for hit testing. /// /// To remove a [RenderView] from the binding, call [removeRenderView]. void addRenderView(RenderView view) { final Object viewId = view.flutterView.viewId; assert(!_viewIdToRenderView.containsValue(view)); assert(!_viewIdToRenderView.containsKey(viewId)); _viewIdToRenderView[viewId] = view; view.configuration = createViewConfigurationFor(view); } /// Removes a [RenderView] previously added with [addRenderView] from the /// binding. void removeRenderView(RenderView view) { final Object viewId = view.flutterView.viewId; assert(_viewIdToRenderView[viewId] == view); _viewIdToRenderView.remove(viewId); } /// Returns a [ViewConfiguration] configured for the provided [RenderView] /// based on the current environment. /// /// This is called during [addRenderView] and also in response to changes to /// the system metrics to update all [renderViews] added to the binding. /// /// Bindings can override this method to change what size or device pixel /// ratio the [RenderView] will use. For example, the testing framework uses /// this to force the display into 800x600 when a test is run on the device /// using `flutter run`. @protected ViewConfiguration createViewConfigurationFor(RenderView renderView) { return ViewConfiguration.fromView(renderView.flutterView); } /// Called when the system metrics change. /// /// See [dart:ui.PlatformDispatcher.onMetricsChanged]. @protected @visibleForTesting void handleMetricsChanged() { bool forceFrame = false; for (final RenderView view in renderViews) { forceFrame = forceFrame || view.child != null; view.configuration = createViewConfigurationFor(view); } if (forceFrame) { scheduleForcedFrame(); } } /// Called when the platform text scale factor changes. /// /// See [dart:ui.PlatformDispatcher.onTextScaleFactorChanged]. @protected void handleTextScaleFactorChanged() { } /// Called when the platform brightness changes. /// /// The current platform brightness can be queried from a Flutter binding or /// from a [MediaQuery] widget. The latter is preferred from widgets because /// it causes the widget to be automatically rebuilt when the brightness /// changes. /// /// {@tool snippet} /// Querying [MediaQuery.platformBrightnessOf] directly. Preferred. /// /// ```dart /// final Brightness brightness = MediaQuery.platformBrightnessOf(context); /// ``` /// {@end-tool} /// /// {@tool snippet} /// Querying [PlatformDispatcher.platformBrightness]. /// /// ```dart /// final Brightness brightness = WidgetsBinding.instance.platformDispatcher.platformBrightness; /// ``` /// {@end-tool} /// /// See [dart:ui.PlatformDispatcher.onPlatformBrightnessChanged]. @protected void handlePlatformBrightnessChanged() { } /// Creates a [MouseTracker] which manages state about currently connected /// mice, for hover notification. /// /// Used by testing framework to reinitialize the mouse tracker between tests. @visibleForTesting void initMouseTracker([MouseTracker? tracker]) { _mouseTracker?.dispose(); _mouseTracker = tracker ?? MouseTracker((Offset position, int viewId) { final HitTestResult result = HitTestResult(); hitTestInView(result, position, viewId); return result; }); } @override // from GestureBinding void dispatchEvent(PointerEvent event, HitTestResult? hitTestResult) { _mouseTracker!.updateWithEvent( event, // When the button is pressed, normal hit test uses a cached // result, but MouseTracker requires that the hit test is re-executed to // update the hovering events. event is PointerMoveEvent ? null : hitTestResult, ); super.dispatchEvent(event, hitTestResult); } @override void performSemanticsAction(SemanticsActionEvent action) { // Due to the asynchronicity in some screen readers (they may not have // processed the latest semantics update yet) this code is more forgiving // and actions for views/nodes that no longer exist are gracefully ignored. _viewIdToRenderView[action.viewId]?.owner?.semanticsOwner?.performAction(action.nodeId, action.type, action.arguments); } void _handleWebFirstFrame(Duration _) { assert(kIsWeb); const MethodChannel methodChannel = MethodChannel('flutter/service_worker'); methodChannel.invokeMethod<void>('first-frame'); } void _handlePersistentFrameCallback(Duration timeStamp) { drawFrame(); _scheduleMouseTrackerUpdate(); } bool _debugMouseTrackerUpdateScheduled = false; void _scheduleMouseTrackerUpdate() { assert(!_debugMouseTrackerUpdateScheduled); assert(() { _debugMouseTrackerUpdateScheduled = true; return true; }()); SchedulerBinding.instance.addPostFrameCallback((Duration duration) { assert(_debugMouseTrackerUpdateScheduled); assert(() { _debugMouseTrackerUpdateScheduled = false; return true; }()); _mouseTracker!.updateAllDevices(); }, debugLabel: 'RendererBinding.mouseTrackerUpdate'); } int _firstFrameDeferredCount = 0; bool _firstFrameSent = false; /// Whether frames produced by [drawFrame] are sent to the engine. /// /// If false the framework will do all the work to produce a frame, /// but the frame is never sent to the engine to actually appear on screen. /// /// See also: /// /// * [deferFirstFrame], which defers when the first frame is sent to the /// engine. bool get sendFramesToEngine => _firstFrameSent || _firstFrameDeferredCount == 0; /// Tell the framework to not send the first frames to the engine until there /// is a corresponding call to [allowFirstFrame]. /// /// Call this to perform asynchronous initialization work before the first /// frame is rendered (which takes down the splash screen). The framework /// will still do all the work to produce frames, but those frames are never /// sent to the engine and will not appear on screen. /// /// Calling this has no effect after the first frame has been sent to the /// engine. void deferFirstFrame() { assert(_firstFrameDeferredCount >= 0); _firstFrameDeferredCount += 1; } /// Called after [deferFirstFrame] to tell the framework that it is ok to /// send the first frame to the engine now. /// /// For best performance, this method should only be called while the /// [schedulerPhase] is [SchedulerPhase.idle]. /// /// This method may only be called once for each corresponding call /// to [deferFirstFrame]. void allowFirstFrame() { assert(_firstFrameDeferredCount > 0); _firstFrameDeferredCount -= 1; // Always schedule a warm up frame even if the deferral count is not down to // zero yet since the removal of a deferral may uncover new deferrals that // are lower in the widget tree. if (!_firstFrameSent) { scheduleWarmUpFrame(); } } /// Call this to pretend that no frames have been sent to the engine yet. /// /// This is useful for tests that want to call [deferFirstFrame] and /// [allowFirstFrame] since those methods only have an effect if no frames /// have been sent to the engine yet. void resetFirstFrameSent() { _firstFrameSent = false; } /// Pump the rendering pipeline to generate a frame. /// /// This method is called by [handleDrawFrame], which itself is called /// automatically by the engine when it is time to lay out and paint a frame. /// /// Each frame consists of the following phases: /// /// 1. The animation phase: The [handleBeginFrame] method, which is registered /// with [PlatformDispatcher.onBeginFrame], invokes all the transient frame /// callbacks registered with [scheduleFrameCallback], in registration order. /// This includes all the [Ticker] instances that are driving /// [AnimationController] objects, which means all of the active [Animation] /// objects tick at this point. /// /// 2. Microtasks: After [handleBeginFrame] returns, any microtasks that got /// scheduled by transient frame callbacks get to run. This typically includes /// callbacks for futures from [Ticker]s and [AnimationController]s that /// completed this frame. /// /// After [handleBeginFrame], [handleDrawFrame], which is registered with /// [dart:ui.PlatformDispatcher.onDrawFrame], is called, which invokes all the /// persistent frame callbacks, of which the most notable is this method, /// [drawFrame], which proceeds as follows: /// /// 3. The layout phase: All the dirty [RenderObject]s in the system are laid /// out (see [RenderObject.performLayout]). See [RenderObject.markNeedsLayout] /// for further details on marking an object dirty for layout. /// /// 4. The compositing bits phase: The compositing bits on any dirty /// [RenderObject] objects are updated. See /// [RenderObject.markNeedsCompositingBitsUpdate]. /// /// 5. The paint phase: All the dirty [RenderObject]s in the system are /// repainted (see [RenderObject.paint]). This generates the [Layer] tree. See /// [RenderObject.markNeedsPaint] for further details on marking an object /// dirty for paint. /// /// 6. The compositing phase: The layer tree is turned into a [Scene] and /// sent to the GPU. /// /// 7. The semantics phase: All the dirty [RenderObject]s in the system have /// their semantics updated. This generates the [SemanticsNode] tree. See /// [RenderObject.markNeedsSemanticsUpdate] for further details on marking an /// object dirty for semantics. /// /// For more details on steps 3-7, see [PipelineOwner]. /// /// 8. The finalization phase: After [drawFrame] returns, [handleDrawFrame] /// then invokes post-frame callbacks (registered with [addPostFrameCallback]). /// /// Some bindings (for example, the [WidgetsBinding]) add extra steps to this /// list (for example, see [WidgetsBinding.drawFrame]). // // When editing the above, also update widgets/binding.dart's copy. @protected void drawFrame() { rootPipelineOwner.flushLayout(); rootPipelineOwner.flushCompositingBits(); rootPipelineOwner.flushPaint(); if (sendFramesToEngine) { for (final RenderView renderView in renderViews) { renderView.compositeFrame(); // this sends the bits to the GPU } rootPipelineOwner.flushSemantics(); // this sends the semantics to the OS. _firstFrameSent = true; } } @override Future<void> performReassemble() async { await super.performReassemble(); if (!kReleaseMode) { FlutterTimeline.startSync('Preparing Hot Reload (layout)'); } try { for (final RenderView renderView in renderViews) { renderView.reassemble(); } } finally { if (!kReleaseMode) { FlutterTimeline.finishSync(); } } scheduleWarmUpFrame(); await endOfFrame; } @override void hitTestInView(HitTestResult result, Offset position, int viewId) { _viewIdToRenderView[viewId]?.hitTest(result, position: position); super.hitTestInView(result, position, viewId); } Future<void> _forceRepaint() { late RenderObjectVisitor visitor; visitor = (RenderObject child) { child.markNeedsPaint(); child.visitChildren(visitor); }; for (final RenderView renderView in renderViews) { renderView.visitChildren(visitor); } return endOfFrame; } } String _debugCollectRenderTrees() { if (RendererBinding.instance.renderViews.isEmpty) { return 'No render tree root was added to the binding.'; } return <String>[ for (final RenderView renderView in RendererBinding.instance.renderViews) renderView.toStringDeep(), ].join('\n\n'); } /// Prints a textual representation of the render trees. /// /// {@template flutter.rendering.debugDumpRenderTree} /// It prints the trees associated with every [RenderView] in /// [RendererBinding.renderView], separated by two blank lines. /// {@endtemplate} void debugDumpRenderTree() { debugPrint(_debugCollectRenderTrees()); } String _debugCollectLayerTrees() { if (RendererBinding.instance.renderViews.isEmpty) { return 'No render tree root was added to the binding.'; } return <String>[ for (final RenderView renderView in RendererBinding.instance.renderViews) renderView.debugLayer?.toStringDeep() ?? 'Layer tree unavailable for $renderView.', ].join('\n\n'); } /// Prints a textual representation of the layer trees. /// /// {@macro flutter.rendering.debugDumpRenderTree} void debugDumpLayerTree() { debugPrint(_debugCollectLayerTrees()); } String _debugCollectSemanticsTrees(DebugSemanticsDumpOrder childOrder) { if (RendererBinding.instance.renderViews.isEmpty) { return 'No render tree root was added to the binding.'; } const String explanation = 'For performance reasons, the framework only generates semantics when asked to do so by the platform.\n' 'Usually, platforms only ask for semantics when assistive technologies (like screen readers) are running.\n' 'To generate semantics, try turning on an assistive technology (like VoiceOver or TalkBack) on your device.'; final List<String> trees = <String>[]; bool printedExplanation = false; for (final RenderView renderView in RendererBinding.instance.renderViews) { final String? tree = renderView.debugSemantics?.toStringDeep(childOrder: childOrder); if (tree != null) { trees.add(tree); } else { String message = 'Semantics not generated for $renderView.'; if (!printedExplanation) { printedExplanation = true; message = '$message\n$explanation'; } trees.add(message); } } return trees.join('\n\n'); } /// Prints a textual representation of the semantics trees. /// /// {@macro flutter.rendering.debugDumpRenderTree} /// /// Semantics trees are only constructed when semantics are enabled (see /// [SemanticsBinding.semanticsEnabled]). If a semantics tree is not available, /// a notice about the missing semantics tree is printed instead. /// /// The order in which the children of a [SemanticsNode] will be printed is /// controlled by the [childOrder] parameter. void debugDumpSemanticsTree([DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.traversalOrder]) { debugPrint(_debugCollectSemanticsTrees(childOrder)); } /// Prints a textual representation of the [PipelineOwner] tree rooted at /// [RendererBinding.rootPipelineOwner]. void debugDumpPipelineOwnerTree() { debugPrint(RendererBinding.instance.rootPipelineOwner.toStringDeep()); } /// A concrete binding for applications that use the Rendering framework /// directly. This is the glue that binds the framework to the Flutter engine. /// /// When using the rendering framework directly, this binding, or one that /// implements the same interfaces, must be used. The following /// mixins are used to implement this binding: /// /// * [GestureBinding], which implements the basics of hit testing. /// * [SchedulerBinding], which introduces the concepts of frames. /// * [ServicesBinding], which provides access to the plugin subsystem. /// * [SemanticsBinding], which supports accessibility. /// * [PaintingBinding], which enables decoding images. /// * [RendererBinding], which handles the render tree. /// /// You would only use this binding if you are writing to the /// rendering layer directly. If you are writing to a higher-level /// library, such as the Flutter Widgets library, then you would use /// that layer's binding (see [WidgetsFlutterBinding]). /// /// The [RenderingFlutterBinding] can manage multiple render trees. Each render /// tree is rooted in a [RenderView] that must be added to the binding via /// [addRenderView] to be consider during frame production, hit testing, etc. /// Furthermore, the render tree must be managed by a [PipelineOwner] that is /// part of the pipeline owner tree rooted at [rootPipelineOwner]. /// /// Adding [PipelineOwner]s and [RenderView]s to this binding in the way /// described above is left as a responsibility for a higher level abstraction. /// The binding does not own any [RenderView]s directly. class RenderingFlutterBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, SemanticsBinding, PaintingBinding, RendererBinding { /// Returns an instance of the binding that implements /// [RendererBinding]. If no binding has yet been initialized, the /// [RenderingFlutterBinding] class is used to create and initialize /// one. /// /// You need to call this method before using the rendering framework /// if you are using it directly. If you are using the widgets framework, /// see [WidgetsFlutterBinding.ensureInitialized]. static RendererBinding ensureInitialized() { if (RendererBinding._instance == null) { RenderingFlutterBinding(); } return RendererBinding.instance; } } /// A [PipelineManifold] implementation that is backed by the [RendererBinding]. class _BindingPipelineManifold extends ChangeNotifier implements PipelineManifold { _BindingPipelineManifold(this._binding) { if (kFlutterMemoryAllocationsEnabled) { ChangeNotifier.maybeDispatchObjectCreation(this); } _binding.addSemanticsEnabledListener(notifyListeners); } final RendererBinding _binding; @override void requestVisualUpdate() { _binding.ensureVisualUpdate(); } @override bool get semanticsEnabled => _binding.semanticsEnabled; @override void dispose() { _binding.removeSemanticsEnabledListener(notifyListeners); super.dispose(); } } // A [PipelineOwner] that cannot have a root node. class _DefaultRootPipelineOwner extends PipelineOwner { _DefaultRootPipelineOwner() : super(onSemanticsUpdate: _onSemanticsUpdate); @override set rootNode(RenderObject? _) { assert(() { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary( 'Cannot set a rootNode on the default root pipeline owner.', ), ErrorDescription( 'By default, the RendererBinding.rootPipelineOwner is not configured ' 'to manage a root node because this pipeline owner does not define a ' 'proper onSemanticsUpdate callback to handle semantics for that node.', ), ErrorHint( 'Typically, the root pipeline owner does not manage a root node. ' 'Instead, properly configured child pipeline owners (which do manage ' 'root nodes) are added to it. Alternatively, if you do want to set a ' 'root node for the root pipeline owner, override ' 'RendererBinding.createRootPipelineOwner to create a ' 'pipeline owner that is configured to properly handle semantics for ' 'the provided root node.' ), ]); }()); } static void _onSemanticsUpdate(ui.SemanticsUpdate _) { // Neve called because we don't have a root node. assert(false); } } // Prior to multi view support, the [RendererBinding] would own a long-lived // [RenderView], that was never disposed (see [RendererBinding.renderView]). // With multi view support, the [RendererBinding] no longer owns a [RenderView] // and instead higher level abstractions (like the [View] widget) can add/remove // multiple [RenderView]s to the binding as needed. When the [View] widget is no // longer needed, it expects to dispose its [RenderView]. // // This special version of a [RenderView] now exists as a bridge between those // worlds to continue supporting the [RendererBinding.renderView] property // through its deprecation period. Per the property's contract, it is supposed // to be long-lived, but it is also managed by a [View] widget (introduced by // [WidgetsBinding.wrapWithDefaultView]), that expects to dispose its render // object at the end of the widget's life time. This special version now // implements logic to reset the [RenderView] when it is "disposed" so it can be // reused by another [View] widget. // // Once the deprecated [RendererBinding.renderView] property is removed, this // class is no longer necessary. class _ReusableRenderView extends RenderView { _ReusableRenderView({required super.view}); bool _initialFramePrepared = false; @override void prepareInitialFrame() { if (_initialFramePrepared) { return; } super.prepareInitialFrame(); _initialFramePrepared = true; } @override void scheduleInitialSemantics() { clearSemantics(); super.scheduleInitialSemantics(); } @override void dispose() { // ignore: must_call_super child = null; } }
flutter/packages/flutter/lib/src/rendering/binding.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/rendering/binding.dart", "repo_id": "flutter", "token_count": 10714 }
684
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:collection' show LinkedHashMap; import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'object.dart'; export 'package:flutter/services.dart' show MouseCursor, SystemMouseCursors; /// Signature for hit testing at the given offset for the specified view. /// /// It is used by the [MouseTracker] to fetch annotations for the mouse /// position. typedef MouseTrackerHitTest = HitTestResult Function(Offset offset, int viewId); // Various states of a connected mouse device used by [MouseTracker]. class _MouseState { _MouseState({ required PointerEvent initialEvent, }) : _latestEvent = initialEvent; // The list of annotations that contains this device. // // It uses [LinkedHashMap] to keep the insertion order. LinkedHashMap<MouseTrackerAnnotation, Matrix4> get annotations => _annotations; LinkedHashMap<MouseTrackerAnnotation, Matrix4> _annotations = LinkedHashMap<MouseTrackerAnnotation, Matrix4>(); LinkedHashMap<MouseTrackerAnnotation, Matrix4> replaceAnnotations(LinkedHashMap<MouseTrackerAnnotation, Matrix4> value) { final LinkedHashMap<MouseTrackerAnnotation, Matrix4> previous = _annotations; _annotations = value; return previous; } // The most recently processed mouse event observed from this device. PointerEvent get latestEvent => _latestEvent; PointerEvent _latestEvent; PointerEvent replaceLatestEvent(PointerEvent value) { assert(value.device == _latestEvent.device); final PointerEvent previous = _latestEvent; _latestEvent = value; return previous; } int get device => latestEvent.device; @override String toString() { final String describeLatestEvent = 'latestEvent: ${describeIdentity(latestEvent)}'; final String describeAnnotations = 'annotations: [list of ${annotations.length}]'; return '${describeIdentity(this)}($describeLatestEvent, $describeAnnotations)'; } } // The information in `MouseTracker._handleDeviceUpdate` to provide the details // of an update of a mouse device. // // This class contains the information needed to handle the update that might // change the state of a mouse device, or the [MouseTrackerAnnotation]s that // the mouse device is hovering. @immutable class _MouseTrackerUpdateDetails with Diagnosticable { /// When device update is triggered by a new frame. /// /// All parameters are required. const _MouseTrackerUpdateDetails.byNewFrame({ required this.lastAnnotations, required this.nextAnnotations, required PointerEvent this.previousEvent, }) : triggeringEvent = null; /// When device update is triggered by a pointer event. /// /// The [lastAnnotations], [nextAnnotations], and [triggeringEvent] are /// required. const _MouseTrackerUpdateDetails.byPointerEvent({ required this.lastAnnotations, required this.nextAnnotations, this.previousEvent, required PointerEvent this.triggeringEvent, }); /// The annotations that the device is hovering before the update. /// /// It is never null. final LinkedHashMap<MouseTrackerAnnotation, Matrix4> lastAnnotations; /// The annotations that the device is hovering after the update. /// /// It is never null. final LinkedHashMap<MouseTrackerAnnotation, Matrix4> nextAnnotations; /// The last event that the device observed before the update. /// /// If the update is triggered by a frame, the [previousEvent] is never null, /// since the pointer must have been added before. /// /// If the update is triggered by a pointer event, the [previousEvent] is not /// null except for cases where the event is the first event observed by the /// pointer (which is not necessarily a [PointerAddedEvent]). final PointerEvent? previousEvent; /// The event that triggered this update. /// /// It is non-null if and only if the update is triggered by a pointer event. final PointerEvent? triggeringEvent; /// The pointing device of this update. int get device { final int result = (previousEvent ?? triggeringEvent)!.device; return result; } /// The last event that the device observed after the update. /// /// The [latestEvent] is never null. PointerEvent get latestEvent { final PointerEvent result = triggeringEvent ?? previousEvent!; return result; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IntProperty('device', device)); properties.add(DiagnosticsProperty<PointerEvent>('previousEvent', previousEvent)); properties.add(DiagnosticsProperty<PointerEvent>('triggeringEvent', triggeringEvent)); properties.add(DiagnosticsProperty<Map<MouseTrackerAnnotation, Matrix4>>('lastAnnotations', lastAnnotations)); properties.add(DiagnosticsProperty<Map<MouseTrackerAnnotation, Matrix4>>('nextAnnotations', nextAnnotations)); } } /// Tracks the relationship between mouse devices and annotations, and /// triggers mouse events and cursor changes accordingly. /// /// The [MouseTracker] tracks the relationship between mouse devices and /// [MouseTrackerAnnotation], notified by [updateWithEvent] and /// [updateAllDevices]. At every update, [MouseTracker] triggers the following /// changes if applicable: /// /// * Dispatches mouse-related pointer events (pointer enter, hover, and exit). /// * Changes mouse cursors. /// * Notifies when [mouseIsConnected] changes. /// /// This class is a [ChangeNotifier] that notifies its listeners if the value of /// [mouseIsConnected] changes. /// /// An instance of [MouseTracker] is owned by the global singleton /// [RendererBinding]. class MouseTracker extends ChangeNotifier { /// Create a mouse tracker. /// /// The `hitTestInView` is used to find the render objects on a given /// position in the specific view. It is typically provided by the /// [RendererBinding]. MouseTracker(MouseTrackerHitTest hitTestInView) : _hitTestInView = hitTestInView; final MouseTrackerHitTest _hitTestInView; final MouseCursorManager _mouseCursorMixin = MouseCursorManager( SystemMouseCursors.basic, ); // Tracks the state of connected mouse devices. // // It is the source of truth for the list of connected mouse devices, and // consists of two parts: // // * The mouse devices that are connected. // * In which annotations each device is contained. final Map<int, _MouseState> _mouseStates = <int, _MouseState>{}; // Used to wrap any procedure that might change `mouseIsConnected`. // // This method records `mouseIsConnected`, runs `task`, and calls // [notifyListeners] at the end if the `mouseIsConnected` has changed. void _monitorMouseConnection(VoidCallback task) { final bool mouseWasConnected = mouseIsConnected; task(); if (mouseWasConnected != mouseIsConnected) { notifyListeners(); } } bool _debugDuringDeviceUpdate = false; // Used to wrap any procedure that might call `_handleDeviceUpdate`. // // In debug mode, this method uses `_debugDuringDeviceUpdate` to prevent // `_deviceUpdatePhase` being recursively called. void _deviceUpdatePhase(VoidCallback task) { assert(!_debugDuringDeviceUpdate); assert(() { _debugDuringDeviceUpdate = true; return true; }()); task(); assert(() { _debugDuringDeviceUpdate = false; return true; }()); } // Whether an observed event might update a device. static bool _shouldMarkStateDirty(_MouseState? state, PointerEvent event) { if (state == null) { return true; } final PointerEvent lastEvent = state.latestEvent; assert(event.device == lastEvent.device); // An Added can only follow a Removed, and a Removed can only be followed // by an Added. assert((event is PointerAddedEvent) == (lastEvent is PointerRemovedEvent)); // Ignore events that are unrelated to mouse tracking. if (event is PointerSignalEvent) { return false; } return lastEvent is PointerAddedEvent || event is PointerRemovedEvent || lastEvent.position != event.position; } LinkedHashMap<MouseTrackerAnnotation, Matrix4> _hitTestInViewResultToAnnotations(HitTestResult result) { final LinkedHashMap<MouseTrackerAnnotation, Matrix4> annotations = LinkedHashMap<MouseTrackerAnnotation, Matrix4>(); for (final HitTestEntry entry in result.path) { final Object target = entry.target; if (target is MouseTrackerAnnotation) { annotations[target] = entry.transform!; } } return annotations; } // Find the annotations that is hovered by the device of the `state`, and // their respective global transform matrices. // // If the device is not connected or not a mouse, an empty map is returned // without calling `hitTest`. LinkedHashMap<MouseTrackerAnnotation, Matrix4> _findAnnotations(_MouseState state) { final Offset globalPosition = state.latestEvent.position; final int device = state.device; final int viewId = state.latestEvent.viewId; if (!_mouseStates.containsKey(device)) { return LinkedHashMap<MouseTrackerAnnotation, Matrix4>(); } return _hitTestInViewResultToAnnotations(_hitTestInView(globalPosition, viewId)); } // A callback that is called on the update of a device. // // An event (not necessarily a pointer event) that might change the // relationship between mouse devices and [MouseTrackerAnnotation]s is called // a _device update_. This method should be called at each such update. // // The update can be caused by two kinds of triggers: // // * Triggered by the addition, movement, or removal of a pointer. Such calls // occur during the handler of the event, indicated by // `details.triggeringEvent` being non-null. // * Triggered by the appearance, movement, or disappearance of an annotation. // Such calls occur after each new frame, during the post-frame callbacks, // indicated by `details.triggeringEvent` being null. // // Calls of this method must be wrapped in `_deviceUpdatePhase`. void _handleDeviceUpdate(_MouseTrackerUpdateDetails details) { assert(_debugDuringDeviceUpdate); _handleDeviceUpdateMouseEvents(details); _mouseCursorMixin.handleDeviceCursorUpdate( details.device, details.triggeringEvent, details.nextAnnotations.keys.map((MouseTrackerAnnotation annotation) => annotation.cursor), ); } /// Whether or not at least one mouse is connected and has produced events. bool get mouseIsConnected => _mouseStates.isNotEmpty; /// Perform a device update for one device according to the given new event. /// /// The [updateWithEvent] is typically called by [RendererBinding] during the /// handler of a pointer event. All pointer events should call this method, /// and let [MouseTracker] filter which to react to. /// /// The `hitTestResult` serves as an optional optimization, and is the hit /// test result already performed by [RendererBinding] for other gestures. It /// can be null, but when it's not null, it should be identical to the result /// from directly calling `hitTestInView` given in the constructor (which /// means that it should not use the cached result for [PointerMoveEvent]). /// /// The [updateWithEvent] is one of the two ways of updating mouse /// states, the other one being [updateAllDevices]. void updateWithEvent(PointerEvent event, HitTestResult? hitTestResult) { if (event.kind != PointerDeviceKind.mouse) { return; } if (event is PointerSignalEvent) { return; } final HitTestResult result; if (event is PointerRemovedEvent) { result = HitTestResult(); } else { final int viewId = event.viewId; result = hitTestResult ?? _hitTestInView(event.position, viewId); } final int device = event.device; final _MouseState? existingState = _mouseStates[device]; if (!_shouldMarkStateDirty(existingState, event)) { return; } _monitorMouseConnection(() { _deviceUpdatePhase(() { // Update mouseState to the latest devices that have not been removed, // so that [mouseIsConnected], which is decided by `_mouseStates`, is // correct during the callbacks. if (existingState == null) { if (event is PointerRemovedEvent) { return; } _mouseStates[device] = _MouseState(initialEvent: event); } else { assert(event is! PointerAddedEvent); if (event is PointerRemovedEvent) { _mouseStates.remove(event.device); } } final _MouseState targetState = _mouseStates[device] ?? existingState!; final PointerEvent lastEvent = targetState.replaceLatestEvent(event); final LinkedHashMap<MouseTrackerAnnotation, Matrix4> nextAnnotations = event is PointerRemovedEvent ? LinkedHashMap<MouseTrackerAnnotation, Matrix4>() : _hitTestInViewResultToAnnotations(result); final LinkedHashMap<MouseTrackerAnnotation, Matrix4> lastAnnotations = targetState.replaceAnnotations(nextAnnotations); _handleDeviceUpdate(_MouseTrackerUpdateDetails.byPointerEvent( lastAnnotations: lastAnnotations, nextAnnotations: nextAnnotations, previousEvent: lastEvent, triggeringEvent: event, )); }); }); } /// Perform a device update for all detected devices. /// /// The [updateAllDevices] is typically called during the post frame phase, /// indicating a frame has passed and all objects have potentially moved. For /// each connected device, the [updateAllDevices] will make a hit test on the /// device's last seen position, and check if necessary changes need to be /// made. /// /// The [updateAllDevices] is one of the two ways of updating mouse /// states, the other one being [updateWithEvent]. void updateAllDevices() { _deviceUpdatePhase(() { for (final _MouseState dirtyState in _mouseStates.values) { final PointerEvent lastEvent = dirtyState.latestEvent; final LinkedHashMap<MouseTrackerAnnotation, Matrix4> nextAnnotations = _findAnnotations(dirtyState); final LinkedHashMap<MouseTrackerAnnotation, Matrix4> lastAnnotations = dirtyState.replaceAnnotations(nextAnnotations); _handleDeviceUpdate(_MouseTrackerUpdateDetails.byNewFrame( lastAnnotations: lastAnnotations, nextAnnotations: nextAnnotations, previousEvent: lastEvent, )); } }); } /// Returns the active mouse cursor for a device. /// /// The return value is the last [MouseCursor] activated onto this device, even /// if the activation failed. /// /// This function is only active when asserts are enabled. In release builds, /// it always returns null. @visibleForTesting MouseCursor? debugDeviceActiveCursor(int device) { return _mouseCursorMixin.debugDeviceActiveCursor(device); } // Handles device update and dispatches mouse event callbacks. static void _handleDeviceUpdateMouseEvents(_MouseTrackerUpdateDetails details) { final PointerEvent latestEvent = details.latestEvent; final LinkedHashMap<MouseTrackerAnnotation, Matrix4> lastAnnotations = details.lastAnnotations; final LinkedHashMap<MouseTrackerAnnotation, Matrix4> nextAnnotations = details.nextAnnotations; // Order is important for mouse event callbacks. The // `_hitTestInViewResultToAnnotations` returns annotations in the visual order // from front to back, called the "hit-test order". The algorithm here is // explained in https://github.com/flutter/flutter/issues/41420 // Send exit events to annotations that are in last but not in next, in // hit-test order. final PointerExitEvent baseExitEvent = PointerExitEvent.fromMouseEvent(latestEvent); lastAnnotations.forEach((MouseTrackerAnnotation annotation, Matrix4 transform) { if (annotation.validForMouseTracker && !nextAnnotations.containsKey(annotation)) { annotation.onExit?.call(baseExitEvent.transformed(lastAnnotations[annotation])); } }); // Send enter events to annotations that are not in last but in next, in // reverse hit-test order. final List<MouseTrackerAnnotation> enteringAnnotations = nextAnnotations.keys.where( (MouseTrackerAnnotation annotation) => !lastAnnotations.containsKey(annotation), ).toList(); final PointerEnterEvent baseEnterEvent = PointerEnterEvent.fromMouseEvent(latestEvent); for (final MouseTrackerAnnotation annotation in enteringAnnotations.reversed) { if (annotation.validForMouseTracker) { annotation.onEnter?.call(baseEnterEvent.transformed(nextAnnotations[annotation])); } } } }
flutter/packages/flutter/lib/src/rendering/mouse_tracker.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/rendering/mouse_tracker.dart", "repo_id": "flutter", "token_count": 5122 }
685
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'box.dart'; import 'sliver.dart'; import 'sliver_multi_box_adaptor.dart'; /// A sliver that places multiple box children in a linear array along the main /// axis. /// /// Each child is forced to have the [SliverConstraints.crossAxisExtent] in the /// cross axis but determines its own main axis extent. /// /// [RenderSliverList] determines its scroll offset by "dead reckoning" because /// children outside the visible part of the sliver are not materialized, which /// means [RenderSliverList] cannot learn their main axis extent. Instead, newly /// materialized children are placed adjacent to existing children. If this dead /// reckoning results in a logical inconsistency (e.g., attempting to place the /// zeroth child at a scroll offset other than zero), the [RenderSliverList] /// generates a [SliverGeometry.scrollOffsetCorrection] to restore consistency. /// /// If the children have a fixed extent in the main axis, consider using /// [RenderSliverFixedExtentList] rather than [RenderSliverList] because /// [RenderSliverFixedExtentList] does not need to perform layout on its /// children to obtain their extent in the main axis and is therefore more /// efficient. /// /// See also: /// /// * [RenderSliverFixedExtentList], which is more efficient for children with /// the same extent in the main axis. /// * [RenderSliverGrid], which places its children in arbitrary positions. class RenderSliverList extends RenderSliverMultiBoxAdaptor { /// Creates a sliver that places multiple box children in a linear array along /// the main axis. RenderSliverList({ required super.childManager, }); @override void performLayout() { final SliverConstraints constraints = this.constraints; childManager.didStartLayout(); childManager.setDidUnderflow(false); final double scrollOffset = constraints.scrollOffset + constraints.cacheOrigin; assert(scrollOffset >= 0.0); final double remainingExtent = constraints.remainingCacheExtent; assert(remainingExtent >= 0.0); final double targetEndScrollOffset = scrollOffset + remainingExtent; final BoxConstraints childConstraints = constraints.asBoxConstraints(); int leadingGarbage = 0; int trailingGarbage = 0; bool reachedEnd = false; // This algorithm in principle is straight-forward: find the first child // that overlaps the given scrollOffset, creating more children at the top // of the list if necessary, then walk down the list updating and laying out // each child and adding more at the end if necessary until we have enough // children to cover the entire viewport. // // It is complicated by one minor issue, which is that any time you update // or create a child, it's possible that the some of the children that // haven't yet been laid out will be removed, leaving the list in an // inconsistent state, and requiring that missing nodes be recreated. // // To keep this mess tractable, this algorithm starts from what is currently // the first child, if any, and then walks up and/or down from there, so // that the nodes that might get removed are always at the edges of what has // already been laid out. // Make sure we have at least one child to start from. if (firstChild == null) { if (!addInitialChild()) { // There are no children. geometry = SliverGeometry.zero; childManager.didFinishLayout(); return; } } // We have at least one child. // These variables track the range of children that we have laid out. Within // this range, the children have consecutive indices. Outside this range, // it's possible for a child to get removed without notice. RenderBox? leadingChildWithLayout, trailingChildWithLayout; RenderBox? earliestUsefulChild = firstChild; // A firstChild with null layout offset is likely a result of children // reordering. // // We rely on firstChild to have accurate layout offset. In the case of null // layout offset, we have to find the first child that has valid layout // offset. if (childScrollOffset(firstChild!) == null) { int leadingChildrenWithoutLayoutOffset = 0; while (earliestUsefulChild != null && childScrollOffset(earliestUsefulChild) == null) { earliestUsefulChild = childAfter(earliestUsefulChild); leadingChildrenWithoutLayoutOffset += 1; } // We should be able to destroy children with null layout offset safely, // because they are likely outside of viewport collectGarbage(leadingChildrenWithoutLayoutOffset, 0); // If can not find a valid layout offset, start from the initial child. if (firstChild == null) { if (!addInitialChild()) { // There are no children. geometry = SliverGeometry.zero; childManager.didFinishLayout(); return; } } } // Find the last child that is at or before the scrollOffset. earliestUsefulChild = firstChild; for (double earliestScrollOffset = childScrollOffset(earliestUsefulChild!)!; earliestScrollOffset > scrollOffset; earliestScrollOffset = childScrollOffset(earliestUsefulChild)!) { // We have to add children before the earliestUsefulChild. earliestUsefulChild = insertAndLayoutLeadingChild(childConstraints, parentUsesSize: true); if (earliestUsefulChild == null) { final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = 0.0; if (scrollOffset == 0.0) { // insertAndLayoutLeadingChild only lays out the children before // firstChild. In this case, nothing has been laid out. We have // to lay out firstChild manually. firstChild!.layout(childConstraints, parentUsesSize: true); earliestUsefulChild = firstChild; leadingChildWithLayout = earliestUsefulChild; trailingChildWithLayout ??= earliestUsefulChild; break; } else { // We ran out of children before reaching the scroll offset. // We must inform our parent that this sliver cannot fulfill // its contract and that we need a scroll offset correction. geometry = SliverGeometry( scrollOffsetCorrection: -scrollOffset, ); return; } } final double firstChildScrollOffset = earliestScrollOffset - paintExtentOf(firstChild!); // firstChildScrollOffset may contain double precision error if (firstChildScrollOffset < -precisionErrorTolerance) { // Let's assume there is no child before the first child. We will // correct it on the next layout if it is not. geometry = SliverGeometry( scrollOffsetCorrection: -firstChildScrollOffset, ); final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = 0.0; return; } final SliverMultiBoxAdaptorParentData childParentData = earliestUsefulChild.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = firstChildScrollOffset; assert(earliestUsefulChild == firstChild); leadingChildWithLayout = earliestUsefulChild; trailingChildWithLayout ??= earliestUsefulChild; } assert(childScrollOffset(firstChild!)! > -precisionErrorTolerance); // If the scroll offset is at zero, we should make sure we are // actually at the beginning of the list. if (scrollOffset < precisionErrorTolerance) { // We iterate from the firstChild in case the leading child has a 0 paint // extent. while (indexOf(firstChild!) > 0) { final double earliestScrollOffset = childScrollOffset(firstChild!)!; // We correct one child at a time. If there are more children before // the earliestUsefulChild, we will correct it once the scroll offset // reaches zero again. earliestUsefulChild = insertAndLayoutLeadingChild(childConstraints, parentUsesSize: true); assert(earliestUsefulChild != null); final double firstChildScrollOffset = earliestScrollOffset - paintExtentOf(firstChild!); final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = 0.0; // We only need to correct if the leading child actually has a // paint extent. if (firstChildScrollOffset < -precisionErrorTolerance) { geometry = SliverGeometry( scrollOffsetCorrection: -firstChildScrollOffset, ); return; } } } // At this point, earliestUsefulChild is the first child, and is a child // whose scrollOffset is at or before the scrollOffset, and // leadingChildWithLayout and trailingChildWithLayout are either null or // cover a range of render boxes that we have laid out with the first being // the same as earliestUsefulChild and the last being either at or after the // scroll offset. assert(earliestUsefulChild == firstChild); assert(childScrollOffset(earliestUsefulChild!)! <= scrollOffset); // Make sure we've laid out at least one child. if (leadingChildWithLayout == null) { earliestUsefulChild!.layout(childConstraints, parentUsesSize: true); leadingChildWithLayout = earliestUsefulChild; trailingChildWithLayout = earliestUsefulChild; } // Here, earliestUsefulChild is still the first child, it's got a // scrollOffset that is at or before our actual scrollOffset, and it has // been laid out, and is in fact our leadingChildWithLayout. It's possible // that some children beyond that one have also been laid out. bool inLayoutRange = true; RenderBox? child = earliestUsefulChild; int index = indexOf(child!); double endScrollOffset = childScrollOffset(child)! + paintExtentOf(child); bool advance() { // returns true if we advanced, false if we have no more children // This function is used in two different places below, to avoid code duplication. assert(child != null); if (child == trailingChildWithLayout) { inLayoutRange = false; } child = childAfter(child!); if (child == null) { inLayoutRange = false; } index += 1; if (!inLayoutRange) { if (child == null || indexOf(child!) != index) { // We are missing a child. Insert it (and lay it out) if possible. child = insertAndLayoutChild(childConstraints, after: trailingChildWithLayout, parentUsesSize: true, ); if (child == null) { // We have run out of children. return false; } } else { // Lay out the child. child!.layout(childConstraints, parentUsesSize: true); } trailingChildWithLayout = child; } assert(child != null); final SliverMultiBoxAdaptorParentData childParentData = child!.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = endScrollOffset; assert(childParentData.index == index); endScrollOffset = childScrollOffset(child!)! + paintExtentOf(child!); return true; } // Find the first child that ends after the scroll offset. while (endScrollOffset < scrollOffset) { leadingGarbage += 1; if (!advance()) { assert(leadingGarbage == childCount); assert(child == null); // we want to make sure we keep the last child around so we know the end scroll offset collectGarbage(leadingGarbage - 1, 0); assert(firstChild == lastChild); final double extent = childScrollOffset(lastChild!)! + paintExtentOf(lastChild!); geometry = SliverGeometry( scrollExtent: extent, maxPaintExtent: extent, ); return; } } // Now find the first child that ends after our end. while (endScrollOffset < targetEndScrollOffset) { if (!advance()) { reachedEnd = true; break; } } // Finally count up all the remaining children and label them as garbage. if (child != null) { child = childAfter(child!); while (child != null) { trailingGarbage += 1; child = childAfter(child!); } } // At this point everything should be good to go, we just have to clean up // the garbage and report the geometry. collectGarbage(leadingGarbage, trailingGarbage); assert(debugAssertChildListIsNonEmptyAndContiguous()); final double estimatedMaxScrollOffset; if (reachedEnd) { estimatedMaxScrollOffset = endScrollOffset; } else { estimatedMaxScrollOffset = childManager.estimateMaxScrollOffset( constraints, firstIndex: indexOf(firstChild!), lastIndex: indexOf(lastChild!), leadingScrollOffset: childScrollOffset(firstChild!), trailingScrollOffset: endScrollOffset, ); assert(estimatedMaxScrollOffset >= endScrollOffset - childScrollOffset(firstChild!)!); } final double paintExtent = calculatePaintOffset( constraints, from: childScrollOffset(firstChild!)!, to: endScrollOffset, ); final double cacheExtent = calculateCacheOffset( constraints, from: childScrollOffset(firstChild!)!, to: endScrollOffset, ); final double targetEndScrollOffsetForPaint = constraints.scrollOffset + constraints.remainingPaintExtent; geometry = SliverGeometry( scrollExtent: estimatedMaxScrollOffset, paintExtent: paintExtent, cacheExtent: cacheExtent, maxPaintExtent: estimatedMaxScrollOffset, // Conservative to avoid flickering away the clip during scroll. hasVisualOverflow: endScrollOffset > targetEndScrollOffsetForPaint || constraints.scrollOffset > 0.0, ); // We may have started the layout while scrolled to the end, which would not // expose a new child. if (estimatedMaxScrollOffset == endScrollOffset) { childManager.setDidUnderflow(true); } childManager.didFinishLayout(); } }
flutter/packages/flutter/lib/src/rendering/sliver_list.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/rendering/sliver_list.dart", "repo_id": "flutter", "token_count": 4812 }
686
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Service extension constants for the scheduler 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 SchedulerServiceExtensions { /// Name of service extension that, when called, will change the value of /// [timeDilation], which determines the factor by which to slow down /// animations for help in development. /// /// See also: /// /// * [timeDilation], which is the field that this service extension exposes. /// * [SchedulerBinding.initServiceExtensions], where the service extension is /// registered. timeDilation, }
flutter/packages/flutter/lib/src/scheduler/service_extensions.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/scheduler/service_extensions.dart", "repo_id": "flutter", "token_count": 239 }
687
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'hardware_keyboard.dart'; export 'hardware_keyboard.dart' show KeyDataTransitMode; /// Override the transit mode with which key events are simulated. /// /// Setting [debugKeyEventSimulatorTransitModeOverride] is a good way to make /// certain tests simulate the behavior of different type of platforms in terms /// of their extent of support for keyboard API. /// /// This value is deprecated and will be removed. @Deprecated( 'No longer supported. Transit mode is always key data only. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) KeyDataTransitMode? debugKeyEventSimulatorTransitModeOverride; /// Setting to true will cause extensive logging to occur when key events are /// received. /// /// Can be used to debug keyboard issues: each time a key event is received on /// the framework side, the event details and the current pressed state will /// be printed. bool debugPrintKeyboardEvents = false; /// Returns true if none of the widget library debug variables have been changed. /// /// This function is used by the test framework to ensure that debug variables /// haven't been inadvertently changed. /// /// See [the services library](services/services-library.html) for a complete list. bool debugAssertAllServicesVarsUnset(String reason) { assert(() { if (debugKeyEventSimulatorTransitModeOverride != null) { throw FlutterError(reason); } if (debugPrintKeyboardEvents) { throw FlutterError(reason); } return true; }()); return true; } /// Controls whether platform channel usage can be debugged in non-release mode. /// /// This value is modified by calls to the /// [ServicesServiceExtensions.profilePlatformChannels] service extension. /// /// See also: /// /// * [shouldProfilePlatformChannels], which checks both /// [kProfilePlatformChannels] and [debugProfilePlatformChannels] for the /// current run mode. /// * [kProfilePlatformChannels], which determines whether platform channel /// usage can be debugged in release mode. bool debugProfilePlatformChannels = false;
flutter/packages/flutter/lib/src/services/debug.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/services/debug.dart", "repo_id": "flutter", "token_count": 603 }
688
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'system_channels.dart'; /// A data structure describing text processing actions. @immutable class ProcessTextAction { /// Creates text processing actions based on those returned by the engine. const ProcessTextAction(this.id, this.label); /// The action unique id. final String id; /// The action localized label. final String label; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is ProcessTextAction && other.id == id && other.label == label; } @override int get hashCode => Object.hash(id, label); } /// Determines how to interact with the text processing feature. abstract class ProcessTextService { /// Returns a [Future] that resolves to a [List] of [ProcessTextAction]s /// containing all text processing actions available. /// /// If there are no actions available, an empty list will be returned. Future<List<ProcessTextAction>> queryTextActions(); /// Returns a [Future] that resolves to a [String] when the text action /// returns a transformed text or null when the text action did not return /// a transformed text. /// /// The `id` parameter is the text action unique identifier returned by /// [queryTextActions]. /// /// The `text` parameter is the text to be processed. /// /// The `readOnly` parameter indicates that the transformed text, if it exists, /// will be used as read-only. Future<String?> processTextAction(String id, String text, bool readOnly); } /// The service used by default for the text processing feature. /// /// Any widget may use this service to get a list of text processing actions /// and send requests to activate these text actions. /// /// This is currently only supported on Android and it requires adding the /// following '<queries>' element to the Android manifest file: /// /// <manifest ...> /// <application ...> /// ... /// </application> /// <!-- Required to query activities that can process text, see: /// https://developer.android.com/training/package-visibility and /// https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT. /// /// In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. --> /// <queries> /// <intent> /// <action android:name="android.intent.action.PROCESS_TEXT"/> /// <data android:mimeType="text/plain"/> /// </intent> /// </queries> /// </manifest> /// /// The '<queries>' element is part of the Android manifest file generated when /// running the 'flutter create' command. /// /// If the '<queries>' element is not found, `queryTextActions()` will return an /// empty list of `ProcessTextAction`. /// /// See also: /// /// * [ProcessTextService], the service that this implements. class DefaultProcessTextService implements ProcessTextService { /// Creates the default service to interact with the platform text processing /// feature via communication over the text processing [MethodChannel]. DefaultProcessTextService() { _processTextChannel = SystemChannels.processText; } /// The channel used to communicate with the engine side. late MethodChannel _processTextChannel; /// Set the [MethodChannel] used to communicate with the engine text processing /// feature. /// /// This is only meant for testing within the Flutter SDK. @visibleForTesting void setChannel(MethodChannel newChannel) { assert(() { _processTextChannel = newChannel; return true; }()); } @override Future<List<ProcessTextAction>> queryTextActions() async { final Map<Object?, Object?> rawResults; try { final Map<Object?, Object?>? result = await _processTextChannel.invokeMethod( 'ProcessText.queryTextActions', ) as Map<Object?, Object?>?; if (result == null) { return <ProcessTextAction>[]; } rawResults = result; } catch (e) { return <ProcessTextAction>[]; } return <ProcessTextAction>[ for (final Object? id in rawResults.keys) ProcessTextAction(id! as String, rawResults[id]! as String), ]; } @override /// On Android, the readOnly parameter might be used by the targeted activity, see: /// https://developer.android.com/reference/android/content/Intent#EXTRA_PROCESS_TEXT_READONLY. Future<String?> processTextAction(String id, String text, bool readOnly) async { final String? processedText = await _processTextChannel.invokeMethod( 'ProcessText.processTextAction', <dynamic>[id, text, readOnly], ) as String?; return processedText; } }
flutter/packages/flutter/lib/src/services/process_text.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/services/process_text.dart", "repo_id": "flutter", "token_count": 1511 }
689
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:characters/characters.dart' show CharacterRange; import 'text_layout_metrics.dart'; // Examples can assume: // late TextLayoutMetrics textLayout; // late TextSpan text; // bool isWhitespace(int? codeUnit) => true; /// Signature for a predicate that takes an offset into a UTF-16 string, and a /// boolean that indicates the search direction. typedef UntilPredicate = bool Function(int offset, bool forward); /// An interface for retrieving the logical text boundary (as opposed to the /// visual boundary) at a given code unit offset in a document. /// /// Either the [getTextBoundaryAt] method, or both the /// [getLeadingTextBoundaryAt] method and the [getTrailingTextBoundaryAt] method /// must be implemented. abstract class TextBoundary { /// A constant constructor to enable subclass override. const TextBoundary(); /// Returns the offset of the closest text boundary before or at the given /// `position`, or null if no boundaries can be found. /// /// The return value, if not null, is usually less than or equal to `position`. /// /// The range of the return value is given by the closed interval /// `[0, string.length]`. int? getLeadingTextBoundaryAt(int position) { if (position < 0) { return null; } final int start = getTextBoundaryAt(position).start; return start >= 0 ? start : null; } /// Returns the offset of the closest text boundary after the given /// `position`, or null if there is no boundary can be found after `position`. /// /// The return value, if not null, is usually greater than `position`. /// /// The range of the return value is given by the closed interval /// `[0, string.length]`. int? getTrailingTextBoundaryAt(int position) { final int end = getTextBoundaryAt(max(0, position)).end; return end >= 0 ? end : null; } /// Returns the text boundary range that encloses the input position. /// /// The returned [TextRange] may contain `-1`, which indicates no boundaries /// can be found in that direction. TextRange getTextBoundaryAt(int position) { final int start = getLeadingTextBoundaryAt(position) ?? -1; final int end = getTrailingTextBoundaryAt(position) ?? -1; return TextRange(start: start, end: end); } } /// A [TextBoundary] subclass for retrieving the range of the grapheme the given /// `position` is in. /// /// The class is implemented using the /// [characters](https://pub.dev/packages/characters) package. class CharacterBoundary extends TextBoundary { /// Creates a [CharacterBoundary] with the text. const CharacterBoundary(this._text); final String _text; @override int? getLeadingTextBoundaryAt(int position) { if (position < 0) { return null; } final int graphemeStart = CharacterRange.at(_text, min(position, _text.length)).stringBeforeLength; assert(CharacterRange.at(_text, graphemeStart).isEmpty); return graphemeStart; } @override int? getTrailingTextBoundaryAt(int position) { if (position >= _text.length) { return null; } final CharacterRange rangeAtPosition = CharacterRange.at(_text, max(0, position + 1)); final int nextBoundary = rangeAtPosition.stringBeforeLength + rangeAtPosition.current.length; assert(nextBoundary == _text.length || CharacterRange.at(_text, nextBoundary).isEmpty); return nextBoundary; } @override TextRange getTextBoundaryAt(int position) { if (position < 0) { return TextRange(start: -1, end: getTrailingTextBoundaryAt(position) ?? -1); } else if (position >= _text.length) { return TextRange(start: getLeadingTextBoundaryAt(position) ?? -1, end: -1); } final CharacterRange rangeAtPosition = CharacterRange.at(_text, position); return rangeAtPosition.isNotEmpty ? TextRange(start: rangeAtPosition.stringBeforeLength, end: rangeAtPosition.stringBeforeLength + rangeAtPosition.current.length) // rangeAtPosition is empty means `position` is a grapheme boundary. : TextRange(start: rangeAtPosition.stringBeforeLength, end: getTrailingTextBoundaryAt(position) ?? -1); } } /// A [TextBoundary] subclass for locating closest line breaks to a given /// `position`. /// /// When the given `position` points to a hard line break, the returned range /// is the line's content range before the hard line break, and does not contain /// the given `position`. For instance, the line breaks at `position = 1` for /// "a\nb" is `[0, 1)`, which does not contain the position `1`. class LineBoundary extends TextBoundary { /// Creates a [LineBoundary] with the text and layout information. const LineBoundary(this._textLayout); final TextLayoutMetrics _textLayout; @override TextRange getTextBoundaryAt(int position) => _textLayout.getLineAtOffset(TextPosition(offset: max(position, 0))); } /// A text boundary that uses paragraphs as logical boundaries. /// /// A paragraph is defined as the range between line terminators. If no /// line terminators exist then the paragraph boundary is the entire document. class ParagraphBoundary extends TextBoundary { /// Creates a [ParagraphBoundary] with the text. const ParagraphBoundary(this._text); final String _text; /// Returns the [int] representing the start position of the paragraph that /// bounds the given `position`. The returned [int] is the position of the code unit /// that follows the line terminator that encloses the desired paragraph. @override int? getLeadingTextBoundaryAt(int position) { if (position < 0 || _text.isEmpty) { return null; } if (position >= _text.length) { return _text.length; } if (position == 0) { return 0; } int index = position; if (index > 1 && _text.codeUnitAt(index) == 0x0A && _text.codeUnitAt(index - 1) == 0x0D) { index -= 2; } else if (TextLayoutMetrics.isLineTerminator(_text.codeUnitAt(index))) { index -= 1; } while (index > 0) { if (TextLayoutMetrics.isLineTerminator(_text.codeUnitAt(index))) { return index + 1; } index -= 1; } return max(index, 0); } /// Returns the [int] representing the end position of the paragraph that /// bounds the given `position`. The returned [int] is the position of the /// code unit representing the trailing line terminator that encloses the /// desired paragraph. @override int? getTrailingTextBoundaryAt(int position) { if (position >= _text.length || _text.isEmpty) { return null; } if (position < 0) { return 0; } int index = position; while (!TextLayoutMetrics.isLineTerminator(_text.codeUnitAt(index))) { index += 1; if (index == _text.length) { return index; } } return index < _text.length - 1 && _text.codeUnitAt(index) == 0x0D && _text.codeUnitAt(index + 1) == 0x0A ? index + 2 : index + 1; } } /// A text boundary that uses the entire document as logical boundary. class DocumentBoundary extends TextBoundary { /// Creates a [DocumentBoundary] with the text. const DocumentBoundary(this._text); final String _text; @override int? getLeadingTextBoundaryAt(int position) => position < 0 ? null : 0; @override int? getTrailingTextBoundaryAt(int position) => position >= _text.length ? null : _text.length; }
flutter/packages/flutter/lib/src/services/text_boundary.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/services/text_boundary.dart", "repo_id": "flutter", "token_count": 2409 }
690
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'framework.dart'; import 'ticker_provider.dart'; /// Animated widget that automatically transitions its size over a given /// duration whenever the given child's size changes. /// /// {@tool dartpad} /// This example makes a [Container] react to being touched, causing the child /// of the [AnimatedSize] widget, here a [FlutterLogo], to animate. /// /// ** See code in examples/api/lib/widgets/animated_size/animated_size.0.dart ** /// {@end-tool} /// /// See also: /// /// * [SizeTransition], which changes its size based on an [Animation]. class AnimatedSize extends StatefulWidget { /// Creates a widget that animates its size to match that of its child. const AnimatedSize({ super.key, this.child, this.alignment = Alignment.center, this.curve = Curves.linear, required this.duration, this.reverseDuration, this.clipBehavior = Clip.hardEdge, this.onEnd, }); /// The widget below this widget in the tree. /// /// {@macro flutter.widgets.ProxyWidget.child} final Widget? child; /// The alignment of the child within the parent when the parent is not yet /// the same size as the child. /// /// The x and y values of the alignment control the horizontal and vertical /// alignment, respectively. An x value of -1.0 means that the left edge of /// the child is aligned with the left edge of the parent whereas an x value /// of 1.0 means that the right edge of the child is aligned with the right /// edge of the parent. Other values interpolate (and extrapolate) linearly. /// For example, a value of 0.0 means that the center of the child is aligned /// with the center of the parent. /// /// Defaults to [Alignment.center]. /// /// See also: /// /// * [Alignment], a class with convenient constants typically used to /// specify an [AlignmentGeometry]. /// * [AlignmentDirectional], like [Alignment] for specifying alignments /// relative to text direction. final AlignmentGeometry alignment; /// The animation curve when transitioning this widget's size to match the /// child's size. final Curve curve; /// The duration when transitioning this widget's size to match the child's /// size. final Duration duration; /// The duration when transitioning this widget's size to match the child's /// size when going in reverse. /// /// If not specified, defaults to [duration]. final Duration? reverseDuration; /// {@macro flutter.material.Material.clipBehavior} /// /// Defaults to [Clip.hardEdge]. final Clip clipBehavior; /// Called every time an animation completes. /// /// This can be useful to trigger additional actions (e.g. another animation) /// at the end of the current animation. final VoidCallback? onEnd; @override State<AnimatedSize> createState() => _AnimatedSizeState(); } class _AnimatedSizeState extends State<AnimatedSize> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { return _AnimatedSize( alignment: widget.alignment, curve: widget.curve, duration: widget.duration, reverseDuration: widget.reverseDuration, vsync: this, clipBehavior: widget.clipBehavior, onEnd: widget.onEnd, child: widget.child, ); } } class _AnimatedSize extends SingleChildRenderObjectWidget { const _AnimatedSize({ super.child, this.alignment = Alignment.center, this.curve = Curves.linear, required this.duration, this.reverseDuration, required this.vsync, this.clipBehavior = Clip.hardEdge, this.onEnd, }); final AlignmentGeometry alignment; final Curve curve; final Duration duration; final Duration? reverseDuration; /// The [TickerProvider] for this widget. final TickerProvider vsync; final Clip clipBehavior; final VoidCallback? onEnd; @override RenderAnimatedSize createRenderObject(BuildContext context) { return RenderAnimatedSize( alignment: alignment, duration: duration, reverseDuration: reverseDuration, curve: curve, vsync: vsync, textDirection: Directionality.maybeOf(context), clipBehavior: clipBehavior, onEnd: onEnd, ); } @override void updateRenderObject(BuildContext context, RenderAnimatedSize renderObject) { renderObject ..alignment = alignment ..duration = duration ..reverseDuration = reverseDuration ..curve = curve ..vsync = vsync ..textDirection = Directionality.maybeOf(context) ..clipBehavior = clipBehavior ..onEnd = onEnd; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: Alignment.topCenter)); properties.add(IntProperty('duration', duration.inMilliseconds, unit: 'ms')); properties.add(IntProperty('reverseDuration', reverseDuration?.inMilliseconds, unit: 'ms', defaultValue: null)); } }
flutter/packages/flutter/lib/src/widgets/animated_size.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/animated_size.dart", "repo_id": "flutter", "token_count": 1620 }
691
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'framework.dart'; /// The buttons that can appear in a context menu by default. /// /// See also: /// /// * [ContextMenuButtonItem], which uses this enum to describe a button in a /// context menu. enum ContextMenuButtonType { /// A button that cuts the current text selection. cut, /// A button that copies the current text selection. copy, /// A button that pastes the clipboard contents into the focused text field. paste, /// A button that selects all the contents of the focused text field. selectAll, /// A button that deletes the current text selection. delete, /// A button that looks up the current text selection. lookUp, /// A button that launches a web search for the current text selection. searchWeb, /// A button that displays the share screen for the current text selection. share, /// A button for starting Live Text input. /// /// See also: /// * [LiveText], where the availability of Live Text input can be obtained. /// * [LiveTextInputStatusNotifier], where the status of Live Text can be listened to. liveTextInput, /// Anything other than the default button types. custom, } /// The type and callback for a context menu button. /// /// See also: /// /// * [AdaptiveTextSelectionToolbar], which can take a list of /// ContextMenuButtonItems and create a platform-specific context menu with /// the indicated buttons. @immutable class ContextMenuButtonItem { /// Creates a const instance of [ContextMenuButtonItem]. const ContextMenuButtonItem({ required this.onPressed, this.type = ContextMenuButtonType.custom, this.label, }); /// The callback to be called when the button is pressed. final VoidCallback? onPressed; /// The type of button this represents. final ContextMenuButtonType type; /// The label to display on the button. /// /// If a [type] other than [ContextMenuButtonType.custom] is given /// and a label is not provided, then the default label for that type for the /// platform will be looked up. final String? label; /// Creates a new [ContextMenuButtonItem] with the provided parameters /// overridden. ContextMenuButtonItem copyWith({ VoidCallback? onPressed, ContextMenuButtonType? type, String? label, }) { return ContextMenuButtonItem( onPressed: onPressed ?? this.onPressed, type: type ?? this.type, label: label ?? this.label, ); } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is ContextMenuButtonItem && other.label == label && other.onPressed == onPressed && other.type == type; } @override int get hashCode => Object.hash(label, onPressed, type); @override String toString() => 'ContextMenuButtonItem $type, $label'; }
flutter/packages/flutter/lib/src/widgets/context_menu_button_item.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/context_menu_button_item.dart", "repo_id": "flutter", "token_count": 883 }
692
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'basic.dart'; import 'focus_manager.dart'; import 'framework.dart'; import 'inherited_notifier.dart'; /// A widget that manages a [FocusNode] to allow keyboard focus to be given /// to this widget and its descendants. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=JCDfh5bs1xc} /// /// When the focus is gained or lost, [onFocusChange] is called. /// /// For keyboard events, [onKey] and [onKeyEvent] are called if /// [FocusNode.hasFocus] is true for this widget's [focusNode], unless a focused /// descendant's [onKey] or [onKeyEvent] callback returned /// [KeyEventResult.handled] when called. /// /// This widget does not provide any visual indication that the focus has /// changed. Any desired visual changes should be made when [onFocusChange] is /// called. /// /// To access the [FocusNode] of the nearest ancestor [Focus] widget and /// establish a relationship that will rebuild the widget when the focus /// changes, use the [Focus.of] and [FocusScope.of] static methods. /// /// To access the focused state of the nearest [Focus] widget, use /// [FocusNode.hasFocus] from a build method, which also establishes a /// relationship between the calling widget and the [Focus] widget that will /// rebuild the calling widget when the focus changes. /// /// Managing a [FocusNode] means managing its lifecycle, listening for changes /// in focus, and re-parenting it when needed to keep the focus hierarchy in /// sync with the widget hierarchy. This widget does all of those things for /// you. See [FocusNode] for more information about the details of what node /// management entails if you are not using a [Focus] widget and you need to do /// it yourself. /// /// If the [Focus] default constructor is used, then this widget will manage any /// given [focusNode] by overwriting the appropriate values of the [focusNode] /// with the values of [FocusNode.onKey], [FocusNode.onKeyEvent], /// [FocusNode.skipTraversal], [FocusNode.canRequestFocus], and /// [FocusNode.descendantsAreFocusable] whenever the [Focus] widget is updated. /// /// If the [Focus.withExternalFocusNode] is used instead, then the values /// returned by [onKey], [onKeyEvent], [skipTraversal], [canRequestFocus], and /// [descendantsAreFocusable] will be the values in the external focus node, and /// the external focus node's values will not be overwritten when the widget is /// updated. /// /// To collect a sub-tree of nodes into an exclusive group that restricts focus /// traversal to the group, use a [FocusScope]. To collect a sub-tree of nodes /// into a group that has a specific order to its traversal but allows the /// traversal to escape the group, use a [FocusTraversalGroup]. /// /// To move the focus, use methods on [FocusNode] by getting the [FocusNode] /// through the [of] method. For instance, to move the focus to the next node in /// the focus traversal order, call `Focus.of(context).nextFocus()`. To unfocus /// a widget, call `Focus.of(context).unfocus()`. /// /// {@tool dartpad} /// This example shows how to manage focus using the [Focus] and [FocusScope] /// widgets. See [FocusNode] for a similar example that doesn't use [Focus] or /// [FocusScope]. /// /// ** See code in examples/api/lib/widgets/focus_scope/focus.0.dart ** /// {@end-tool} /// /// {@tool dartpad} /// This example shows how to wrap another widget in a [Focus] widget to make it /// focusable. It wraps a [Container], and changes the container's color when it /// is set as the [FocusManager.primaryFocus]. /// /// If you also want to handle mouse hover and/or keyboard actions on a widget, /// consider using a [FocusableActionDetector], which combines several different /// widgets to provide those capabilities. /// /// ** See code in examples/api/lib/widgets/focus_scope/focus.1.dart ** /// {@end-tool} /// /// {@tool dartpad} /// This example shows how to focus a newly-created widget immediately after it /// is created. /// /// The focus node will not actually be given the focus until after the frame in /// which it has requested focus is drawn, so it is OK to call /// [FocusNode.requestFocus] on a node which is not yet in the focus tree. /// /// ** See code in examples/api/lib/widgets/focus_scope/focus.2.dart ** /// {@end-tool} /// /// See also: /// /// * [FocusNode], which represents a node in the focus hierarchy and /// [FocusNode]'s API documentation includes a detailed explanation of its role /// in the overall focus system. /// * [FocusScope], a widget that manages a group of focusable widgets using a /// [FocusScopeNode]. /// * [FocusScopeNode], a node that collects focus nodes into a group for /// traversal. /// * [FocusManager], a singleton that manages the primary focus and /// distributes key events to focused nodes. /// * [FocusTraversalPolicy], an object used to determine how to move the focus /// to other nodes. /// * [FocusTraversalGroup], a widget that groups together and imposes a /// traversal policy on the [Focus] nodes below it in the widget hierarchy. class Focus extends StatefulWidget { /// Creates a widget that manages a [FocusNode]. const Focus({ super.key, required this.child, this.focusNode, this.parentNode, this.autofocus = false, this.onFocusChange, FocusOnKeyEventCallback? onKeyEvent, @Deprecated( 'Use onKeyEvent instead. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) FocusOnKeyCallback? onKey, bool? canRequestFocus, bool? skipTraversal, bool? descendantsAreFocusable, bool? descendantsAreTraversable, this.includeSemantics = true, String? debugLabel, }) : _onKeyEvent = onKeyEvent, _onKey = onKey, _canRequestFocus = canRequestFocus, _skipTraversal = skipTraversal, _descendantsAreFocusable = descendantsAreFocusable, _descendantsAreTraversable = descendantsAreTraversable, _debugLabel = debugLabel; /// Creates a Focus widget that uses the given [focusNode] as the source of /// truth for attributes on the node, rather than the attributes of this widget. const factory Focus.withExternalFocusNode({ Key? key, required Widget child, required FocusNode focusNode, FocusNode? parentNode, bool autofocus, ValueChanged<bool>? onFocusChange, bool includeSemantics, }) = _FocusWithExternalFocusNode; // Indicates whether the widget's focusNode attributes should have priority // when then widget is updated. bool get _usingExternalFocus => false; /// The optional parent node to use when reparenting the [focusNode] for this /// [Focus] widget. /// /// If [parentNode] is null, then [Focus.maybeOf] is used to find the parent /// in the widget tree, which is typically what is desired, since it is easier /// to reason about the focus tree if it mirrors the shape of the widget tree. /// /// Set this property if the focus tree needs to have a different shape than /// the widget tree. This is typically in cases where a dialog is in an /// [Overlay] (or another part of the widget tree), and focus should /// behave as if the widgets in the overlay are descendants of the given /// [parentNode] for purposes of focus. /// /// Defaults to null. final FocusNode? parentNode; /// The child widget of this [Focus]. /// /// {@macro flutter.widgets.ProxyWidget.child} final Widget child; /// {@template flutter.widgets.Focus.focusNode} /// An optional focus node to use as the focus node for this widget. /// /// If one is not supplied, then one will be automatically allocated, owned, /// and managed by this widget. The widget will be focusable even if a /// [focusNode] is not supplied. If supplied, the given [focusNode] will be /// _hosted_ by this widget, but not owned. See [FocusNode] for more /// information on what being hosted and/or owned implies. /// /// Supplying a focus node is sometimes useful if an ancestor to this widget /// wants to control when this widget has the focus. The owner will be /// responsible for calling [FocusNode.dispose] on the focus node when it is /// done with it, but this widget will attach/detach and reparent the node /// when needed. /// {@endtemplate} /// /// A non-null [focusNode] must be supplied if using the /// [Focus.withExternalFocusNode] constructor. final FocusNode? focusNode; /// {@template flutter.widgets.Focus.autofocus} /// True if this widget will be selected as the initial focus when no other /// node in its scope is currently focused. /// /// Ideally, there is only one widget with autofocus set in each [FocusScope]. /// If there is more than one widget with autofocus set, then the first one /// added to the tree will get focus. /// /// Defaults to false. /// {@endtemplate} final bool autofocus; /// Handler called when the focus changes. /// /// Called with true if this widget's node gains focus, and false if it loses /// focus. final ValueChanged<bool>? onFocusChange; /// A handler for keys that are pressed when this object or one of its /// children has focus. /// /// Key events are first given to the [FocusNode] that has primary focus, and /// if its [onKeyEvent] method returns [KeyEventResult.ignored], then they are /// given to each ancestor node up the focus hierarchy in turn. If an event /// reaches the root of the hierarchy, it is discarded. /// /// This is not the way to get text input in the manner of a text field: it /// leaves out support for input method editors, and doesn't support soft /// keyboards in general. For text input, consider [TextField], /// [EditableText], or [CupertinoTextField] instead, which do support these /// things. FocusOnKeyEventCallback? get onKeyEvent => _onKeyEvent ?? focusNode?.onKeyEvent; final FocusOnKeyEventCallback? _onKeyEvent; /// A handler for keys that are pressed when this object or one of its /// children has focus. /// /// This property is deprecated and will be removed. Use [onKeyEvent] instead. /// /// Key events are first given to the [FocusNode] that has primary focus, and /// if its [onKey] method return false, then they are given to each ancestor /// node up the focus hierarchy in turn. If an event reaches the root of the /// hierarchy, it is discarded. /// /// This is not the way to get text input in the manner of a text field: it /// leaves out support for input method editors, and doesn't support soft /// keyboards in general. For text input, consider [TextField], /// [EditableText], or [CupertinoTextField] instead, which do support these /// things. @Deprecated( 'Use onKeyEvent instead. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) FocusOnKeyCallback? get onKey => _onKey ?? focusNode?.onKey; final FocusOnKeyCallback? _onKey; /// {@template flutter.widgets.Focus.canRequestFocus} /// If true, this widget may request the primary focus. /// /// Defaults to true. Set to false if you want the [FocusNode] this widget /// manages to do nothing when [FocusNode.requestFocus] is called on it. Does /// not affect the children of this node, and [FocusNode.hasFocus] can still /// return true if this node is the ancestor of the primary focus. /// /// This is different than [Focus.skipTraversal] because [Focus.skipTraversal] /// still allows the widget to be focused, just not traversed to. /// /// Setting [FocusNode.canRequestFocus] to false implies that the widget will /// also be skipped for traversal purposes. /// /// See also: /// /// * [FocusTraversalGroup], a widget that sets the traversal policy for its /// descendants. /// * [FocusTraversalPolicy], a class that can be extended to describe a /// traversal policy. /// {@endtemplate} bool get canRequestFocus => _canRequestFocus ?? focusNode?.canRequestFocus ?? true; final bool? _canRequestFocus; /// Sets the [FocusNode.skipTraversal] flag on the focus node so that it won't /// be visited by the [FocusTraversalPolicy]. /// /// This is sometimes useful if a [Focus] widget should receive key events as /// part of the focus chain, but shouldn't be accessible via focus traversal. /// /// This is different from [FocusNode.canRequestFocus] because it only implies /// that the widget can't be reached via traversal, not that it can't be /// focused. It may still be focused explicitly. bool get skipTraversal => _skipTraversal ?? focusNode?.skipTraversal ?? false; final bool? _skipTraversal; /// {@template flutter.widgets.Focus.descendantsAreFocusable} /// If false, will make this widget's descendants unfocusable. /// /// Defaults to true. Does not affect focusability of this node (just its /// descendants): for that, use [FocusNode.canRequestFocus]. /// /// If any descendants are focused when this is set to false, they will be /// unfocused. When [descendantsAreFocusable] is set to true again, they will /// not be refocused, although they will be able to accept focus again. /// /// Does not affect the value of [FocusNode.canRequestFocus] on the /// descendants. /// /// If a descendant node loses focus when this value is changed, the focus /// will move to the scope enclosing this node. /// /// See also: /// /// * [ExcludeFocus], a widget that uses this property to conditionally /// exclude focus for a subtree. /// * [descendantsAreTraversable], which makes this widget's descendants /// untraversable. /// * [ExcludeFocusTraversal], a widget that conditionally excludes focus /// traversal for a subtree. /// * [FocusTraversalGroup], a widget used to group together and configure the /// focus traversal policy for a widget subtree that has a /// `descendantsAreFocusable` parameter to conditionally block focus for a /// subtree. /// {@endtemplate} bool get descendantsAreFocusable => _descendantsAreFocusable ?? focusNode?.descendantsAreFocusable ?? true; final bool? _descendantsAreFocusable; /// {@template flutter.widgets.Focus.descendantsAreTraversable} /// If false, will make this widget's descendants untraversable. /// /// Defaults to true. Does not affect traversability of this node (just its /// descendants): for that, use [FocusNode.skipTraversal]. /// /// Does not affect the value of [FocusNode.skipTraversal] on the /// descendants. Does not affect focusability of the descendants. /// /// See also: /// /// * [ExcludeFocusTraversal], a widget that uses this property to /// conditionally exclude focus traversal for a subtree. /// * [descendantsAreFocusable], which makes this widget's descendants /// unfocusable. /// * [ExcludeFocus], a widget that conditionally excludes focus for a subtree. /// * [FocusTraversalGroup], a widget used to group together and configure the /// focus traversal policy for a widget subtree that has a /// `descendantsAreFocusable` parameter to conditionally block focus for a /// subtree. /// {@endtemplate} bool get descendantsAreTraversable => _descendantsAreTraversable ?? focusNode?.descendantsAreTraversable ?? true; final bool? _descendantsAreTraversable; /// {@template flutter.widgets.Focus.includeSemantics} /// Include semantics information in this widget. /// /// If true, this widget will include a [Semantics] node that indicates the /// [SemanticsProperties.focusable] and [SemanticsProperties.focused] /// properties. /// /// It is not typical to set this to false, as that can affect the semantics /// information available to accessibility systems. /// /// Defaults to true. /// {@endtemplate} final bool includeSemantics; /// A debug label for this widget. /// /// Not used for anything except to be printed in the diagnostic output from /// [toString] or [toStringDeep]. /// /// To get a string with the entire tree, call [debugDescribeFocusTree]. To /// print it to the console call [debugDumpFocusTree]. /// /// Defaults to null. String? get debugLabel => _debugLabel ?? focusNode?.debugLabel; final String? _debugLabel; /// Returns the [focusNode] of the [Focus] that most tightly encloses the /// given [BuildContext]. /// /// If no [Focus] node is found before reaching the nearest [FocusScope] /// widget, or there is no [Focus] widget in the context, then this method /// will throw an exception. /// /// {@macro flutter.widgets.focus_scope.Focus.maybeOf} /// /// See also: /// /// * [maybeOf], which is similar to this function, but will return null /// instead of throwing if it doesn't find a [Focus] node. static FocusNode of(BuildContext context, { bool scopeOk = false, bool createDependency = true }) { final FocusNode? node = Focus.maybeOf(context, scopeOk: scopeOk, createDependency: createDependency); assert(() { if (node == null) { throw FlutterError( 'Focus.of() was called with a context that does not contain a Focus widget.\n' 'No Focus widget ancestor could be found starting from the context that was passed to ' 'Focus.of(). This can happen because you are using a widget that looks for a Focus ' 'ancestor, and do not have a Focus widget descendant in the nearest FocusScope.\n' 'The context used was:\n' ' $context', ); } return true; }()); assert(() { if (!scopeOk && node is FocusScopeNode) { throw FlutterError( 'Focus.of() was called with a context that does not contain a Focus between the given ' 'context and the nearest FocusScope widget.\n' 'No Focus ancestor could be found starting from the context that was passed to ' 'Focus.of() to the point where it found the nearest FocusScope widget. This can happen ' 'because you are using a widget that looks for a Focus ancestor, and do not have a ' 'Focus widget ancestor in the current FocusScope.\n' 'The context used was:\n' ' $context', ); } return true; }()); return node!; } /// Returns the [focusNode] of the [Focus] that most tightly encloses the /// given [BuildContext]. /// /// If no [Focus] node is found before reaching the nearest [FocusScope] /// widget, or there is no [Focus] widget in scope, then this method will /// return null. /// /// {@template flutter.widgets.focus_scope.Focus.maybeOf} /// If `createDependency` is true (which is the default), calling this /// function creates a dependency that will rebuild the given context when the /// focus node gains or loses focus. /// {@endtemplate} /// /// See also: /// /// * [of], which is similar to this function, but will throw an exception if /// it doesn't find a [Focus] node, instead of returning null. static FocusNode? maybeOf(BuildContext context, { bool scopeOk = false, bool createDependency = true }) { final _FocusInheritedScope? scope; if (createDependency) { scope = context.dependOnInheritedWidgetOfExactType<_FocusInheritedScope>(); } else { scope = context.getInheritedWidgetOfExactType<_FocusInheritedScope>(); } final FocusNode? node = scope?.notifier; if (node == null) { return null; } if (!scopeOk && node is FocusScopeNode) { return null; } return node; } /// Returns true if the nearest enclosing [Focus] widget's node is focused. /// /// A convenience method to allow build methods to write: /// `Focus.isAt(context)` to get whether or not the nearest [Focus] above them /// in the widget hierarchy currently has the input focus. /// /// Returns false if no [Focus] widget is found before reaching the nearest /// [FocusScope], or if the root of the focus tree is reached without finding /// a [Focus] widget. /// /// Calling this function creates a dependency that will rebuild the given /// context when the focus changes. static bool isAt(BuildContext context) => Focus.maybeOf(context)?.hasFocus ?? false; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(StringProperty('debugLabel', debugLabel, defaultValue: null)); properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'AUTOFOCUS', defaultValue: false)); properties.add(FlagProperty('canRequestFocus', value: canRequestFocus, ifFalse: 'NOT FOCUSABLE', defaultValue: false)); properties.add(FlagProperty('descendantsAreFocusable', value: descendantsAreFocusable, ifFalse: 'DESCENDANTS UNFOCUSABLE', defaultValue: true)); properties.add(FlagProperty('descendantsAreTraversable', value: descendantsAreTraversable, ifFalse: 'DESCENDANTS UNTRAVERSABLE', defaultValue: true)); properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode, defaultValue: null)); } @override State<Focus> createState() => _FocusState(); } // Implements the behavior differences when the Focus.withExternalFocusNode // constructor is used. class _FocusWithExternalFocusNode extends Focus { const _FocusWithExternalFocusNode({ super.key, required super.child, required FocusNode super.focusNode, super.parentNode, super.autofocus, super.onFocusChange, super.includeSemantics, }); @override bool get _usingExternalFocus => true; @override FocusOnKeyEventCallback? get onKeyEvent => focusNode!.onKeyEvent; @override FocusOnKeyCallback? get onKey => focusNode!.onKey; @override bool get canRequestFocus => focusNode!.canRequestFocus; @override bool get skipTraversal => focusNode!.skipTraversal; @override bool get descendantsAreFocusable => focusNode!.descendantsAreFocusable; @override bool? get _descendantsAreTraversable => focusNode!.descendantsAreTraversable; @override String? get debugLabel => focusNode!.debugLabel; } class _FocusState extends State<Focus> { FocusNode? _internalNode; FocusNode get focusNode => widget.focusNode ?? (_internalNode ??= _createNode()); late bool _hadPrimaryFocus; late bool _couldRequestFocus; late bool _descendantsWereFocusable; late bool _descendantsWereTraversable; bool _didAutofocus = false; FocusAttachment? _focusAttachment; @override void initState() { super.initState(); _initNode(); } void _initNode() { if (!widget._usingExternalFocus) { focusNode.descendantsAreFocusable = widget.descendantsAreFocusable; focusNode.descendantsAreTraversable = widget.descendantsAreTraversable; focusNode.skipTraversal = widget.skipTraversal; if (widget._canRequestFocus != null) { focusNode.canRequestFocus = widget._canRequestFocus!; } } _couldRequestFocus = focusNode.canRequestFocus; _descendantsWereFocusable = focusNode.descendantsAreFocusable; _descendantsWereTraversable = focusNode.descendantsAreTraversable; _hadPrimaryFocus = focusNode.hasPrimaryFocus; _focusAttachment = focusNode.attach(context, onKeyEvent: widget.onKeyEvent, onKey: widget.onKey); // Add listener even if the _internalNode existed before, since it should // not be listening now if we're re-using a previous one because it should // have already removed its listener. focusNode.addListener(_handleFocusChanged); } FocusNode _createNode() { return FocusNode( debugLabel: widget.debugLabel, canRequestFocus: widget.canRequestFocus, descendantsAreFocusable: widget.descendantsAreFocusable, descendantsAreTraversable: widget.descendantsAreTraversable, skipTraversal: widget.skipTraversal, ); } @override void dispose() { // Regardless of the node owner, we need to remove it from the tree and stop // listening to it. focusNode.removeListener(_handleFocusChanged); _focusAttachment!.detach(); // Don't manage the lifetime of external nodes given to the widget, just the // internal node. _internalNode?.dispose(); super.dispose(); } @override void didChangeDependencies() { super.didChangeDependencies(); _focusAttachment?.reparent(); _handleAutofocus(); } void _handleAutofocus() { if (!_didAutofocus && widget.autofocus) { FocusScope.of(context).autofocus(focusNode); _didAutofocus = true; } } @override void deactivate() { super.deactivate(); // The focus node's location in the tree is no longer valid here. But // we can't unfocus or remove the node from the tree because if the widget // is moved to a different part of the tree (via global key) it should // retain its focus state. That's why we temporarily park it on the root // focus node (via reparent) until it either gets moved to a different part // of the tree (via didChangeDependencies) or until it is disposed. _focusAttachment?.reparent(); _didAutofocus = false; } @override void didUpdateWidget(Focus oldWidget) { super.didUpdateWidget(oldWidget); assert(() { // Only update the debug label in debug builds. if (oldWidget.focusNode == widget.focusNode && !widget._usingExternalFocus && oldWidget.debugLabel != widget.debugLabel) { focusNode.debugLabel = widget.debugLabel; } return true; }()); if (oldWidget.focusNode == widget.focusNode) { if (!widget._usingExternalFocus) { if (widget.onKey != focusNode.onKey) { focusNode.onKey = widget.onKey; } if (widget.onKeyEvent != focusNode.onKeyEvent) { focusNode.onKeyEvent = widget.onKeyEvent; } focusNode.skipTraversal = widget.skipTraversal; if (widget._canRequestFocus != null) { focusNode.canRequestFocus = widget._canRequestFocus!; } focusNode.descendantsAreFocusable = widget.descendantsAreFocusable; focusNode.descendantsAreTraversable = widget.descendantsAreTraversable; } } else { _focusAttachment!.detach(); oldWidget.focusNode?.removeListener(_handleFocusChanged); _initNode(); } if (oldWidget.autofocus != widget.autofocus) { _handleAutofocus(); } } void _handleFocusChanged() { final bool hasPrimaryFocus = focusNode.hasPrimaryFocus; final bool canRequestFocus = focusNode.canRequestFocus; final bool descendantsAreFocusable = focusNode.descendantsAreFocusable; final bool descendantsAreTraversable = focusNode.descendantsAreTraversable; widget.onFocusChange?.call(focusNode.hasFocus); // Check the cached states that matter here, and call setState if they have // changed. if (_hadPrimaryFocus != hasPrimaryFocus) { setState(() { _hadPrimaryFocus = hasPrimaryFocus; }); } if (_couldRequestFocus != canRequestFocus) { setState(() { _couldRequestFocus = canRequestFocus; }); } if (_descendantsWereFocusable != descendantsAreFocusable) { setState(() { _descendantsWereFocusable = descendantsAreFocusable; }); } if (_descendantsWereTraversable != descendantsAreTraversable) { setState(() { _descendantsWereTraversable = descendantsAreTraversable; }); } } @override Widget build(BuildContext context) { _focusAttachment!.reparent(parent: widget.parentNode); Widget child = widget.child; if (widget.includeSemantics) { child = Semantics( focusable: _couldRequestFocus, focused: _hadPrimaryFocus, child: widget.child, ); } return _FocusInheritedScope( node: focusNode, child: child, ); } } /// A [FocusScope] is similar to a [Focus], but also serves as a scope for its /// descendants, restricting focus traversal to the scoped controls. /// /// For example a new [FocusScope] is created automatically when a route is /// pushed, keeping the focus traversal from moving to a control in a previous /// route. /// /// If you just want to group widgets together in a group so that they are /// traversed in a particular order, but the focus can still leave the group, /// use a [FocusTraversalGroup]. /// /// Like [Focus], [FocusScope] provides an [onFocusChange] as a way to be /// notified when the focus is given to or removed from this widget. /// /// The [onKey] argument allows specification of a key event handler that is /// invoked when this node or one of its children has focus. Keys are handed to /// the primary focused widget first, and then they propagate through the /// ancestors of that node, stopping if one of them returns /// [KeyEventResult.handled] from [onKey], indicating that it has handled the /// event. /// /// Managing a [FocusScopeNode] means managing its lifecycle, listening for /// changes in focus, and re-parenting it when needed to keep the focus /// hierarchy in sync with the widget hierarchy. This widget does all of those /// things for you. See [FocusScopeNode] for more information about the details /// of what node management entails if you are not using a [FocusScope] widget /// and you need to do it yourself. /// /// [FocusScopeNode]s remember the last [FocusNode] that was focused within /// their descendants, and can move that focus to the next/previous node, or a /// node in a particular direction when the [FocusNode.nextFocus], /// [FocusNode.previousFocus], or [FocusNode.focusInDirection] are called on a /// [FocusNode] or [FocusScopeNode]. /// /// To move the focus, use methods on [FocusNode] by getting the [FocusNode] /// through the [of] method. For instance, to move the focus to the next node in /// the focus traversal order, call `Focus.of(context).nextFocus()`. To unfocus /// a widget, call `Focus.of(context).unfocus()`. /// /// {@tool dartpad} /// This example demonstrates using a [FocusScope] to restrict focus to a particular /// portion of the app. In this case, restricting focus to the visible part of a /// Stack. /// /// ** See code in examples/api/lib/widgets/focus_scope/focus_scope.0.dart ** /// {@end-tool} /// /// See also: /// /// * [FocusScopeNode], which represents a scope node in the focus hierarchy. /// * [FocusNode], which represents a node in the focus hierarchy and has an /// explanation of the focus system. /// * [Focus], a widget that manages a [FocusNode] and allows easy access to /// managing focus without having to manage the node. /// * [FocusManager], a singleton that manages the focus and distributes key /// events to focused nodes. /// * [FocusTraversalPolicy], an object used to determine how to move the focus /// to other nodes. /// * [FocusTraversalGroup], a widget used to configure the focus traversal /// policy for a widget subtree. class FocusScope extends Focus { /// Creates a widget that manages a [FocusScopeNode]. const FocusScope({ super.key, FocusScopeNode? node, super.parentNode, required super.child, super.autofocus, super.onFocusChange, super.canRequestFocus, super.skipTraversal, super.onKeyEvent, super.onKey, super.debugLabel, }) : super( focusNode: node, ); /// Creates a FocusScope widget that uses the given [focusScopeNode] as the /// source of truth for attributes on the node, rather than the attributes of /// this widget. const factory FocusScope.withExternalFocusNode({ Key? key, required Widget child, required FocusScopeNode focusScopeNode, FocusNode? parentNode, bool autofocus, ValueChanged<bool>? onFocusChange, }) = _FocusScopeWithExternalFocusNode; /// Returns the [FocusNode.nearestScope] of the [Focus] or [FocusScope] that /// most tightly encloses the given [context]. /// /// If this node doesn't have a [Focus] or [FocusScope] widget ancestor, then /// the [FocusManager.rootScope] is returned. /// /// {@macro flutter.widgets.focus_scope.Focus.maybeOf} static FocusScopeNode of(BuildContext context, { bool createDependency = true }) { return Focus.maybeOf(context, scopeOk: true, createDependency: createDependency)?.nearestScope ?? context.owner!.focusManager.rootScope; } @override State<Focus> createState() => _FocusScopeState(); } // Implements the behavior differences when the FocusScope.withExternalFocusNode // constructor is used. class _FocusScopeWithExternalFocusNode extends FocusScope { const _FocusScopeWithExternalFocusNode({ super.key, required super.child, required FocusScopeNode focusScopeNode, super.parentNode, super.autofocus, super.onFocusChange, }) : super( node: focusScopeNode, ); @override bool get _usingExternalFocus => true; @override FocusOnKeyEventCallback? get onKeyEvent => focusNode!.onKeyEvent; @override FocusOnKeyCallback? get onKey => focusNode!.onKey; @override bool get canRequestFocus => focusNode!.canRequestFocus; @override bool get skipTraversal => focusNode!.skipTraversal; @override bool get descendantsAreFocusable => focusNode!.descendantsAreFocusable; @override bool get descendantsAreTraversable => focusNode!.descendantsAreTraversable; @override String? get debugLabel => focusNode!.debugLabel; } class _FocusScopeState extends _FocusState { @override FocusScopeNode _createNode() { return FocusScopeNode( debugLabel: widget.debugLabel, canRequestFocus: widget.canRequestFocus, skipTraversal: widget.skipTraversal, ); } @override Widget build(BuildContext context) { _focusAttachment!.reparent(parent: widget.parentNode); return Semantics( explicitChildNodes: true, child: _FocusInheritedScope( node: focusNode, child: widget.child, ), ); } } // The InheritedWidget for Focus and FocusScope. class _FocusInheritedScope extends InheritedNotifier<FocusNode> { const _FocusInheritedScope({ required FocusNode node, required super.child, }) : super(notifier: node); } /// A widget that controls whether or not the descendants of this widget are /// focusable. /// /// Does not affect the value of [Focus.canRequestFocus] on the descendants. /// /// See also: /// /// * [Focus], a widget for adding and managing a [FocusNode] in the widget tree. /// * [FocusTraversalGroup], a widget that groups widgets for focus traversal, /// and can also be used in the same way as this widget by setting its /// `descendantsAreFocusable` attribute. class ExcludeFocus extends StatelessWidget { /// Const constructor for [ExcludeFocus] widget. const ExcludeFocus({ super.key, this.excluding = true, required this.child, }); /// If true, will make this widget's descendants unfocusable. /// /// Defaults to true. /// /// If any descendants are focused when this is set to true, they will be /// unfocused. When [excluding] is set to false again, they will not be /// refocused, although they will be able to accept focus again. /// /// Does not affect the value of [FocusNode.canRequestFocus] on the /// descendants. /// /// See also: /// /// * [Focus.descendantsAreFocusable], the attribute of a [Focus] widget that /// controls this same property for focus widgets. /// * [FocusTraversalGroup], a widget used to group together and configure the /// focus traversal policy for a widget subtree that has a /// `descendantsAreFocusable` parameter to conditionally block focus for a /// subtree. final bool excluding; /// The child widget of this [ExcludeFocus]. /// /// {@macro flutter.widgets.ProxyWidget.child} final Widget child; @override Widget build(BuildContext context) { return Focus( canRequestFocus: false, skipTraversal: true, includeSemantics: false, descendantsAreFocusable: !excluding, child: child, ); } }
flutter/packages/flutter/lib/src/widgets/focus_scope.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/focus_scope.dart", "repo_id": "flutter", "token_count": 10894 }
693
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'framework.dart'; /// An inherited widget for a [Listenable] [notifier], which updates its /// dependencies when the [notifier] is triggered. /// /// This is a variant of [InheritedWidget], specialized for subclasses of /// [Listenable], such as [ChangeNotifier] or [ValueNotifier]. /// /// Dependents are notified whenever the [notifier] sends notifications, or /// whenever the identity of the [notifier] changes. /// /// Multiple notifications are coalesced, so that dependents only rebuild once /// even if the [notifier] fires multiple times between two frames. /// /// Typically this class is subclassed with a class that provides an `of` static /// method that calls [BuildContext.dependOnInheritedWidgetOfExactType] with that /// class. /// /// The [updateShouldNotify] method may also be overridden, to change the logic /// in the cases where [notifier] itself is changed. The [updateShouldNotify] /// method is called with the old [notifier] in the case of the [notifier] being /// changed. When it returns true, the dependents are marked as needing to be /// rebuilt this frame. /// /// {@tool dartpad} /// This example shows three spinning squares that use the value of the notifier /// on an ancestor [InheritedNotifier] (`SpinModel`) to give them their /// rotation. The [InheritedNotifier] doesn't need to know about the children, /// and the `notifier` argument doesn't need to be an animation controller, it /// can be anything that implements [Listenable] (like a [ChangeNotifier]). /// /// The `SpinModel` class could just as easily listen to another object (say, a /// separate object that keeps the value of an input or data model value) that /// is a [Listenable], and get the value from that. The descendants also don't /// need to have an instance of the [InheritedNotifier] in order to use it, they /// just need to know that there is one in their ancestry. This can help with /// decoupling widgets from their models. /// /// ** See code in examples/api/lib/widgets/inherited_notifier/inherited_notifier.0.dart ** /// {@end-tool} /// /// See also: /// /// * [Animation], an implementation of [Listenable] that ticks each frame to /// update a value. /// * [ViewportOffset] or its subclass [ScrollPosition], implementations of /// [Listenable] that trigger when a view is scrolled. /// * [InheritedWidget], an inherited widget that only notifies dependents /// when its value is different. /// * [InheritedModel], an inherited widget that allows clients to subscribe /// to changes for subparts of the value. abstract class InheritedNotifier<T extends Listenable> extends InheritedWidget { /// Create an inherited widget that updates its dependents when [notifier] /// sends notifications. const InheritedNotifier({ super.key, this.notifier, required super.child, }); /// The [Listenable] object to which to listen. /// /// Whenever this object sends change notifications, the dependents of this /// widget are triggered. /// /// By default, whenever the [notifier] is changed (including when changing to /// or from null), if the old notifier is not equal to the new notifier (as /// determined by the `==` operator), notifications are sent. This behavior /// can be overridden by overriding [updateShouldNotify]. /// /// While the [notifier] is null, no notifications are sent, since the null /// object cannot itself send notifications. final T? notifier; @override bool updateShouldNotify(InheritedNotifier<T> oldWidget) { return oldWidget.notifier != notifier; } @override InheritedElement createElement() => _InheritedNotifierElement<T>(this); } class _InheritedNotifierElement<T extends Listenable> extends InheritedElement { _InheritedNotifierElement(InheritedNotifier<T> widget) : super(widget) { widget.notifier?.addListener(_handleUpdate); } bool _dirty = false; @override void update(InheritedNotifier<T> newWidget) { final T? oldNotifier = (widget as InheritedNotifier<T>).notifier; final T? newNotifier = newWidget.notifier; if (oldNotifier != newNotifier) { oldNotifier?.removeListener(_handleUpdate); newNotifier?.addListener(_handleUpdate); } super.update(newWidget); } @override Widget build() { if (_dirty) { notifyClients(widget as InheritedNotifier<T>); } return super.build(); } void _handleUpdate() { _dirty = true; markNeedsBuild(); } @override void notifyClients(InheritedNotifier<T> oldWidget) { super.notifyClients(oldWidget); _dirty = false; } @override void unmount() { (widget as InheritedNotifier<T>).notifier?.removeListener(_handleUpdate); super.unmount(); } }
flutter/packages/flutter/lib/src/widgets/inherited_notifier.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/inherited_notifier.dart", "repo_id": "flutter", "token_count": 1429 }
694
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'basic.dart'; import 'framework.dart'; import 'layout_builder.dart'; import 'media_query.dart'; /// Signature for a function that builds a widget given an [Orientation]. /// /// Used by [OrientationBuilder.builder]. typedef OrientationWidgetBuilder = Widget Function(BuildContext context, Orientation orientation); /// Builds a widget tree that can depend on the parent widget's orientation /// (distinct from the device orientation). /// /// See also: /// /// * [LayoutBuilder], which exposes the complete constraints, not just the /// orientation. /// * [CustomSingleChildLayout], which positions its child during layout. /// * [CustomMultiChildLayout], with which you can define the precise layout /// of a list of children during the layout phase. /// * [MediaQueryData.orientation], which exposes whether the device is in /// landscape or portrait mode. class OrientationBuilder extends StatelessWidget { /// Creates an orientation builder. const OrientationBuilder({ super.key, required this.builder, }); /// Builds the widgets below this widget given this widget's orientation. /// /// A widget's orientation is a factor of its width relative to its /// height. For example, a [Column] widget will have a landscape orientation /// if its width exceeds its height, even though it displays its children in /// a vertical array. final OrientationWidgetBuilder builder; Widget _buildWithConstraints(BuildContext context, BoxConstraints constraints) { // If the constraints are fully unbounded (i.e., maxWidth and maxHeight are // both infinite), we prefer Orientation.portrait because its more common to // scroll vertically then horizontally. final Orientation orientation = constraints.maxWidth > constraints.maxHeight ? Orientation.landscape : Orientation.portrait; return builder(context, orientation); } @override Widget build(BuildContext context) { return LayoutBuilder(builder: _buildWithConstraints); } }
flutter/packages/flutter/lib/src/widgets/orientation_builder.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/orientation_builder.dart", "repo_id": "flutter", "token_count": 560 }
695
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'basic.dart'; import 'debug.dart'; import 'framework.dart'; import 'inherited_theme.dart'; import 'localizations.dart'; import 'media_query.dart'; import 'overlay.dart'; import 'scroll_controller.dart'; import 'scroll_delegate.dart'; import 'scroll_physics.dart'; import 'scroll_view.dart'; import 'scrollable.dart'; import 'scrollable_helpers.dart'; import 'sliver.dart'; import 'sliver_prototype_extent_list.dart'; import 'sliver_varied_extent_list.dart'; import 'ticker_provider.dart'; import 'transitions.dart'; // Examples can assume: // class MyDataObject {} /// A callback used by [ReorderableList] to report that a list item has moved /// to a new position in the list. /// /// Implementations should remove the corresponding list item at [oldIndex] /// and reinsert it at [newIndex]. /// /// If [oldIndex] is before [newIndex], removing the item at [oldIndex] from the /// list will reduce the list's length by one. Implementations will need to /// account for this when inserting before [newIndex]. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=3fB1mxOsqJE} /// /// {@tool snippet} /// /// ```dart /// final List<MyDataObject> backingList = <MyDataObject>[/* ... */]; /// /// void handleReorder(int oldIndex, int newIndex) { /// if (oldIndex < newIndex) { /// // removing the item at oldIndex will shorten the list by 1. /// newIndex -= 1; /// } /// final MyDataObject element = backingList.removeAt(oldIndex); /// backingList.insert(newIndex, element); /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [ReorderableList], a widget list that allows the user to reorder /// its items. /// * [SliverReorderableList], a sliver list that allows the user to reorder /// its items. /// * [ReorderableListView], a Material Design list that allows the user to /// reorder its items. typedef ReorderCallback = void Function(int oldIndex, int newIndex); /// Signature for the builder callback used to decorate the dragging item in /// [ReorderableList] and [SliverReorderableList]. /// /// The [child] will be the item that is being dragged, and [index] is the /// position of the item in the list. /// /// The [animation] will be driven forward from 0.0 to 1.0 while the item is /// being picked up during a drag operation, and reversed from 1.0 to 0.0 when /// the item is dropped. This can be used to animate properties of the proxy /// like an elevation or border. /// /// The returned value will typically be the [child] wrapped in other widgets. typedef ReorderItemProxyDecorator = Widget Function(Widget child, int index, Animation<double> animation); /// A scrolling container that allows the user to interactively reorder the /// list items. /// /// This widget is similar to one created by [ListView.builder], and uses /// an [IndexedWidgetBuilder] to create each item. /// /// It is up to the application to wrap each child (or an internal part of the /// child such as a drag handle) with a drag listener that will recognize /// the start of an item drag and then start the reorder by calling /// [ReorderableListState.startItemDragReorder]. This is most easily achieved /// by wrapping each child in a [ReorderableDragStartListener] or a /// [ReorderableDelayedDragStartListener]. These will take care of recognizing /// the start of a drag gesture and call the list state's /// [ReorderableListState.startItemDragReorder] method. /// /// This widget's [ReorderableListState] can be used to manually start an item /// reorder, or cancel a current drag. To refer to the /// [ReorderableListState] either provide a [GlobalKey] or use the static /// [ReorderableList.of] method from an item's build method. /// /// See also: /// /// * [SliverReorderableList], a sliver list that allows the user to reorder /// its items. /// * [ReorderableListView], a Material Design list that allows the user to /// reorder its items. class ReorderableList extends StatefulWidget { /// Creates a scrolling container that allows the user to interactively /// reorder the list items. /// /// The [itemCount] must be greater than or equal to zero. const ReorderableList({ super.key, required this.itemBuilder, required this.itemCount, required this.onReorder, this.onReorderStart, this.onReorderEnd, this.itemExtent, this.itemExtentBuilder, this.prototypeItem, this.proxyDecorator, this.padding, this.scrollDirection = Axis.vertical, this.reverse = false, this.controller, 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.', ); /// {@template flutter.widgets.reorderable_list.itemBuilder} /// Called, as needed, to build list item widgets. /// /// List items are only built when they're scrolled into view. /// /// The [IndexedWidgetBuilder] index parameter indicates the item's /// position in the list. The value of the index parameter will be between /// zero and one less than [itemCount]. All items in the list must have a /// unique [Key], and should have some kind of listener to start the drag /// (usually a [ReorderableDragStartListener] or /// [ReorderableDelayedDragStartListener]). /// {@endtemplate} final IndexedWidgetBuilder itemBuilder; /// {@template flutter.widgets.reorderable_list.itemCount} /// The number of items in the list. /// /// It must be a non-negative integer. When zero, nothing is displayed and /// the widget occupies no space. /// {@endtemplate} final int itemCount; /// {@template flutter.widgets.reorderable_list.onReorder} /// A callback used by the list to report that a list item has been dragged /// to a new location in the list and the application should update the order /// of the items. /// {@endtemplate} final ReorderCallback onReorder; /// {@template flutter.widgets.reorderable_list.onReorderStart} /// A callback that is called when an item drag has started. /// /// The index parameter of the callback is the index of the selected item. /// /// See also: /// /// * [onReorderEnd], which is a called when the dragged item is dropped. /// * [onReorder], which reports that a list item has been dragged to a new /// location. /// {@endtemplate} final void Function(int index)? onReorderStart; /// {@template flutter.widgets.reorderable_list.onReorderEnd} /// A callback that is called when the dragged item is dropped. /// /// The index parameter of the callback is the index where the item is /// dropped. Unlike [onReorder], this is called even when the list item is /// dropped in the same location. /// /// See also: /// /// * [onReorderStart], which is a called when an item drag has started. /// * [onReorder], which reports that a list item has been dragged to a new /// location. /// {@endtemplate} final void Function(int index)? onReorderEnd; /// {@template flutter.widgets.reorderable_list.proxyDecorator} /// A callback that allows the app to add an animated decoration around /// an item when it is being dragged. /// {@endtemplate} final ReorderItemProxyDecorator? proxyDecorator; /// {@template flutter.widgets.reorderable_list.padding} /// The amount of space by which to inset the list contents. /// /// It defaults to `EdgeInsets.all(0)`. /// {@endtemplate} final EdgeInsetsGeometry? padding; /// {@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? controller; /// {@macro flutter.widgets.scroll_view.primary} 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; /// The state from the closest instance of this class that encloses the given /// context. /// /// This method is typically used by [ReorderableList] item widgets that /// insert or remove items in response to user input. /// /// If no [ReorderableList] surrounds the given context, then this function /// will assert in debug mode and throw an exception in release mode. /// /// This method can be expensive (it walks the element tree). /// /// See also: /// /// * [maybeOf], a similar function that will return null if no /// [ReorderableList] ancestor is found. static ReorderableListState of(BuildContext context) { final ReorderableListState? result = context.findAncestorStateOfType<ReorderableListState>(); assert(() { if (result == null) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('ReorderableList.of() called with a context that does not contain a ReorderableList.'), ErrorDescription( 'No ReorderableList ancestor could be found starting from the context that was passed to ReorderableList.of().', ), ErrorHint( 'This can happen when the context provided is from the same StatefulWidget that ' 'built the ReorderableList. Please see the ReorderableList documentation for examples ' 'of how to refer to an ReorderableListState object:\n' ' https://api.flutter.dev/flutter/widgets/ReorderableListState-class.html', ), context.describeElement('The context used was'), ]); } return true; }()); return result!; } /// The state from the closest instance of this class that encloses the given /// context. /// /// This method is typically used by [ReorderableList] item widgets that insert /// or remove items in response to user input. /// /// If no [ReorderableList] surrounds the context given, then this function will /// return null. /// /// This method can be expensive (it walks the element tree). /// /// See also: /// /// * [of], a similar function that will throw if no [ReorderableList] ancestor /// is found. static ReorderableListState? maybeOf(BuildContext context) { return context.findAncestorStateOfType<ReorderableListState>(); } @override ReorderableListState createState() => ReorderableListState(); } /// The state for a list that allows the user to interactively reorder /// the list items. /// /// An app that needs to start a new item drag or cancel an existing one /// can refer to the [ReorderableList]'s state with a global key: /// /// ```dart /// GlobalKey<ReorderableListState> listKey = GlobalKey<ReorderableListState>(); /// // ... /// Widget build(BuildContext context) { /// return ReorderableList( /// key: listKey, /// itemBuilder: (BuildContext context, int index) => const SizedBox(height: 10.0), /// itemCount: 5, /// onReorder: (int oldIndex, int newIndex) { /// // ... /// }, /// ); /// } /// // ... /// listKey.currentState!.cancelReorder(); /// ``` class ReorderableListState extends State<ReorderableList> { final GlobalKey<SliverReorderableListState> _sliverReorderableListKey = GlobalKey(); /// Initiate the dragging of the item at [index] that was started with /// the pointer down [event]. /// /// The given [recognizer] will be used to recognize and start the drag /// item tracking and lead to either an item reorder, or a canceled drag. /// The list will take ownership of the returned recognizer and will dispose /// it when it is no longer needed. /// /// Most applications will not use this directly, but will wrap the item /// (or part of the item, like a drag handle) in either a /// [ReorderableDragStartListener] or [ReorderableDelayedDragStartListener] /// which call this for the application. void startItemDragReorder({ required int index, required PointerDownEvent event, required MultiDragGestureRecognizer recognizer, }) { _sliverReorderableListKey.currentState!.startItemDragReorder(index: index, event: event, recognizer: recognizer); } /// Cancel any item drag in progress. /// /// This should be called before any major changes to the item list /// occur so that any item drags will not get confused by /// changes to the underlying list. /// /// If no drag is active, this will do nothing. void cancelReorder() { _sliverReorderableListKey.currentState!.cancelReorder(); } @override Widget build(BuildContext context) { return CustomScrollView( scrollDirection: widget.scrollDirection, reverse: widget.reverse, controller: widget.controller, 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>[ SliverPadding( padding: widget.padding ?? EdgeInsets.zero, sliver: SliverReorderableList( key: _sliverReorderableListKey, itemExtent: widget.itemExtent, prototypeItem: widget.prototypeItem, itemBuilder: widget.itemBuilder, itemCount: widget.itemCount, onReorder: widget.onReorder, onReorderStart: widget.onReorderStart, onReorderEnd: widget.onReorderEnd, proxyDecorator: widget.proxyDecorator, autoScrollerVelocityScalar: widget.autoScrollerVelocityScalar, ), ), ], ); } } /// A sliver list that allows the user to interactively reorder the list items. /// /// It is up to the application to wrap each child (or an internal part of the /// child) with a drag listener that will recognize the start of an item drag /// and then start the reorder by calling /// [SliverReorderableListState.startItemDragReorder]. This is most easily /// achieved by wrapping each child in a [ReorderableDragStartListener] or /// a [ReorderableDelayedDragStartListener]. These will take care of /// recognizing the start of a drag gesture and call the list state's start /// item drag method. /// /// This widget's [SliverReorderableListState] can be used to manually start an item /// reorder, or cancel a current drag that's already underway. To refer to the /// [SliverReorderableListState] either provide a [GlobalKey] or use the static /// [SliverReorderableList.of] method from an item's build method. /// /// See also: /// /// * [ReorderableList], a regular widget list that allows the user to reorder /// its items. /// * [ReorderableListView], a Material Design list that allows the user to /// reorder its items. class SliverReorderableList extends StatefulWidget { /// Creates a sliver list that allows the user to interactively reorder its /// items. /// /// The [itemCount] must be greater than or equal to zero. const SliverReorderableList({ super.key, required this.itemBuilder, this.findChildIndexCallback, required this.itemCount, required this.onReorder, this.onReorderStart, this.onReorderEnd, this.itemExtent, this.itemExtentBuilder, this.prototypeItem, this.proxyDecorator, double? autoScrollerVelocityScalar, }) : autoScrollerVelocityScalar = autoScrollerVelocityScalar ?? _kDefaultAutoScrollVelocityScalar, 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.', ); // An eyeballed value for a smooth scrolling experience. static const double _kDefaultAutoScrollVelocityScalar = 50; /// {@macro flutter.widgets.reorderable_list.itemBuilder} final IndexedWidgetBuilder itemBuilder; /// {@macro flutter.widgets.SliverChildBuilderDelegate.findChildIndexCallback} final ChildIndexGetter? findChildIndexCallback; /// {@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)? onReorderStart; /// {@macro flutter.widgets.reorderable_list.onReorderEnd} final void Function(int)? onReorderEnd; /// {@macro flutter.widgets.reorderable_list.proxyDecorator} final ReorderItemProxyDecorator? proxyDecorator; /// {@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} /// /// {@template flutter.widgets.SliverReorderableList.autoScrollerVelocityScalar.default} /// Defaults to 50 if not set or set to null. /// {@endtemplate} final double autoScrollerVelocityScalar; @override SliverReorderableListState createState() => SliverReorderableListState(); /// The state from the closest instance of this class that encloses the given /// context. /// /// This method is typically used by [SliverReorderableList] item widgets to /// start or cancel an item drag operation. /// /// If no [SliverReorderableList] surrounds the context given, this function /// will assert in debug mode and throw an exception in release mode. /// /// This method can be expensive (it walks the element tree). /// /// See also: /// /// * [maybeOf], a similar function that will return null if no /// [SliverReorderableList] ancestor is found. static SliverReorderableListState of(BuildContext context) { final SliverReorderableListState? result = context.findAncestorStateOfType<SliverReorderableListState>(); assert(() { if (result == null) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary( 'SliverReorderableList.of() called with a context that does not contain a SliverReorderableList.', ), ErrorDescription( 'No SliverReorderableList ancestor could be found starting from the context that was passed to SliverReorderableList.of().', ), ErrorHint( 'This can happen when the context provided is from the same StatefulWidget that ' 'built the SliverReorderableList. Please see the SliverReorderableList documentation for examples ' 'of how to refer to an SliverReorderableList object:\n' ' https://api.flutter.dev/flutter/widgets/SliverReorderableListState-class.html', ), context.describeElement('The context used was'), ]); } return true; }()); return result!; } /// The state from the closest instance of this class that encloses the given /// context. /// /// This method is typically used by [SliverReorderableList] item widgets that /// insert or remove items in response to user input. /// /// If no [SliverReorderableList] surrounds the context given, this function /// will return null. /// /// This method can be expensive (it walks the element tree). /// /// See also: /// /// * [of], a similar function that will throw if no [SliverReorderableList] /// ancestor is found. static SliverReorderableListState? maybeOf(BuildContext context) { return context.findAncestorStateOfType<SliverReorderableListState>(); } } /// The state for a sliver list that allows the user to interactively reorder /// the list items. /// /// An app that needs to start a new item drag or cancel an existing one /// can refer to the [SliverReorderableList]'s state with a global key: /// /// ```dart /// // (e.g. in a stateful widget) /// GlobalKey<SliverReorderableListState> listKey = GlobalKey<SliverReorderableListState>(); /// /// // ... /// /// @override /// Widget build(BuildContext context) { /// return SliverReorderableList( /// key: listKey, /// itemBuilder: (BuildContext context, int index) => const SizedBox(height: 10.0), /// itemCount: 5, /// onReorder: (int oldIndex, int newIndex) { /// // ... /// }, /// ); /// } /// /// // ... /// /// void _stop() { /// listKey.currentState!.cancelReorder(); /// } /// ``` /// /// [ReorderableDragStartListener] and [ReorderableDelayedDragStartListener] /// refer to their [SliverReorderableList] with the static /// [SliverReorderableList.of] method. class SliverReorderableListState extends State<SliverReorderableList> with TickerProviderStateMixin { // Map of index -> child state used manage where the dragging item will need // to be inserted. final Map<int, _ReorderableItemState> _items = <int, _ReorderableItemState>{}; OverlayEntry? _overlayEntry; int? _dragIndex; _DragInfo? _dragInfo; int? _insertIndex; Offset? _finalDropPosition; MultiDragGestureRecognizer? _recognizer; int? _recognizerPointer; EdgeDraggingAutoScroller? _autoScroller; late ScrollableState _scrollable; Axis get _scrollDirection => axisDirectionToAxis(_scrollable.axisDirection); bool get _reverse => _scrollable.axisDirection == AxisDirection.up || _scrollable.axisDirection == AxisDirection.left; @override void didChangeDependencies() { super.didChangeDependencies(); _scrollable = Scrollable.of(context); if (_autoScroller?.scrollable != _scrollable) { _autoScroller?.stopAutoScroll(); _autoScroller = EdgeDraggingAutoScroller( _scrollable, onScrollViewScrolled: _handleScrollableAutoScrolled, velocityScalar: widget.autoScrollerVelocityScalar, ); } } @override void didUpdateWidget(covariant SliverReorderableList oldWidget) { super.didUpdateWidget(oldWidget); if (widget.itemCount != oldWidget.itemCount) { cancelReorder(); } if (widget.autoScrollerVelocityScalar != oldWidget.autoScrollerVelocityScalar) { _autoScroller?.stopAutoScroll(); _autoScroller = EdgeDraggingAutoScroller( _scrollable, onScrollViewScrolled: _handleScrollableAutoScrolled, velocityScalar: widget.autoScrollerVelocityScalar, ); } } @override void dispose() { _dragReset(); _recognizer?.dispose(); super.dispose(); } /// Initiate the dragging of the item at [index] that was started with /// the pointer down [event]. /// /// The given [recognizer] will be used to recognize and start the drag /// item tracking and lead to either an item reorder, or a canceled drag. /// /// Most applications will not use this directly, but will wrap the item /// (or part of the item, like a drag handle) in either a /// [ReorderableDragStartListener] or [ReorderableDelayedDragStartListener] /// which call this method when they detect the gesture that triggers a drag /// start. void startItemDragReorder({ required int index, required PointerDownEvent event, required MultiDragGestureRecognizer recognizer, }) { assert(0 <= index && index < widget.itemCount); setState(() { if (_dragInfo != null) { cancelReorder(); } else if (_recognizer != null && _recognizerPointer != event.pointer) { _recognizer!.dispose(); _recognizer = null; _recognizerPointer = null; } if (_items.containsKey(index)) { _dragIndex = index; _recognizer = recognizer ..onStart = _dragStart ..addPointer(event); _recognizerPointer = event.pointer; } else { // TODO(darrenaustin): Can we handle this better, maybe scroll to the item? throw Exception('Attempting to start a drag on a non-visible item'); } }); } /// Cancel any item drag in progress. /// /// This should be called before any major changes to the item list /// occur so that any item drags will not get confused by /// changes to the underlying list. /// /// If a drag operation is in progress, this will immediately reset /// the list to back to its pre-drag state. /// /// If no drag is active, this will do nothing. void cancelReorder() { setState(() { _dragReset(); }); } void _registerItem(_ReorderableItemState item) { if (_dragInfo != null && _items[item.index] != item) { item.updateForGap(_dragInfo!.index, _dragInfo!.index, _dragInfo!.itemExtent, false, _reverse); } _items[item.index] = item; if (item.index == _dragInfo?.index) { item.dragging = true; item.rebuild(); } } void _unregisterItem(int index, _ReorderableItemState item) { final _ReorderableItemState? currentItem = _items[index]; if (currentItem == item) { _items.remove(index); } } Drag? _dragStart(Offset position) { assert(_dragInfo == null); final _ReorderableItemState item = _items[_dragIndex!]!; item.dragging = true; widget.onReorderStart?.call(_dragIndex!); item.rebuild(); _insertIndex = item.index; _dragInfo = _DragInfo( item: item, initialPosition: position, scrollDirection: _scrollDirection, onUpdate: _dragUpdate, onCancel: _dragCancel, onEnd: _dragEnd, onDropCompleted: _dropCompleted, proxyDecorator: widget.proxyDecorator, tickerProvider: this, ); _dragInfo!.startDrag(); final OverlayState overlay = Overlay.of(context, debugRequiredFor: widget); assert(_overlayEntry == null); _overlayEntry = OverlayEntry(builder: _dragInfo!.createProxy); overlay.insert(_overlayEntry!); for (final _ReorderableItemState childItem in _items.values) { if (childItem == item || !childItem.mounted) { continue; } childItem.updateForGap(_insertIndex!, _insertIndex!, _dragInfo!.itemExtent, false, _reverse); } return _dragInfo; } void _dragUpdate(_DragInfo item, Offset position, Offset delta) { setState(() { _overlayEntry?.markNeedsBuild(); _dragUpdateItems(); _autoScroller?.startAutoScrollIfNecessary(_dragTargetRect); }); } void _dragCancel(_DragInfo item) { setState(() { _dragReset(); }); } void _dragEnd(_DragInfo item) { setState(() { if (_insertIndex == item.index) { _finalDropPosition = _itemOffsetAt(_insertIndex!); } else if (_reverse) { if (_insertIndex! >= _items.length) { // Drop at the starting position of the last element and offset its own extent _finalDropPosition = _itemOffsetAt(_items.length - 1) - _extentOffset(item.itemExtent, _scrollDirection); } else { // Drop at the end of the current element occupying the insert position _finalDropPosition = _itemOffsetAt(_insertIndex!) + _extentOffset(_itemExtentAt(_insertIndex!), _scrollDirection); } } else { if (_insertIndex! == 0) { // Drop at the starting position of the first element and offset its own extent _finalDropPosition = _itemOffsetAt(0) - _extentOffset(item.itemExtent, _scrollDirection); } else { // Drop at the end of the previous element occupying the insert position final int atIndex = _insertIndex! - 1; _finalDropPosition = _itemOffsetAt(atIndex) + _extentOffset(_itemExtentAt(atIndex), _scrollDirection); } } }); widget.onReorderEnd?.call(_insertIndex!); } void _dropCompleted() { final int fromIndex = _dragIndex!; final int toIndex = _insertIndex!; if (fromIndex != toIndex) { widget.onReorder.call(fromIndex, toIndex); } setState(() { _dragReset(); }); } void _dragReset() { if (_dragInfo != null) { if (_dragIndex != null && _items.containsKey(_dragIndex)) { final _ReorderableItemState dragItem = _items[_dragIndex!]!; dragItem._dragging = false; dragItem.rebuild(); _dragIndex = null; } _dragInfo?.dispose(); _dragInfo = null; _autoScroller?.stopAutoScroll(); _resetItemGap(); _recognizer?.dispose(); _recognizer = null; _overlayEntry?.remove(); _overlayEntry?.dispose(); _overlayEntry = null; _finalDropPosition = null; } } void _resetItemGap() { for (final _ReorderableItemState item in _items.values) { item.resetGap(); } } void _handleScrollableAutoScrolled() { if (_dragInfo == null) { return; } _dragUpdateItems(); // Continue scrolling if the drag is still in progress. _autoScroller?.startAutoScrollIfNecessary(_dragTargetRect); } void _dragUpdateItems() { assert(_dragInfo != null); final double gapExtent = _dragInfo!.itemExtent; final double proxyItemStart = _offsetExtent(_dragInfo!.dragPosition - _dragInfo!.dragOffset, _scrollDirection); final double proxyItemEnd = proxyItemStart + gapExtent; // Find the new index for inserting the item being dragged. int newIndex = _insertIndex!; for (final _ReorderableItemState item in _items.values) { if (item.index == _dragIndex! || !item.mounted) { continue; } final Rect geometry = item.targetGeometry(); final double itemStart = _scrollDirection == Axis.vertical ? geometry.top : geometry.left; final double itemExtent = _scrollDirection == Axis.vertical ? geometry.height : geometry.width; final double itemEnd = itemStart + itemExtent; final double itemMiddle = itemStart + itemExtent / 2; if (_reverse) { if (itemEnd >= proxyItemEnd && proxyItemEnd >= itemMiddle) { // The start of the proxy is in the beginning half of the item, so // we should swap the item with the gap and we are done looking for // the new index. newIndex = item.index; break; } else if (itemMiddle >= proxyItemStart && proxyItemStart >= itemStart) { // The end of the proxy is in the ending half of the item, so // we should swap the item with the gap and we are done looking for // the new index. newIndex = item.index + 1; break; } else if (itemStart > proxyItemEnd && newIndex < (item.index + 1)) { newIndex = item.index + 1; } else if (proxyItemStart > itemEnd && newIndex > item.index) { newIndex = item.index; } } else { if (itemStart <= proxyItemStart && proxyItemStart <= itemMiddle) { // The start of the proxy is in the beginning half of the item, so // we should swap the item with the gap and we are done looking for // the new index. newIndex = item.index; break; } else if (itemMiddle <= proxyItemEnd && proxyItemEnd <= itemEnd) { // The end of the proxy is in the ending half of the item, so // we should swap the item with the gap and we are done looking for // the new index. newIndex = item.index + 1; break; } else if (itemEnd < proxyItemStart && newIndex < (item.index + 1)) { newIndex = item.index + 1; } else if (proxyItemEnd < itemStart && newIndex > item.index) { newIndex = item.index; } } } if (newIndex != _insertIndex) { _insertIndex = newIndex; for (final _ReorderableItemState item in _items.values) { if (item.index == _dragIndex! || !item.mounted) { continue; } item.updateForGap(_dragIndex!, newIndex, gapExtent, true, _reverse); } } } Rect get _dragTargetRect { final Offset origin = _dragInfo!.dragPosition - _dragInfo!.dragOffset; return Rect.fromLTWH(origin.dx, origin.dy, _dragInfo!.itemSize.width, _dragInfo!.itemSize.height); } Offset _itemOffsetAt(int index) { return _items[index]!.targetGeometry().topLeft; } double _itemExtentAt(int index) { return _sizeExtent(_items[index]!.targetGeometry().size, _scrollDirection); } Widget _itemBuilder(BuildContext context, int index) { if (_dragInfo != null && index >= widget.itemCount) { return switch (_scrollDirection) { Axis.horizontal => SizedBox(width: _dragInfo!.itemExtent), Axis.vertical => SizedBox(height: _dragInfo!.itemExtent), }; } final Widget child = widget.itemBuilder(context, index); assert(child.key != null, 'All list items must have a key'); final OverlayState overlay = Overlay.of(context, debugRequiredFor: widget); return _ReorderableItem( key: _ReorderableItemGlobalKey(child.key!, index, this), index: index, capturedThemes: InheritedTheme.capture(from: context, to: overlay.context), child: _wrapWithSemantics(child, index), ); } Widget _wrapWithSemantics(Widget child, int index) { void reorder(int startIndex, int endIndex) { if (startIndex != endIndex) { widget.onReorder(startIndex, endIndex); } } // First, determine which semantics actions apply. final Map<CustomSemanticsAction, VoidCallback> semanticsActions = <CustomSemanticsAction, VoidCallback>{}; // Create the appropriate semantics actions. void moveToStart() => reorder(index, 0); void moveToEnd() => reorder(index, widget.itemCount); void moveBefore() => reorder(index, index - 1); // To move after, go to index+2 because it is moved to the space // before index+2, which is after the space at index+1. void moveAfter() => reorder(index, index + 2); final WidgetsLocalizations localizations = WidgetsLocalizations.of(context); final bool isHorizontal = _scrollDirection == Axis.horizontal; // If the item can move to before its current position in the list. if (index > 0) { semanticsActions[CustomSemanticsAction(label: localizations.reorderItemToStart)] = moveToStart; String reorderItemBefore = localizations.reorderItemUp; if (isHorizontal) { reorderItemBefore = Directionality.of(context) == TextDirection.ltr ? localizations.reorderItemLeft : localizations.reorderItemRight; } semanticsActions[CustomSemanticsAction(label: reorderItemBefore)] = moveBefore; } // If the item can move to after its current position in the list. if (index < widget.itemCount - 1) { String reorderItemAfter = localizations.reorderItemDown; if (isHorizontal) { reorderItemAfter = Directionality.of(context) == TextDirection.ltr ? localizations.reorderItemRight : localizations.reorderItemLeft; } semanticsActions[CustomSemanticsAction(label: reorderItemAfter)] = moveAfter; semanticsActions[CustomSemanticsAction(label: localizations.reorderItemToEnd)] = moveToEnd; } // Pass toWrap with a GlobalKey into the item so that when it // gets dragged, the accessibility framework can preserve the selected // state of the dragging item. // // Also apply the relevant custom accessibility actions for moving the item // up, down, to the start, and to the end of the list. return Semantics( container: true, customSemanticsActions: semanticsActions, child: child, ); } @override Widget build(BuildContext context) { assert(debugCheckHasOverlay(context)); final SliverChildBuilderDelegate childrenDelegate = SliverChildBuilderDelegate( _itemBuilder, childCount: widget.itemCount, findChildIndexCallback: widget.findChildIndexCallback, ); if (widget.itemExtent != null) { return SliverFixedExtentList( delegate: childrenDelegate, itemExtent: widget.itemExtent!, ); } else if (widget.itemExtentBuilder != null) { return SliverVariedExtentList( delegate: childrenDelegate, itemExtentBuilder: widget.itemExtentBuilder!, ); } else if (widget.prototypeItem != null) { return SliverPrototypeExtentList( delegate: childrenDelegate, prototypeItem: widget.prototypeItem!, ); } return SliverList(delegate: childrenDelegate); } } class _ReorderableItem extends StatefulWidget { const _ReorderableItem({ required Key key, required this.index, required this.child, required this.capturedThemes, }) : super(key: key); final int index; final Widget child; final CapturedThemes capturedThemes; @override _ReorderableItemState createState() => _ReorderableItemState(); } class _ReorderableItemState extends State<_ReorderableItem> { late SliverReorderableListState _listState; Offset _startOffset = Offset.zero; Offset _targetOffset = Offset.zero; AnimationController? _offsetAnimation; Key get key => widget.key!; int get index => widget.index; bool get dragging => _dragging; set dragging(bool dragging) { if (mounted) { setState(() { _dragging = dragging; }); } } bool _dragging = false; @override void initState() { _listState = SliverReorderableList.of(context); _listState._registerItem(this); super.initState(); } @override void dispose() { _offsetAnimation?.dispose(); _listState._unregisterItem(index, this); super.dispose(); } @override void didUpdateWidget(covariant _ReorderableItem oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.index != widget.index) { _listState._unregisterItem(oldWidget.index, this); _listState._registerItem(this); } } @override Widget build(BuildContext context) { if (_dragging) { final Size size = _extentSize(_listState._dragInfo!.itemExtent, _listState._scrollDirection); return SizedBox.fromSize(size: size); } _listState._registerItem(this); return Transform( transform: Matrix4.translationValues(offset.dx, offset.dy, 0.0), child: widget.child, ); } @override void deactivate() { _listState._unregisterItem(index, this); super.deactivate(); } Offset get offset { if (_offsetAnimation != null) { final double animValue = Curves.easeInOut.transform(_offsetAnimation!.value); return Offset.lerp(_startOffset, _targetOffset, animValue)!; } return _targetOffset; } void updateForGap(int dragIndex, int gapIndex, double gapExtent, bool animate, bool reverse) { // An offset needs to be added to create a gap when we are between the // moving element (dragIndex) and the current gap position (gapIndex). // For how to update the gap position, refer to [_dragUpdateItems]. final Offset newTargetOffset; if (gapIndex < dragIndex && index < dragIndex && index >= gapIndex) { newTargetOffset = _extentOffset(reverse ? -gapExtent : gapExtent, _listState._scrollDirection); } else if (gapIndex > dragIndex && index > dragIndex && index < gapIndex) { newTargetOffset = _extentOffset(reverse ? gapExtent : -gapExtent, _listState._scrollDirection); } else { newTargetOffset = Offset.zero; } if (newTargetOffset != _targetOffset) { _targetOffset = newTargetOffset; if (animate) { if (_offsetAnimation == null) { _offsetAnimation = AnimationController( vsync: _listState, duration: const Duration(milliseconds: 250), ) ..addListener(rebuild) ..addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) { _startOffset = _targetOffset; _offsetAnimation!.dispose(); _offsetAnimation = null; } }) ..forward(); } else { _startOffset = offset; _offsetAnimation!.forward(from: 0.0); } } else { if (_offsetAnimation != null) { _offsetAnimation!.dispose(); _offsetAnimation = null; } _startOffset = _targetOffset; } rebuild(); } } void resetGap() { if (_offsetAnimation != null) { _offsetAnimation!.dispose(); _offsetAnimation = null; } _startOffset = Offset.zero; _targetOffset = Offset.zero; rebuild(); } Rect targetGeometry() { final RenderBox itemRenderBox = context.findRenderObject()! as RenderBox; final Offset itemPosition = itemRenderBox.localToGlobal(Offset.zero) + _targetOffset; return itemPosition & itemRenderBox.size; } void rebuild() { if (mounted) { setState(() {}); } } } /// A wrapper widget that will recognize the start of a drag on the wrapped /// widget by a [PointerDownEvent], and immediately initiate dragging the /// wrapped item to a new location in a reorderable list. /// /// See also: /// /// * [ReorderableDelayedDragStartListener], a similar wrapper that will /// only recognize the start after a long press event. /// * [ReorderableList], a widget list that allows the user to reorder /// its items. /// * [SliverReorderableList], a sliver list that allows the user to reorder /// its items. /// * [ReorderableListView], a Material Design list that allows the user to /// reorder its items. class ReorderableDragStartListener extends StatelessWidget { /// Creates a listener for a drag immediately following a pointer down /// event over the given child widget. /// /// This is most commonly used to wrap part of a list item like a drag /// handle. const ReorderableDragStartListener({ super.key, required this.child, required this.index, this.enabled = true, }); /// The widget for which the application would like to respond to a tap and /// drag gesture by starting a reordering drag on a reorderable list. final Widget child; /// The index of the associated item that will be dragged in the list. final int index; /// Whether the [child] item can be dragged and moved in the list. /// /// If true, the item can be moved to another location in the list when the /// user taps on the child. If false, tapping on the child will be ignored. final bool enabled; @override Widget build(BuildContext context) { return Listener( onPointerDown: enabled ? (PointerDownEvent event) => _startDragging(context, event) : null, child: child, ); } /// Provides the gesture recognizer used to indicate the start of a reordering /// drag operation. /// /// By default this returns an [ImmediateMultiDragGestureRecognizer] but /// subclasses can use this to customize the drag start gesture. @protected MultiDragGestureRecognizer createRecognizer() { return ImmediateMultiDragGestureRecognizer(debugOwner: this); } void _startDragging(BuildContext context, PointerDownEvent event) { final DeviceGestureSettings? gestureSettings = MediaQuery.maybeGestureSettingsOf(context); final SliverReorderableListState? list = SliverReorderableList.maybeOf(context); list?.startItemDragReorder( index: index, event: event, recognizer: createRecognizer() ..gestureSettings = gestureSettings, ); } } /// A wrapper widget that will recognize the start of a drag operation by /// looking for a long press event. Once it is recognized, it will start /// a drag operation on the wrapped item in the reorderable list. /// /// See also: /// /// * [ReorderableDragStartListener], a similar wrapper that will /// recognize the start of the drag immediately after a pointer down event. /// * [ReorderableList], a widget list that allows the user to reorder /// its items. /// * [SliverReorderableList], a sliver list that allows the user to reorder /// its items. /// * [ReorderableListView], a Material Design list that allows the user to /// reorder its items. class ReorderableDelayedDragStartListener extends ReorderableDragStartListener { /// Creates a listener for an drag following a long press event over the /// given child widget. /// /// This is most commonly used to wrap an entire list item in a reorderable /// list. const ReorderableDelayedDragStartListener({ super.key, required super.child, required super.index, super.enabled, }); @override MultiDragGestureRecognizer createRecognizer() { return DelayedMultiDragGestureRecognizer(debugOwner: this); } } typedef _DragItemUpdate = void Function(_DragInfo item, Offset position, Offset delta); typedef _DragItemCallback = void Function(_DragInfo item); class _DragInfo extends Drag { _DragInfo({ required _ReorderableItemState item, Offset initialPosition = Offset.zero, this.scrollDirection = Axis.vertical, this.onUpdate, this.onEnd, this.onCancel, this.onDropCompleted, this.proxyDecorator, required this.tickerProvider, }) { // TODO(polina-c): stop duplicating code across disposables // https://github.com/flutter/flutter/issues/137435 if (kFlutterMemoryAllocationsEnabled) { FlutterMemoryAllocations.instance.dispatchObjectCreated( library: 'package:flutter/widgets.dart', className: '$_DragInfo', object: this, ); } final RenderBox itemRenderBox = item.context.findRenderObject()! as RenderBox; listState = item._listState; index = item.index; child = item.widget.child; capturedThemes = item.widget.capturedThemes; dragPosition = initialPosition; dragOffset = itemRenderBox.globalToLocal(initialPosition); itemSize = item.context.size!; itemExtent = _sizeExtent(itemSize, scrollDirection); scrollable = Scrollable.of(item.context); } final Axis scrollDirection; final _DragItemUpdate? onUpdate; final _DragItemCallback? onEnd; final _DragItemCallback? onCancel; final VoidCallback? onDropCompleted; final ReorderItemProxyDecorator? proxyDecorator; final TickerProvider tickerProvider; late SliverReorderableListState listState; late int index; late Widget child; late Offset dragPosition; late Offset dragOffset; late Size itemSize; late double itemExtent; late CapturedThemes capturedThemes; ScrollableState? scrollable; AnimationController? _proxyAnimation; void dispose() { if (kFlutterMemoryAllocationsEnabled) { FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); } _proxyAnimation?.dispose(); } void startDrag() { _proxyAnimation = AnimationController( vsync: tickerProvider, duration: const Duration(milliseconds: 250), ) ..addStatusListener((AnimationStatus status) { if (status == AnimationStatus.dismissed) { _dropCompleted(); } }) ..forward(); } @override void update(DragUpdateDetails details) { final Offset delta = _restrictAxis(details.delta, scrollDirection); dragPosition += delta; onUpdate?.call(this, dragPosition, details.delta); } @override void end(DragEndDetails details) { _proxyAnimation!.reverse(); onEnd?.call(this); } @override void cancel() { _proxyAnimation?.dispose(); _proxyAnimation = null; onCancel?.call(this); } void _dropCompleted() { _proxyAnimation?.dispose(); _proxyAnimation = null; onDropCompleted?.call(); } Widget createProxy(BuildContext context) { return capturedThemes.wrap( _DragItemProxy( listState: listState, index: index, size: itemSize, animation: _proxyAnimation!, position: dragPosition - dragOffset - _overlayOrigin(context), proxyDecorator: proxyDecorator, child: child, ), ); } } Offset _overlayOrigin(BuildContext context) { final OverlayState overlay = Overlay.of(context, debugRequiredFor: context.widget); final RenderBox overlayBox = overlay.context.findRenderObject()! as RenderBox; return overlayBox.localToGlobal(Offset.zero); } class _DragItemProxy extends StatelessWidget { const _DragItemProxy({ required this.listState, required this.index, required this.child, required this.position, required this.size, required this.animation, required this.proxyDecorator, }); final SliverReorderableListState listState; final int index; final Widget child; final Offset position; final Size size; final AnimationController animation; final ReorderItemProxyDecorator? proxyDecorator; @override Widget build(BuildContext context) { final Widget proxyChild = proxyDecorator?.call(child, index, animation.view) ?? child; final Offset overlayOrigin = _overlayOrigin(context); return MediaQuery( // Remove the top padding so that any nested list views in the item // won't pick up the scaffold's padding in the overlay. data: MediaQuery.of(context).removePadding(removeTop: true), child: AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { Offset effectivePosition = position; final Offset? dropPosition = listState._finalDropPosition; if (dropPosition != null) { effectivePosition = Offset.lerp(dropPosition - overlayOrigin, effectivePosition, Curves.easeOut.transform(animation.value))!; } return Positioned( left: effectivePosition.dx, top: effectivePosition.dy, child: SizedBox( width: size.width, height: size.height, child: child, ), ); }, child: proxyChild, ), ); } } double _sizeExtent(Size size, Axis scrollDirection) { return switch (scrollDirection) { Axis.horizontal => size.width, Axis.vertical => size.height, }; } Size _extentSize(double extent, Axis scrollDirection) { switch (scrollDirection) { case Axis.horizontal: return Size(extent, 0); case Axis.vertical: return Size(0, extent); } } double _offsetExtent(Offset offset, Axis scrollDirection) { return switch (scrollDirection) { Axis.horizontal => offset.dx, Axis.vertical => offset.dy, }; } Offset _extentOffset(double extent, Axis scrollDirection) { return switch (scrollDirection) { Axis.horizontal => Offset(extent, 0.0), Axis.vertical => Offset(0.0, extent), }; } Offset _restrictAxis(Offset offset, Axis scrollDirection) { return switch (scrollDirection) { Axis.horizontal => Offset(offset.dx, 0.0), Axis.vertical => Offset(0.0, offset.dy), }; } // 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 _ReorderableItemGlobalKey extends GlobalObjectKey { const _ReorderableItemGlobalKey(this.subKey, this.index, this.state) : super(subKey); final Key subKey; final int index; final SliverReorderableListState state; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is _ReorderableItemGlobalKey && other.subKey == subKey && other.index == index && other.state == state; } @override int get hashCode => Object.hash(subKey, index, state); }
flutter/packages/flutter/lib/src/widgets/reorderable_list.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/reorderable_list.dart", "repo_id": "flutter", "token_count": 18449 }
696
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/physics.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'basic.dart'; import 'framework.dart'; import 'notification_listener.dart'; import 'page_storage.dart'; import 'scroll_activity.dart'; import 'scroll_context.dart'; import 'scroll_metrics.dart'; import 'scroll_notification.dart'; import 'scroll_physics.dart'; export 'scroll_activity.dart' show ScrollHoldController; /// The policy to use when applying the `alignment` parameter of /// [ScrollPosition.ensureVisible]. enum ScrollPositionAlignmentPolicy { /// Use the `alignment` property of [ScrollPosition.ensureVisible] to decide /// where to align the visible object. explicit, /// Find the bottom edge of the scroll container, and scroll the container, if /// necessary, to show the bottom of the object. /// /// For example, find the bottom edge of the scroll container. If the bottom /// edge of the item is below the bottom edge of the scroll container, scroll /// the item so that the bottom of the item is just visible. If the entire /// item is already visible, then do nothing. keepVisibleAtEnd, /// Find the top edge of the scroll container, and scroll the container if /// necessary to show the top of the object. /// /// For example, find the top edge of the scroll container. If the top edge of /// the item is above the top edge of the scroll container, scroll the item so /// that the top of the item is just visible. If the entire item is already /// visible, then do nothing. keepVisibleAtStart, } /// Determines which portion of the content is visible in a scroll view. /// /// The [pixels] value determines the scroll offset that the scroll view uses to /// select which part of its content to display. As the user scrolls the /// viewport, this value changes, which changes the content that is displayed. /// /// The [ScrollPosition] applies [physics] to scrolling, and stores the /// [minScrollExtent] and [maxScrollExtent]. /// /// Scrolling is controlled by the current [activity], which is set by /// [beginActivity]. [ScrollPosition] itself does not start any activities. /// Instead, concrete subclasses, such as [ScrollPositionWithSingleContext], /// typically start activities in response to user input or instructions from a /// [ScrollController]. /// /// This object is a [Listenable] that notifies its listeners when [pixels] /// changes. /// /// {@template flutter.widgets.scrollPosition.listening} /// ### Accessing Scrolling Information /// /// There are several ways to acquire information about scrolling and /// scrollable widgets, but each provides different types of information about /// the scrolling activity, the position, and the dimensions of the [Viewport]. /// /// A [ScrollController] is a [Listenable]. It notifies its listeners whenever /// any of the attached [ScrollPosition]s notify _their_ listeners, such as when /// scrolling occurs. This is very similar to using a [NotificationListener] of /// type [ScrollNotification] to listen to changes in the scroll position, with /// the difference being that a notification listener will provide information /// about the scrolling activity. A notification listener can further listen to /// specific subclasses of [ScrollNotification], like [UserScrollNotification]. /// /// {@tool dartpad} /// This sample shows the difference between using a [ScrollController] or a /// [NotificationListener] of type [ScrollNotification] to listen to scrolling /// activities. Toggling the [Radio] button switches between the two. /// Using a [ScrollNotification] will provide details about the scrolling /// activity, along with the metrics of the [ScrollPosition], but not the scroll /// position object itself. By listening with a [ScrollController], the position /// object is directly accessible. /// Both of these types of notifications are only triggered by scrolling. /// /// ** See code in examples/api/lib/widgets/scroll_position/scroll_controller_notification.0.dart ** /// {@end-tool} /// /// [ScrollController] does not notify its listeners when the list of /// [ScrollPosition]s attached to the scroll controller changes. To listen to /// the attaching and detaching of scroll positions to the controller, use the /// [ScrollController.onAttach] and [ScrollController.onDetach] methods. This is /// also useful for adding a listener to the /// [ScrollPosition.isScrollingNotifier] when the position is created during the /// build method of the [Scrollable]. /// /// At the time that a scroll position is attached, the [ScrollMetrics], such as /// the [ScrollMetrics.maxScrollExtent], are not yet available. These are not /// determined until the [Scrollable] has finished laying out its contents and /// computing things like the full extent of that content. /// [ScrollPosition.hasContentDimensions] can be used to know when the /// metrics are available, or a [ScrollMetricsNotification] can be used, /// discussed further below. /// /// {@tool dartpad} /// This sample shows how to apply a listener to the /// [ScrollPosition.isScrollingNotifier] using [ScrollController.onAttach]. /// This is used to change the [AppBar]'s color when scrolling is occurring. /// /// ** See code in examples/api/lib/widgets/scroll_position/scroll_controller_on_attach.0.dart ** /// {@end-tool} /// /// #### From a different context /// /// When needing to access scrolling information from a context that is within /// the scrolling widget itself, use [Scrollable.of] to access the /// [ScrollableState] and the [ScrollableState.position]. This would be the same /// [ScrollPosition] attached to a [ScrollController]. /// /// When needing to access scrolling information from a context that is not an /// ancestor of the scrolling widget, use [ScrollNotificationObserver]. This is /// used by [AppBar] to create the scrolled under effect. Since [Scaffold.appBar] /// is a separate subtree from the [Scaffold.body], scroll notifications would /// not bubble up to the app bar. Use /// [ScrollNotificationObserverState.addListener] to listen to scroll /// notifications happening outside of the current context. /// /// #### Dimension changes /// /// Lastly, listening to a [ScrollController] or a [ScrollPosition] will /// _not_ notify when the [ScrollMetrics] of a given scroll position changes, /// such as when the window is resized, changing the dimensions of the /// [Viewport] and the previously mentioned extents of the scrollable. In order /// to listen to changes in scroll metrics, use a [NotificationListener] of type /// [ScrollMetricsNotification]. This type of notification differs from /// [ScrollNotification], as it is not associated with the activity of /// scrolling, but rather the dimensions of the scrollable area, such as the /// window size. /// /// {@tool dartpad} /// This sample shows how a [ScrollMetricsNotification] is dispatched when /// the `windowSize` is changed. Press the floating action button to increase /// the scrollable window's size. /// /// ** See code in examples/api/lib/widgets/scroll_position/scroll_metrics_notification.0.dart ** /// {@end-tool} /// {@endtemplate} /// /// ## Subclassing ScrollPosition /// /// Over time, a [Scrollable] might have many different [ScrollPosition] /// objects. For example, if [Scrollable.physics] changes type, [Scrollable] /// creates a new [ScrollPosition] with the new physics. To transfer state from /// the old instance to the new instance, subclasses implement [absorb]. See /// [absorb] for more details. /// /// Subclasses also need to call [didUpdateScrollDirection] whenever /// [userScrollDirection] changes values. /// /// See also: /// /// * [Scrollable], which uses a [ScrollPosition] to determine which portion of /// its content to display. /// * [ScrollController], which can be used with [ListView], [GridView] and /// other scrollable widgets to control a [ScrollPosition]. /// * [ScrollPositionWithSingleContext], which is the most commonly used /// concrete subclass of [ScrollPosition]. /// * [ScrollNotification] and [NotificationListener], which can be used to watch /// the scroll position without using a [ScrollController]. abstract class ScrollPosition extends ViewportOffset with ScrollMetrics { /// Creates an object that determines which portion of the content is visible /// in a scroll view. ScrollPosition({ required this.physics, required this.context, this.keepScrollOffset = true, ScrollPosition? oldPosition, this.debugLabel, }) { if (oldPosition != null) { absorb(oldPosition); } if (keepScrollOffset) { restoreScrollOffset(); } } /// How the scroll position should respond to user input. /// /// For example, determines how the widget continues to animate after the /// user stops dragging the scroll view. final ScrollPhysics physics; /// Where the scrolling is taking place. /// /// Typically implemented by [ScrollableState]. final ScrollContext context; /// Save the current scroll offset with [PageStorage] and restore it if /// this scroll position's scrollable is recreated. /// /// See also: /// /// * [ScrollController.keepScrollOffset] and [PageController.keepPage], which /// create scroll positions and initialize this property. // TODO(goderbauer): Deprecate this when state restoration supports all features of PageStorage. final bool keepScrollOffset; /// A label that is used in the [toString] output. /// /// Intended to aid with identifying animation controller instances in debug /// output. final String? debugLabel; @override double get minScrollExtent => _minScrollExtent!; double? _minScrollExtent; @override double get maxScrollExtent => _maxScrollExtent!; double? _maxScrollExtent; @override bool get hasContentDimensions => _minScrollExtent != null && _maxScrollExtent != null; /// The additional velocity added for a [forcePixels] change in a single /// frame. /// /// This value is used by [recommendDeferredLoading] in addition to the /// [activity]'s [ScrollActivity.velocity] to ask the [physics] whether or /// not to defer loading. It accounts for the fact that a [forcePixels] call /// may involve a [ScrollActivity] with 0 velocity, but the scrollable is /// still instantaneously moving from its current position to a potentially /// very far position, and which is of interest to callers of /// [recommendDeferredLoading]. /// /// For example, if a scrollable is currently at 5000 pixels, and we [jumpTo] /// 0 to get back to the top of the list, we would have an implied velocity of /// -5000 and an `activity.velocity` of 0. The jump may be going past a /// number of resource intensive widgets which should avoid doing work if the /// position jumps past them. double _impliedVelocity = 0; @override double get pixels => _pixels!; double? _pixels; @override bool get hasPixels => _pixels != null; @override double get viewportDimension => _viewportDimension!; double? _viewportDimension; @override bool get hasViewportDimension => _viewportDimension != null; /// Whether [viewportDimension], [minScrollExtent], [maxScrollExtent], /// [outOfRange], and [atEdge] are available. /// /// Set to true just before the first time [applyNewDimensions] is called. bool get haveDimensions => _haveDimensions; bool _haveDimensions = false; /// Take any current applicable state from the given [ScrollPosition]. /// /// This method is called by the constructor if it is given an `oldPosition`. /// The `other` argument might not have the same [runtimeType] as this object. /// /// This method can be destructive to the other [ScrollPosition]. The other /// object must be disposed immediately after this call (in the same call /// stack, before microtask resolution, by whomever called this object's /// constructor). /// /// If the old [ScrollPosition] object is a different [runtimeType] than this /// one, the [ScrollActivity.resetActivity] method is invoked on the newly /// adopted [ScrollActivity]. /// /// ## Overriding /// /// Overrides of this method must call `super.absorb` after setting any /// metrics-related or activity-related state, since this method may restart /// the activity and scroll activities tend to use those metrics when being /// restarted. /// /// Overrides of this method might need to start an [IdleScrollActivity] if /// they are unable to absorb the activity from the other [ScrollPosition]. /// /// Overrides of this method might also need to update the delegates of /// absorbed scroll activities if they use themselves as a /// [ScrollActivityDelegate]. @protected @mustCallSuper void absorb(ScrollPosition other) { assert(other.context == context); assert(_pixels == null); if (other.hasContentDimensions) { _minScrollExtent = other.minScrollExtent; _maxScrollExtent = other.maxScrollExtent; } if (other.hasPixels) { _pixels = other.pixels; } if (other.hasViewportDimension) { _viewportDimension = other.viewportDimension; } assert(activity == null); assert(other.activity != null); _activity = other.activity; other._activity = null; if (other.runtimeType != runtimeType) { activity!.resetActivity(); } context.setIgnorePointer(activity!.shouldIgnorePointer); isScrollingNotifier.value = activity!.isScrolling; } @override double get devicePixelRatio => context.devicePixelRatio; /// Update the scroll position ([pixels]) to a given pixel value. /// /// This should only be called by the current [ScrollActivity], either during /// the transient callback phase or in response to user input. /// /// Returns the overscroll, if any. If the return value is 0.0, that means /// that [pixels] now returns the given `value`. If the return value is /// positive, then [pixels] is less than the requested `value` by the given /// amount (overscroll past the max extent), and if it is negative, it is /// greater than the requested `value` by the given amount (underscroll past /// the min extent). /// /// The amount of overscroll is computed by [applyBoundaryConditions]. /// /// The amount of the change that is applied is reported using [didUpdateScrollPositionBy]. /// If there is any overscroll, it is reported using [didOverscrollBy]. double setPixels(double newPixels) { assert(hasPixels); assert(SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks, "A scrollable's position should not change during the build, layout, and paint phases, otherwise the rendering will be confused."); if (newPixels != pixels) { final double overscroll = applyBoundaryConditions(newPixels); assert(() { final double delta = newPixels - pixels; if (overscroll.abs() > delta.abs()) { throw FlutterError( '$runtimeType.applyBoundaryConditions returned invalid overscroll value.\n' 'setPixels() was called to change the scroll offset from $pixels to $newPixels.\n' 'That is a delta of $delta units.\n' '$runtimeType.applyBoundaryConditions reported an overscroll of $overscroll units.', ); } return true; }()); final double oldPixels = pixels; _pixels = newPixels - overscroll; if (_pixels != oldPixels) { notifyListeners(); didUpdateScrollPositionBy(pixels - oldPixels); } if (overscroll.abs() > precisionErrorTolerance) { didOverscrollBy(overscroll); return overscroll; } } return 0.0; } /// Change the value of [pixels] to the new value, without notifying any /// customers. /// /// This is used to adjust the position while doing layout. In particular, /// this is typically called as a response to [applyViewportDimension] or /// [applyContentDimensions] (in both cases, if this method is called, those /// methods should then return false to indicate that the position has been /// adjusted). /// /// Calling this is rarely correct in other contexts. It will not immediately /// cause the rendering to change, since it does not notify the widgets or /// render objects that might be listening to this object: they will only /// change when they next read the value, which could be arbitrarily later. It /// is generally only appropriate in the very specific case of the value being /// corrected during layout (since then the value is immediately read), in the /// specific case of a [ScrollPosition] with a single viewport customer. /// /// To cause the position to jump or animate to a new value, consider [jumpTo] /// or [animateTo], which will honor the normal conventions for changing the /// scroll offset. /// /// To force the [pixels] to a particular value without honoring the normal /// conventions for changing the scroll offset, consider [forcePixels]. (But /// see the discussion there for why that might still be a bad idea.) /// /// See also: /// /// * [correctBy], which is a method of [ViewportOffset] used /// by viewport render objects to correct the offset during layout /// without notifying its listeners. /// * [jumpTo], for making changes to position while not in the /// middle of layout and applying the new position immediately. /// * [animateTo], which is like [jumpTo] but animating to the /// destination offset. // ignore: use_setters_to_change_properties, (API is intended to discourage setting value) void correctPixels(double value) { _pixels = value; } /// Apply a layout-time correction to the scroll offset. /// /// This method should change the [pixels] value by `correction`, but without /// calling [notifyListeners]. It is called during layout by the /// [RenderViewport], before [applyContentDimensions]. After this method is /// called, the layout will be recomputed and that may result in this method /// being called again, though this should be very rare. /// /// See also: /// /// * [jumpTo], for also changing the scroll position when not in layout. /// [jumpTo] applies the change immediately and notifies its listeners. /// * [correctPixels], which is used by the [ScrollPosition] itself to /// set the offset initially during construction or after /// [applyViewportDimension] or [applyContentDimensions] is called. @override void correctBy(double correction) { assert( hasPixels, 'An initial pixels value must exist by calling correctPixels on the ScrollPosition', ); _pixels = _pixels! + correction; _didChangeViewportDimensionOrReceiveCorrection = true; } /// Change the value of [pixels] to the new value, and notify any customers, /// but without honoring normal conventions for changing the scroll offset. /// /// This is used to implement [jumpTo]. It can also be used adjust the /// position when the dimensions of the viewport change. It should only be /// used when manually implementing the logic for honoring the relevant /// conventions of the class. For example, [ScrollPositionWithSingleContext] /// introduces [ScrollActivity] objects and uses [forcePixels] in conjunction /// with adjusting the activity, e.g. by calling /// [ScrollPositionWithSingleContext.goIdle], so that the activity does /// not immediately set the value back. (Consider, for instance, a case where /// one is using a [DrivenScrollActivity]. That object will ignore any calls /// to [forcePixels], which would result in the rendering stuttering: changing /// in response to [forcePixels], and then changing back to the next value /// derived from the animation.) /// /// To cause the position to jump or animate to a new value, consider [jumpTo] /// or [animateTo]. /// /// This should not be called during layout (e.g. when setting the initial /// scroll offset). Consider [correctPixels] if you find you need to adjust /// the position during layout. @protected void forcePixels(double value) { assert(hasPixels); _impliedVelocity = value - pixels; _pixels = value; notifyListeners(); SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { _impliedVelocity = 0; }, debugLabel: 'ScrollPosition.resetVelocity'); } /// Called whenever scrolling ends, to store the current scroll offset in a /// storage mechanism with a lifetime that matches the app's lifetime. /// /// The stored value will be used by [restoreScrollOffset] when the /// [ScrollPosition] is recreated, in the case of the [Scrollable] being /// disposed then recreated in the same session. This might happen, for /// instance, if a [ListView] is on one of the pages inside a [TabBarView], /// and that page is displayed, then hidden, then displayed again. /// /// The default implementation writes the [pixels] using the nearest /// [PageStorage] found from the [context]'s [ScrollContext.storageContext] /// property. // TODO(goderbauer): Deprecate this when state restoration supports all features of PageStorage. @protected void saveScrollOffset() { PageStorage.maybeOf(context.storageContext)?.writeState(context.storageContext, pixels); } /// Called whenever the [ScrollPosition] is created, to restore the scroll /// offset if possible. /// /// The value is stored by [saveScrollOffset] when the scroll position /// changes, so that it can be restored in the case of the [Scrollable] being /// disposed then recreated in the same session. This might happen, for /// instance, if a [ListView] is on one of the pages inside a [TabBarView], /// and that page is displayed, then hidden, then displayed again. /// /// The default implementation reads the value from the nearest [PageStorage] /// found from the [context]'s [ScrollContext.storageContext] property, and /// sets it using [correctPixels], if [pixels] is still null. /// /// This method is called from the constructor, so layout has not yet /// occurred, and the viewport dimensions aren't yet known when it is called. // TODO(goderbauer): Deprecate this when state restoration supports all features of PageStorage. @protected void restoreScrollOffset() { if (!hasPixels) { final double? value = PageStorage.maybeOf(context.storageContext)?.readState(context.storageContext) as double?; if (value != null) { correctPixels(value); } } } /// Called by [context] to restore the scroll offset to the provided value. /// /// The provided value has previously been provided to the [context] by /// calling [ScrollContext.saveOffset], e.g. from [saveOffset]. /// /// This method may be called right after the scroll position is created /// before layout has occurred. In that case, `initialRestore` is set to true /// and the viewport dimensions will not be known yet. If the [context] /// doesn't have any information to restore the scroll offset this method is /// not called. /// /// The method may be called multiple times in the lifecycle of a /// [ScrollPosition] to restore it to different scroll offsets. void restoreOffset(double offset, {bool initialRestore = false}) { if (initialRestore) { correctPixels(offset); } else { jumpTo(offset); } } /// Called whenever scrolling ends, to persist the current scroll offset for /// state restoration purposes. /// /// The default implementation stores the current value of [pixels] on the /// [context] by calling [ScrollContext.saveOffset]. At a later point in time /// or after the application restarts, the [context] may restore the scroll /// position to the persisted offset by calling [restoreOffset]. @protected void saveOffset() { assert(hasPixels); context.saveOffset(pixels); } /// Returns the overscroll by applying the boundary conditions. /// /// If the given value is in bounds, returns 0.0. Otherwise, returns the /// amount of value that cannot be applied to [pixels] as a result of the /// boundary conditions. If the [physics] allow out-of-bounds scrolling, this /// method always returns 0.0. /// /// The default implementation defers to the [physics] object's /// [ScrollPhysics.applyBoundaryConditions]. @protected double applyBoundaryConditions(double value) { final double result = physics.applyBoundaryConditions(this, value); assert(() { final double delta = value - pixels; if (result.abs() > delta.abs()) { throw FlutterError( '${physics.runtimeType}.applyBoundaryConditions returned invalid overscroll value.\n' 'The method was called to consider a change from $pixels to $value, which is a ' 'delta of ${delta.toStringAsFixed(1)} units. However, it returned an overscroll of ' '${result.toStringAsFixed(1)} units, which has a greater magnitude than the delta. ' 'The applyBoundaryConditions method is only supposed to reduce the possible range ' 'of movement, not increase it.\n' 'The scroll extents are $minScrollExtent .. $maxScrollExtent, and the ' 'viewport dimension is $viewportDimension.', ); } return true; }()); return result; } bool _didChangeViewportDimensionOrReceiveCorrection = true; @override bool applyViewportDimension(double viewportDimension) { if (_viewportDimension != viewportDimension) { _viewportDimension = viewportDimension; _didChangeViewportDimensionOrReceiveCorrection = true; // If this is called, you can rely on applyContentDimensions being called // soon afterwards in the same layout phase. So we put all the logic that // relies on both values being computed into applyContentDimensions. } return true; } bool _pendingDimensions = false; ScrollMetrics? _lastMetrics; // True indicates that there is a ScrollMetrics update notification pending. bool _haveScheduledUpdateNotification = false; Axis? _lastAxis; bool _isMetricsChanged() { assert(haveDimensions); final ScrollMetrics currentMetrics = copyWith(); return _lastMetrics == null || !(currentMetrics.extentBefore == _lastMetrics!.extentBefore && currentMetrics.extentInside == _lastMetrics!.extentInside && currentMetrics.extentAfter == _lastMetrics!.extentAfter && currentMetrics.axisDirection == _lastMetrics!.axisDirection); } @override bool applyContentDimensions(double minScrollExtent, double maxScrollExtent) { assert(haveDimensions == (_lastMetrics != null)); if (!nearEqual(_minScrollExtent, minScrollExtent, Tolerance.defaultTolerance.distance) || !nearEqual(_maxScrollExtent, maxScrollExtent, Tolerance.defaultTolerance.distance) || _didChangeViewportDimensionOrReceiveCorrection || _lastAxis != axis) { assert(minScrollExtent <= maxScrollExtent); _minScrollExtent = minScrollExtent; _maxScrollExtent = maxScrollExtent; _lastAxis = axis; final ScrollMetrics? currentMetrics = haveDimensions ? copyWith() : null; _didChangeViewportDimensionOrReceiveCorrection = false; _pendingDimensions = true; if (haveDimensions && !correctForNewDimensions(_lastMetrics!, currentMetrics!)) { return false; } _haveDimensions = true; } assert(haveDimensions); if (_pendingDimensions) { applyNewDimensions(); _pendingDimensions = false; } assert(!_didChangeViewportDimensionOrReceiveCorrection, 'Use correctForNewDimensions() (and return true) to change the scroll offset during applyContentDimensions().'); if (_isMetricsChanged()) { // It is too late to send useful notifications, because the potential // listeners have, by definition, already been built this frame. To make // sure the notification is sent at all, we delay it until after the frame // is complete. if (!_haveScheduledUpdateNotification) { scheduleMicrotask(didUpdateScrollMetrics); _haveScheduledUpdateNotification = true; } _lastMetrics = copyWith(); } return true; } /// Verifies that the new content and viewport dimensions are acceptable. /// /// Called by [applyContentDimensions] to determine its return value. /// /// Should return true if the current scroll offset is correct given /// the new content and viewport dimensions. /// /// Otherwise, should call [correctPixels] to correct the scroll /// offset given the new dimensions, and then return false. /// /// This is only called when [haveDimensions] is true. /// /// The default implementation defers to [ScrollPhysics.adjustPositionForNewDimensions]. @protected bool correctForNewDimensions(ScrollMetrics oldPosition, ScrollMetrics newPosition) { final double newPixels = physics.adjustPositionForNewDimensions( oldPosition: oldPosition, newPosition: newPosition, isScrolling: activity!.isScrolling, velocity: activity!.velocity, ); if (newPixels != pixels) { correctPixels(newPixels); return false; } return true; } /// Notifies the activity that the dimensions of the underlying viewport or /// contents have changed. /// /// Called after [applyViewportDimension] or [applyContentDimensions] have /// changed the [minScrollExtent], the [maxScrollExtent], or the /// [viewportDimension]. When this method is called, it should be called /// _after_ any corrections are applied to [pixels] using [correctPixels], not /// before. /// /// The default implementation informs the [activity] of the new dimensions by /// calling its [ScrollActivity.applyNewDimensions] method. /// /// See also: /// /// * [applyViewportDimension], which is called when new /// viewport dimensions are established. /// * [applyContentDimensions], which is called after new /// viewport dimensions are established, and also if new content dimensions /// are established, and which calls [ScrollPosition.applyNewDimensions]. @protected @mustCallSuper void applyNewDimensions() { assert(hasPixels); assert(_pendingDimensions); activity!.applyNewDimensions(); _updateSemanticActions(); // will potentially request a semantics update. } Set<SemanticsAction>? _semanticActions; /// Called whenever the scroll position or the dimensions of the scroll view /// change to schedule an update of the available semantics actions. The /// actual update will be performed in the next frame. If non is pending /// a frame will be scheduled. /// /// For example: If the scroll view has been scrolled all the way to the top, /// the action to scroll further up needs to be removed as the scroll view /// cannot be scrolled in that direction anymore. /// /// This method is potentially called twice per frame (if scroll position and /// scroll view dimensions both change) and therefore shouldn't do anything /// expensive. void _updateSemanticActions() { final (SemanticsAction forward, SemanticsAction backward) = switch (axisDirection) { AxisDirection.up => (SemanticsAction.scrollDown, SemanticsAction.scrollUp), AxisDirection.down => (SemanticsAction.scrollUp, SemanticsAction.scrollDown), AxisDirection.left => (SemanticsAction.scrollRight, SemanticsAction.scrollLeft), AxisDirection.right => (SemanticsAction.scrollLeft, SemanticsAction.scrollRight), }; final Set<SemanticsAction> actions = <SemanticsAction>{}; if (pixels > minScrollExtent) { actions.add(backward); } if (pixels < maxScrollExtent) { actions.add(forward); } if (setEquals<SemanticsAction>(actions, _semanticActions)) { return; } _semanticActions = actions; context.setSemanticsActions(_semanticActions!); } ScrollPositionAlignmentPolicy _maybeFlipAlignment(ScrollPositionAlignmentPolicy alignmentPolicy) { return switch (alignmentPolicy) { // Don't flip when explicit. ScrollPositionAlignmentPolicy.explicit => alignmentPolicy, ScrollPositionAlignmentPolicy.keepVisibleAtEnd => ScrollPositionAlignmentPolicy.keepVisibleAtStart, ScrollPositionAlignmentPolicy.keepVisibleAtStart => ScrollPositionAlignmentPolicy.keepVisibleAtEnd, }; } ScrollPositionAlignmentPolicy _applyAxisDirectionToAlignmentPolicy(ScrollPositionAlignmentPolicy alignmentPolicy) { return switch (axisDirection) { // Start and end alignments must account for axis direction. // When focus is requested for example, it knows the directionality of the // keyboard keys initiating traversal, but not the direction of the // Scrollable. AxisDirection.up || AxisDirection.left => _maybeFlipAlignment(alignmentPolicy), AxisDirection.down || AxisDirection.right => alignmentPolicy, }; } /// Animates the position such that the given object is as visible as possible /// by just scrolling this position. /// /// The optional `targetRenderObject` parameter is used to determine which area /// of that object should be as visible as possible. If `targetRenderObject` /// is null, the entire [RenderObject] (as defined by its /// [RenderObject.paintBounds]) will be as visible as possible. If /// `targetRenderObject` is provided, it must be a descendant of the object. /// /// See also: /// /// * [ScrollPositionAlignmentPolicy] for the way in which `alignment` is /// applied, and the way the given `object` is aligned. Future<void> ensureVisible( RenderObject object, { double alignment = 0.0, Duration duration = Duration.zero, Curve curve = Curves.ease, ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit, RenderObject? targetRenderObject, }) async { assert(object.attached); final RenderAbstractViewport? viewport = RenderAbstractViewport.maybeOf(object); // If no viewport is found, return. if (viewport == null) { return; } Rect? targetRect; if (targetRenderObject != null && targetRenderObject != object) { targetRect = MatrixUtils.transformRect( targetRenderObject.getTransformTo(object), object.paintBounds.intersect(targetRenderObject.paintBounds), ); } double target; switch (_applyAxisDirectionToAlignmentPolicy(alignmentPolicy)) { case ScrollPositionAlignmentPolicy.explicit: target = viewport.getOffsetToReveal( object, alignment, rect: targetRect, axis: axis, ).offset; target = clampDouble(target, minScrollExtent, maxScrollExtent); case ScrollPositionAlignmentPolicy.keepVisibleAtEnd: target = viewport.getOffsetToReveal( object, 1.0, // Aligns to end rect: targetRect, axis: axis, ).offset; target = clampDouble(target, minScrollExtent, maxScrollExtent); if (target < pixels) { target = pixels; } case ScrollPositionAlignmentPolicy.keepVisibleAtStart: target = viewport.getOffsetToReveal( object, 0.0, // Aligns to start rect: targetRect, axis: axis, ).offset; target = clampDouble(target, minScrollExtent, maxScrollExtent); if (target > pixels) { target = pixels; } } if (target == pixels) { return; } if (duration == Duration.zero) { jumpTo(target); return; } return animateTo(target, duration: duration, curve: curve); } /// This notifier's value is true if a scroll is underway and false if the scroll /// position is idle. /// /// Listeners added by stateful widgets should be removed in the widget's /// [State.dispose] method. final ValueNotifier<bool> isScrollingNotifier = ValueNotifier<bool>(false); /// Animates the position from its current value to the given value. /// /// Any active animation is canceled. If the user is currently scrolling, that /// action is canceled. /// /// The returned [Future] will complete when the animation ends, whether it /// completed successfully or whether it was interrupted prematurely. /// /// An animation will be interrupted whenever the user attempts to scroll /// manually, or whenever another activity is started, or whenever the /// animation reaches the edge of the viewport and attempts to overscroll. (If /// the [ScrollPosition] does not overscroll but instead allows scrolling /// beyond the extents, then going beyond the extents will not interrupt the /// animation.) /// /// The animation is indifferent to changes to the viewport or content /// dimensions. /// /// Once the animation has completed, the scroll position will attempt to /// begin a ballistic activity in case its value is not stable (for example, /// if it is scrolled beyond the extents and in that situation the scroll /// position would normally bounce back). /// /// The duration must not be zero. To jump to a particular value without an /// animation, use [jumpTo]. /// /// The animation is typically handled by an [DrivenScrollActivity]. @override Future<void> animateTo( double to, { required Duration duration, required Curve curve, }); /// Jumps the scroll position from its current value to the given value, /// without animation, and without checking if the new value is in range. /// /// Any active animation is canceled. If the user is currently scrolling, that /// action is canceled. /// /// If this method changes the scroll position, a sequence of start/update/end /// scroll notifications will be dispatched. No overscroll notifications can /// be generated by this method. @override void jumpTo(double value); /// Changes the scrolling position based on a pointer signal from current /// value to delta without animation and without checking if new value is in /// range, taking min/max scroll extent into account. /// /// Any active animation is canceled. If the user is currently scrolling, that /// action is canceled. /// /// This method dispatches the start/update/end sequence of scrolling /// notifications. /// /// This method is very similar to [jumpTo], but [pointerScroll] will /// update the [ScrollDirection]. void pointerScroll(double delta); /// Calls [jumpTo] if duration is null or [Duration.zero], otherwise /// [animateTo] is called. /// /// If [clamp] is true (the default) then [to] is adjusted to prevent over or /// underscroll. /// /// If [animateTo] is called then [curve] defaults to [Curves.ease]. @override Future<void> moveTo( double to, { Duration? duration, Curve? curve, bool? clamp = true, }) { assert(clamp != null); if (clamp!) { to = clampDouble(to, minScrollExtent, maxScrollExtent); } return super.moveTo(to, duration: duration, curve: curve); } @override bool get allowImplicitScrolling => physics.allowImplicitScrolling; /// Deprecated. Use [jumpTo] or a custom [ScrollPosition] instead. @Deprecated('This will lead to bugs.') // flutter_ignore: deprecation_syntax, https://github.com/flutter/flutter/issues/44609 void jumpToWithoutSettling(double value); /// Stop the current activity and start a [HoldScrollActivity]. ScrollHoldController hold(VoidCallback holdCancelCallback); /// Start a drag activity corresponding to the given [DragStartDetails]. /// /// The `onDragCanceled` argument will be invoked if the drag is ended /// prematurely (e.g. from another activity taking over). See /// [ScrollDragController.onDragCanceled] for details. Drag drag(DragStartDetails details, VoidCallback dragCancelCallback); /// The currently operative [ScrollActivity]. /// /// If the scroll position is not performing any more specific activity, the /// activity will be an [IdleScrollActivity]. To determine whether the scroll /// position is idle, check the [isScrollingNotifier]. /// /// Call [beginActivity] to change the current activity. @protected @visibleForTesting ScrollActivity? get activity => _activity; ScrollActivity? _activity; /// Change the current [activity], disposing of the old one and /// sending scroll notifications as necessary. /// /// If the argument is null, this method has no effect. This is convenient for /// cases where the new activity is obtained from another method, and that /// method might return null, since it means the caller does not have to /// explicitly null-check the argument. void beginActivity(ScrollActivity? newActivity) { if (newActivity == null) { return; } bool wasScrolling, oldIgnorePointer; if (_activity != null) { oldIgnorePointer = _activity!.shouldIgnorePointer; wasScrolling = _activity!.isScrolling; if (wasScrolling && !newActivity.isScrolling) { // Notifies and then saves the scroll offset. didEndScroll(); } _activity!.dispose(); } else { oldIgnorePointer = false; wasScrolling = false; } _activity = newActivity; if (oldIgnorePointer != activity!.shouldIgnorePointer) { context.setIgnorePointer(activity!.shouldIgnorePointer); } isScrollingNotifier.value = activity!.isScrolling; if (!wasScrolling && _activity!.isScrolling) { didStartScroll(); } } // NOTIFICATION DISPATCH /// Called by [beginActivity] to report when an activity has started. void didStartScroll() { activity!.dispatchScrollStartNotification(copyWith(), context.notificationContext); } /// Called by [setPixels] to report a change to the [pixels] position. void didUpdateScrollPositionBy(double delta) { activity!.dispatchScrollUpdateNotification(copyWith(), context.notificationContext!, delta); } /// Called by [beginActivity] to report when an activity has ended. /// /// This also saves the scroll offset using [saveScrollOffset]. void didEndScroll() { activity!.dispatchScrollEndNotification(copyWith(), context.notificationContext!); saveOffset(); if (keepScrollOffset) { saveScrollOffset(); } } /// Called by [setPixels] to report overscroll when an attempt is made to /// change the [pixels] position. Overscroll is the amount of change that was /// not applied to the [pixels] value. void didOverscrollBy(double value) { assert(activity!.isScrolling); activity!.dispatchOverscrollNotification(copyWith(), context.notificationContext!, value); } /// Dispatches a notification that the [userScrollDirection] has changed. /// /// Subclasses should call this function when they change [userScrollDirection]. void didUpdateScrollDirection(ScrollDirection direction) { UserScrollNotification(metrics: copyWith(), context: context.notificationContext!, direction: direction).dispatch(context.notificationContext); } /// Dispatches a notification that the [ScrollMetrics] have changed. void didUpdateScrollMetrics() { assert(SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks); assert(_haveScheduledUpdateNotification); _haveScheduledUpdateNotification = false; if (context.notificationContext != null) { ScrollMetricsNotification(metrics: copyWith(), context: context.notificationContext!).dispatch(context.notificationContext); } } /// Provides a heuristic to determine if expensive frame-bound tasks should be /// deferred. /// /// The actual work of this is delegated to the [physics] via /// [ScrollPhysics.recommendDeferredLoading] called with the current /// [activity]'s [ScrollActivity.velocity]. /// /// Returning true from this method indicates that the [ScrollPhysics] /// evaluate the current scroll velocity to be great enough that expensive /// operations impacting the UI should be deferred. bool recommendDeferredLoading(BuildContext context) { assert(activity != null); return physics.recommendDeferredLoading( activity!.velocity + _impliedVelocity, copyWith(), context, ); } @override void dispose() { activity?.dispose(); // it will be null if it got absorbed by another ScrollPosition _activity = null; isScrollingNotifier.dispose(); super.dispose(); } @override void notifyListeners() { _updateSemanticActions(); // will potentially request a semantics update. super.notifyListeners(); } @override void debugFillDescription(List<String> description) { if (debugLabel != null) { description.add(debugLabel!); } super.debugFillDescription(description); description.add('range: ${_minScrollExtent?.toStringAsFixed(1)}..${_maxScrollExtent?.toStringAsFixed(1)}'); description.add('viewport: ${_viewportDimension?.toStringAsFixed(1)}'); } } /// A notification that a scrollable widget's [ScrollMetrics] have changed. /// /// For example, when the content of a scrollable is altered, making it larger /// or smaller, this notification will be dispatched. Similarly, if the size /// of the window or parent changes, the scrollable can notify of these /// changes in dimensions. /// /// The above behaviors usually do not trigger [ScrollNotification] events, /// so this is useful for listening to [ScrollMetrics] changes that are not /// caused by the user scrolling. /// /// {@tool dartpad} /// This sample shows how a [ScrollMetricsNotification] is dispatched when /// the `windowSize` is changed. Press the floating action button to increase /// the scrollable window's size. /// /// ** See code in examples/api/lib/widgets/scroll_position/scroll_metrics_notification.0.dart ** /// {@end-tool} class ScrollMetricsNotification extends Notification with ViewportNotificationMixin { /// Creates a notification that the scrollable widget's [ScrollMetrics] have /// changed. ScrollMetricsNotification({ required this.metrics, required this.context, }); /// Description of a scrollable widget's [ScrollMetrics]. final ScrollMetrics metrics; /// The build context of the widget that fired this notification. /// /// This can be used to find the scrollable widget's render objects to /// determine the size of the viewport, for instance. final BuildContext context; /// Convert this notification to a [ScrollNotification]. /// /// This allows it to be used with [ScrollNotificationPredicate]s. ScrollUpdateNotification asScrollUpdate() { return ScrollUpdateNotification( metrics: metrics, context: context, depth: depth, ); } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); description.add('$metrics'); } }
flutter/packages/flutter/lib/src/widgets/scroll_position.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/scroll_position.dart", "repo_id": "flutter", "token_count": 13667 }
697
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'framework.dart'; import 'scroll_delegate.dart'; import 'sliver.dart'; /// A sliver that contains multiple box children that each fills the viewport. /// /// _To learn more about slivers, see [CustomScrollView.slivers]._ /// /// [SliverFillViewport] places its children in a linear array along the main /// axis. Each child is sized to fill the viewport, both in the main and cross /// axis. /// /// See also: /// /// * [SliverFixedExtentList], which has a configurable /// [SliverFixedExtentList.itemExtent]. /// * [SliverPrototypeExtentList], which is similar to [SliverFixedExtentList] /// except that it uses a prototype list item instead of a pixel value to define /// the main axis extent of each item. /// * [SliverList], which does not require its children to have the same /// extent in the main axis. class SliverFillViewport extends StatelessWidget { /// Creates a sliver whose box children that each fill the viewport. const SliverFillViewport({ super.key, required this.delegate, this.viewportFraction = 1.0, this.padEnds = true, }) : assert(viewportFraction > 0.0); /// The fraction of the viewport that each child should fill in the main axis. /// /// If this fraction is less than 1.0, more than one child will be visible at /// once. If this fraction is greater than 1.0, each child will be larger than /// the viewport in the main axis. final double viewportFraction; /// Whether to add padding to both ends of the list. /// /// If this is set to true and [viewportFraction] < 1.0, padding will be added /// such that the first and last child slivers will be in the center of the /// viewport when scrolled all the way to the start or end, respectively. You /// may want to set this to false if this [SliverFillViewport] is not the only /// widget along this main axis, such as in a [CustomScrollView] with multiple /// children. /// /// If [viewportFraction] is greater than one, this option has no effect. /// Defaults to true. final bool padEnds; /// {@macro flutter.widgets.SliverMultiBoxAdaptorWidget.delegate} final SliverChildDelegate delegate; @override Widget build(BuildContext context) { return _SliverFractionalPadding( viewportFraction: padEnds ? clampDouble(1 - viewportFraction, 0, 1) / 2 : 0, sliver: _SliverFillViewportRenderObjectWidget( viewportFraction: viewportFraction, delegate: delegate, ), ); } } class _SliverFillViewportRenderObjectWidget extends SliverMultiBoxAdaptorWidget { const _SliverFillViewportRenderObjectWidget({ required super.delegate, this.viewportFraction = 1.0, }) : assert(viewportFraction > 0.0); final double viewportFraction; @override RenderSliverFillViewport createRenderObject(BuildContext context) { final SliverMultiBoxAdaptorElement element = context as SliverMultiBoxAdaptorElement; return RenderSliverFillViewport(childManager: element, viewportFraction: viewportFraction); } @override void updateRenderObject(BuildContext context, RenderSliverFillViewport renderObject) { renderObject.viewportFraction = viewportFraction; } } class _SliverFractionalPadding extends SingleChildRenderObjectWidget { const _SliverFractionalPadding({ this.viewportFraction = 0, Widget? sliver, }) : assert(viewportFraction >= 0), assert(viewportFraction <= 0.5), super(child: sliver); final double viewportFraction; @override RenderObject createRenderObject(BuildContext context) => _RenderSliverFractionalPadding(viewportFraction: viewportFraction); @override void updateRenderObject(BuildContext context, _RenderSliverFractionalPadding renderObject) { renderObject.viewportFraction = viewportFraction; } } class _RenderSliverFractionalPadding extends RenderSliverEdgeInsetsPadding { _RenderSliverFractionalPadding({ double viewportFraction = 0, }) : assert(viewportFraction <= 0.5), assert(viewportFraction >= 0), _viewportFraction = viewportFraction; SliverConstraints? _lastResolvedConstraints; double get viewportFraction => _viewportFraction; double _viewportFraction; set viewportFraction(double newValue) { if (_viewportFraction == newValue) { return; } _viewportFraction = newValue; _markNeedsResolution(); } @override EdgeInsets? get resolvedPadding => _resolvedPadding; EdgeInsets? _resolvedPadding; void _markNeedsResolution() { _resolvedPadding = null; markNeedsLayout(); } void _resolve() { if (_resolvedPadding != null && _lastResolvedConstraints == constraints) { return; } final double paddingValue = constraints.viewportMainAxisExtent * viewportFraction; _lastResolvedConstraints = constraints; _resolvedPadding = switch (constraints.axis) { Axis.horizontal => EdgeInsets.symmetric(horizontal: paddingValue), Axis.vertical => EdgeInsets.symmetric(vertical: paddingValue), }; return; } @override void performLayout() { _resolve(); super.performLayout(); } } /// A sliver that contains a single box child that fills the remaining space in /// the viewport. /// /// _To learn more about slivers, see [CustomScrollView.slivers]._ /// /// [SliverFillRemaining] will size its [child] to fill the viewport in the /// cross axis. The extent of the sliver and its child's size in the main axis /// is computed conditionally, described in further detail below. /// /// Typically this will be the last sliver in a viewport, since (by definition) /// there is never any room for anything beyond this sliver. /// /// ## Main Axis Extent /// /// ### When [SliverFillRemaining] has a scrollable child /// /// The [hasScrollBody] flag indicates whether the sliver's child has a /// scrollable body. This value is never null, and defaults to true. A common /// example of this use is a [NestedScrollView]. In this case, the sliver will /// size its child to fill the maximum available extent. [SliverFillRemaining] /// will not constrain the scrollable area, as it could potentially have an /// infinite depth. This is also true for use cases such as a [ScrollView] when /// [ScrollView.shrinkWrap] is true. /// /// ### When [SliverFillRemaining] does not have a scrollable child /// /// When [hasScrollBody] is set to false, the child's size is taken into account /// when considering the extent to which it should fill the space. The extent to /// which the preceding slivers have been scrolled is also taken into /// account in deciding how to layout this sliver. /// /// [SliverFillRemaining] will size its [child] to fill the viewport in the /// main axis if that space is larger than the child's extent, and the amount /// of space that has been scrolled beforehand has not exceeded the main axis /// extent of the viewport. /// /// {@tool dartpad} /// In this sample the [SliverFillRemaining] sizes its [child] to fill the /// remaining extent of the viewport in both axes. The icon is centered in the /// sliver, and would be in any computed extent for the sliver. /// /// ** See code in examples/api/lib/widgets/sliver_fill/sliver_fill_remaining.0.dart ** /// {@end-tool} /// /// [SliverFillRemaining] will defer to the size of its [child] if the /// child's size exceeds the remaining space in the viewport. /// /// {@tool dartpad} /// In this sample the [SliverFillRemaining] defers to the size of its [child] /// because the child's extent exceeds that of the remaining extent of the /// viewport's main axis. /// /// ** See code in examples/api/lib/widgets/sliver_fill/sliver_fill_remaining.1.dart ** /// {@end-tool} /// /// [SliverFillRemaining] will defer to the size of its [child] if the /// [SliverConstraints.precedingScrollExtent] exceeded the length of the viewport's main axis. /// /// {@tool dartpad} /// In this sample the [SliverFillRemaining] defers to the size of its [child] /// because the [SliverConstraints.precedingScrollExtent] has gone /// beyond that of the viewport's main axis. /// /// ** See code in examples/api/lib/widgets/sliver_fill/sliver_fill_remaining.2.dart ** /// {@end-tool} /// /// For [ScrollPhysics] that allow overscroll, such as /// [BouncingScrollPhysics], setting the [fillOverscroll] flag to true allows /// the size of the [child] to _stretch_, filling the overscroll area. It does /// this regardless of the path chosen to provide the child's size. /// /// {@animation 250 500 https://flutter.github.io/assets-for-api-docs/assets/widgets/sliver_fill_remaining_fill_overscroll.mp4} /// /// {@tool dartpad} /// In this sample the [SliverFillRemaining]'s child stretches to fill the /// overscroll area when [fillOverscroll] is true. This sample also features a /// button that is pinned to the bottom of the sliver, regardless of size or /// overscroll behavior. Try switching [fillOverscroll] to see the difference. /// /// This sample only shows the overscroll behavior on devices that support /// overscroll. /// /// ** See code in examples/api/lib/widgets/sliver_fill/sliver_fill_remaining.3.dart ** /// {@end-tool} /// /// /// See also: /// /// * [SliverFillViewport], which sizes its children based on the /// size of the viewport, regardless of what else is in the scroll view. /// * [SliverList], which shows a list of variable-sized children in a /// viewport. class SliverFillRemaining extends StatelessWidget { /// Creates a sliver that fills the remaining space in the viewport. const SliverFillRemaining({ super.key, this.child, this.hasScrollBody = true, this.fillOverscroll = false, }); /// Box child widget that fills the remaining space in the viewport. /// /// The main [SliverFillRemaining] documentation contains more details. final Widget? child; /// Indicates whether the child has a scrollable body, this value cannot be /// null. /// /// Defaults to true such that the child will extend beyond the viewport and /// scroll, as seen in [NestedScrollView]. /// /// Setting this value to false will allow the child to fill the remainder of /// the viewport and not extend further. However, if the /// [SliverConstraints.precedingScrollExtent] and/or the [child]'s /// extent exceeds the size of the viewport, the sliver will defer to the /// child's size rather than overriding it. final bool hasScrollBody; /// Indicates whether the child should stretch to fill the overscroll area /// created by certain scroll physics, such as iOS' default scroll physics. /// This flag is only relevant when [hasScrollBody] is false. /// /// Defaults to false, meaning that the default behavior is for the child to /// maintain its size and not extend into the overscroll area. final bool fillOverscroll; @override Widget build(BuildContext context) { if (hasScrollBody) { return _SliverFillRemainingWithScrollable(child: child); } if (!fillOverscroll) { return _SliverFillRemainingWithoutScrollable(child: child); } return _SliverFillRemainingAndOverscroll(child: child); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add( DiagnosticsProperty<Widget>( 'child', child, ), ); final List<String> flags = <String>[ if (hasScrollBody) 'scrollable', if (fillOverscroll) 'fillOverscroll', ]; if (flags.isEmpty) { flags.add('nonscrollable'); } properties.add(IterableProperty<String>('mode', flags)); } } class _SliverFillRemainingWithScrollable extends SingleChildRenderObjectWidget { const _SliverFillRemainingWithScrollable({ super.child, }); @override RenderSliverFillRemainingWithScrollable createRenderObject(BuildContext context) => RenderSliverFillRemainingWithScrollable(); } class _SliverFillRemainingWithoutScrollable extends SingleChildRenderObjectWidget { const _SliverFillRemainingWithoutScrollable({ super.child, }); @override RenderSliverFillRemaining createRenderObject(BuildContext context) => RenderSliverFillRemaining(); } class _SliverFillRemainingAndOverscroll extends SingleChildRenderObjectWidget { const _SliverFillRemainingAndOverscroll({ super.child, }); @override RenderSliverFillRemainingAndOverscroll createRenderObject(BuildContext context) => RenderSliverFillRemainingAndOverscroll(); }
flutter/packages/flutter/lib/src/widgets/sliver_fill.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/sliver_fill.dart", "repo_id": "flutter", "token_count": 3852 }
698
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/rendering.dart'; /// A [SingleChildLayoutDelegate] for use with [CustomSingleChildLayout] that /// positions its child above [anchorAbove] if it fits, or otherwise below /// [anchorBelow]. /// /// Primarily intended for use with toolbars or context menus. /// /// See also: /// /// * [TextSelectionToolbar], which uses this to position itself. /// * [CupertinoTextSelectionToolbar], which also uses this to position /// itself. class TextSelectionToolbarLayoutDelegate extends SingleChildLayoutDelegate { /// Creates an instance of TextSelectionToolbarLayoutDelegate. /// /// The [fitsAbove] parameter is optional; if omitted, it will be calculated. TextSelectionToolbarLayoutDelegate({ required this.anchorAbove, required this.anchorBelow, this.fitsAbove, }); /// {@macro flutter.material.TextSelectionToolbar.anchorAbove} /// /// Should be provided in local coordinates. final Offset anchorAbove; /// {@macro flutter.material.TextSelectionToolbar.anchorAbove} /// /// Should be provided in local coordinates. final Offset anchorBelow; /// Whether or not the child should be considered to fit above anchorAbove. /// /// Typically used to force the child to be drawn at anchorAbove even when it /// doesn't fit, such as when the Material [TextSelectionToolbar] draws an /// open overflow menu. /// /// If not provided, it will be calculated. final bool? fitsAbove; /// Return the distance from zero that centers `width` as closely as possible /// to `position` from zero while fitting between zero and `max`. static double centerOn(double position, double width, double max) { // If it overflows on the left, put it as far left as possible. if (position - width / 2.0 < 0.0) { return 0.0; } // If it overflows on the right, put it as far right as possible. if (position + width / 2.0 > max) { return max - width; } // Otherwise it fits while perfectly centered. return position - width / 2.0; } @override BoxConstraints getConstraintsForChild(BoxConstraints constraints) { return constraints.loosen(); } @override Offset getPositionForChild(Size size, Size childSize) { final bool fitsAbove = this.fitsAbove ?? anchorAbove.dy >= childSize.height; final Offset anchor = fitsAbove ? anchorAbove : anchorBelow; return Offset( centerOn( anchor.dx, childSize.width, size.width, ), fitsAbove ? math.max(0.0, anchor.dy - childSize.height) : anchor.dy, ); } @override bool shouldRelayout(TextSelectionToolbarLayoutDelegate oldDelegate) { return anchorAbove != oldDelegate.anchorAbove || anchorBelow != oldDelegate.anchorBelow || fitsAbove != oldDelegate.fitsAbove; } }
flutter/packages/flutter/lib/src/widgets/text_selection_toolbar_layout_delegate.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/text_selection_toolbar_layout_delegate.dart", "repo_id": "flutter", "token_count": 955 }
699
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; // Examples can assume: // late BuildContext context; /// Interactive states that some of the widgets can take on when receiving input /// from the user. /// /// States are defined by https://material.io/design/interaction/states.html#usage, /// but are not limited to the Material design system or library. /// /// Some widgets track their current state in a `Set<WidgetState>`. /// /// See also: /// /// * [MaterialState], the Material specific version of `WidgetState`. /// * [WidgetStateProperty], an interface for objects that "resolve" to /// different values depending on a widget's state. /// {@template flutter.widgets.WidgetStateProperty.implementations} /// * [WidgetStateColor], a [Color] that implements `WidgetStateProperty` /// which is used in APIs that need to accept either a [Color] or a /// `WidgetStateProperty<Color>`. /// * [WidgetStateMouseCursor], a [MouseCursor] that implements /// `WidgetStateProperty` which is used in APIs that need to accept either /// a [MouseCursor] or a [WidgetStateProperty<MouseCursor>]. /// * [WidgetStateOutlinedBorder], an [OutlinedBorder] that implements /// `WidgetStateProperty` which is used in APIs that need to accept either /// an [OutlinedBorder] or a [WidgetStateProperty<OutlinedBorder>]. /// * [WidgetStateBorderSide], a [BorderSide] that implements /// `WidgetStateProperty` which is used in APIs that need to accept either /// a [BorderSide] or a [WidgetStateProperty<BorderSide>]. /// * [WidgetStateTextStyle], a [TextStyle] that implements /// `WidgetStateProperty` which is used in APIs that need to accept either /// a [TextStyle] or a [WidgetStateProperty<TextStyle>]. /// {@endtemplate} enum WidgetState { /// The state when the user drags their mouse cursor over the given widget. /// /// See: https://material.io/design/interaction/states.html#hover. hovered, /// The state when the user navigates with the keyboard to a given widget. /// /// This can also sometimes be triggered when a widget is tapped. For example, /// when a [TextField] is tapped, it becomes [focused]. /// /// See: https://material.io/design/interaction/states.html#focus. focused, /// The state when the user is actively pressing down on the given widget. /// /// See: https://material.io/design/interaction/states.html#pressed. pressed, /// The state when this widget is being dragged from one place to another by /// the user. /// /// https://material.io/design/interaction/states.html#dragged. dragged, /// The state when this item has been selected. /// /// This applies to things that can be toggled (such as chips and checkboxes) /// and things that are selected from a set of options (such as tabs and radio buttons). /// /// See: https://material.io/design/interaction/states.html#selected. selected, /// The state when this widget overlaps the content of a scrollable below. /// /// Used by [AppBar] to indicate that the primary scrollable's /// content has scrolled up and behind the app bar. scrolledUnder, /// The state when this widget is disabled and cannot be interacted with. /// /// Disabled widgets should not respond to hover, focus, press, or drag /// interactions. /// /// See: https://material.io/design/interaction/states.html#disabled. disabled, /// The state when the widget has entered some form of invalid state. /// /// See https://material.io/design/interaction/states.html#usage. error, } /// Signature for the function that returns a value of type `T` based on a given /// set of states. typedef WidgetPropertyResolver<T> = T Function(Set<WidgetState> states); /// Defines a [Color] that is also a [WidgetStateProperty]. /// /// This class exists to enable widgets with [Color] valued properties /// to also accept [WidgetStateProperty<Color>] values. A widget /// state color property represents a color which depends on /// a widget's "interactive state". This state is represented as a /// [Set] of [WidgetState]s, like [WidgetState.pressed], /// [WidgetState.focused] and [WidgetState.hovered]. /// /// [WidgetStateColor] should only be used with widgets that document /// their support, like [TimePickerThemeData.dayPeriodColor]. /// /// To use a [WidgetStateColor], you can either: /// 1. Create a subclass of [WidgetStateColor] and implement the abstract `resolve` method. /// 2. Use [WidgetStateColor.resolveWith] and pass in a callback that /// will be used to resolve the color in the given states. /// /// If a [WidgetStateColor] is used for a property or a parameter that doesn't /// support resolving [WidgetStateProperty<Color>]s, then its default color /// value will be used for all states. /// /// To define a `const` [WidgetStateColor], you'll need to extend /// [WidgetStateColor] and override its [resolve] method. You'll also need /// to provide a `defaultValue` to the super constructor, so that we can know /// at compile-time what its default color is. /// /// {@tool snippet} /// /// This example defines a [WidgetStateColor] with a const constructor. /// /// ```dart /// class MyColor extends WidgetStateColor { /// const MyColor() : super(_defaultColor); /// /// static const int _defaultColor = 0xcafefeed; /// static const int _pressedColor = 0xdeadbeef; /// /// @override /// Color resolve(Set<WidgetState> states) { /// if (states.contains(WidgetState.pressed)) { /// return const Color(_pressedColor); /// } /// return const Color(_defaultColor); /// } /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [MaterialStateColor], the Material specific version of `WidgetStateColor`. abstract class WidgetStateColor extends Color implements WidgetStateProperty<Color> { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const WidgetStateColor(super.defaultValue); /// Creates a [WidgetStateColor] from a [WidgetPropertyResolver<Color>] /// callback function. /// /// If used as a regular color, the color resolved in the default state (the /// empty set of states) will be used. /// /// The given callback parameter must return a non-null color in the default /// state. static WidgetStateColor resolveWith(WidgetPropertyResolver<Color> callback) => _WidgetStateColor(callback); /// Returns a [Color] that's to be used when a component is in the specified /// state. @override Color resolve(Set<WidgetState> states); /// A constant whose value is transparent for all states. static const WidgetStateColor transparent = _WidgetStateColorTransparent(); } class _WidgetStateColor extends WidgetStateColor { _WidgetStateColor(this._resolve) : super(_resolve(_defaultStates).value); final WidgetPropertyResolver<Color> _resolve; static const Set<WidgetState> _defaultStates = <WidgetState>{}; @override Color resolve(Set<WidgetState> states) => _resolve(states); } class _WidgetStateColorTransparent extends WidgetStateColor { const _WidgetStateColorTransparent() : super(0x00000000); @override Color resolve(Set<WidgetState> states) => const Color(0x00000000); } /// Defines a [MouseCursor] whose value depends on a set of [WidgetState]s which /// represent the interactive state of a component. /// /// This kind of [MouseCursor] is useful when the set of interactive /// actions a widget supports varies with its state. For example, a /// mouse pointer hovering over a disabled [ListTile] should not /// display [SystemMouseCursors.click], since a disabled list tile /// doesn't respond to mouse clicks. [ListTile]'s default mouse cursor /// is a [WidgetStateMouseCursor.clickable], which resolves to /// [SystemMouseCursors.basic] when the button is disabled. /// /// To use a [WidgetStateMouseCursor], you should create a subclass of /// [WidgetStateMouseCursor] and implement the abstract `resolve` method. /// /// {@tool dartpad} /// This example defines a mouse cursor that resolves to /// [SystemMouseCursors.forbidden] when its widget is disabled. /// /// ** See code in examples/api/lib/material/material_state/material_state_mouse_cursor.0.dart ** /// {@end-tool} /// /// This class should only be used for parameters which are documented to take /// [WidgetStateMouseCursor], otherwise only the default state will be used. /// /// See also: /// /// * [MaterialStateMouseCursor], the Material specific version of /// `WidgetStateMouseCursor`. /// * [MouseCursor] for introduction on the mouse cursor system. /// * [SystemMouseCursors], which defines cursors that are supported by /// native platforms. abstract class WidgetStateMouseCursor extends MouseCursor implements WidgetStateProperty<MouseCursor> { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const WidgetStateMouseCursor(); @protected @override MouseCursorSession createSession(int device) { return resolve(<WidgetState>{}).createSession(device); } /// Returns a [MouseCursor] that's to be used when a component is in the /// specified state. @override MouseCursor resolve(Set<WidgetState> states); /// A mouse cursor for clickable widgets, which resolves differently when the /// widget is disabled. /// /// By default this cursor resolves to [SystemMouseCursors.click]. If the widget is /// disabled, the cursor resolves to [SystemMouseCursors.basic]. /// /// This cursor is the default for many widgets. static const WidgetStateMouseCursor clickable = _EnabledAndDisabledMouseCursor( enabledCursor: SystemMouseCursors.click, disabledCursor: SystemMouseCursors.basic, name: 'clickable', ); /// A mouse cursor for widgets related to text, which resolves differently /// when the widget is disabled. /// /// By default this cursor resolves to [SystemMouseCursors.text]. If the widget is /// disabled, the cursor resolves to [SystemMouseCursors.basic]. /// /// This cursor is the default for many widgets. static const WidgetStateMouseCursor textable = _EnabledAndDisabledMouseCursor( enabledCursor: SystemMouseCursors.text, disabledCursor: SystemMouseCursors.basic, name: 'textable', ); } class _EnabledAndDisabledMouseCursor extends WidgetStateMouseCursor { const _EnabledAndDisabledMouseCursor({ required this.enabledCursor, required this.disabledCursor, required this.name, }); final MouseCursor enabledCursor; final MouseCursor disabledCursor; final String name; @override MouseCursor resolve(Set<WidgetState> states) { if (states.contains(WidgetState.disabled)) { return disabledCursor; } return enabledCursor; } @override String get debugDescription => 'WidgetStateMouseCursor($name)'; } /// Defines a [BorderSide] whose value depends on a set of [WidgetState]s /// which represent the interactive state of a component. /// /// To use a [WidgetStateBorderSide], you should create a subclass of a /// [WidgetStateBorderSide] and override the abstract `resolve` method. /// /// This class enables existing widget implementations with [BorderSide] /// properties to be extended to also effectively support `WidgetStateProperty<BorderSide>` /// property values. [WidgetStateBorderSide] should only be used with widgets that document /// their support, like [ActionChip.side]. /// /// This class should only be used for parameters which are documented to take /// [WidgetStateBorderSide], otherwise only the default state will be used. /// /// See also: /// /// * [MaterialStateBorderSide], the Material specific version of /// `WidgetStateBorderSide`. abstract class WidgetStateBorderSide extends BorderSide implements WidgetStateProperty<BorderSide?> { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const WidgetStateBorderSide(); /// Creates a [WidgetStateBorderSide] from a /// [WidgetPropertyResolver<BorderSide?>] callback function. /// /// If used as a regular [BorderSide], the border resolved in the default state /// (the empty set of states) will be used. /// /// Usage: /// /// ```dart /// ChipTheme( /// data: Theme.of(context).chipTheme.copyWith( /// side: WidgetStateBorderSide.resolveWith((Set<WidgetState> states) { /// if (states.contains(WidgetState.selected)) { /// return const BorderSide(color: Colors.red); /// } /// return null; // Defer to default value on the theme or widget. /// }), /// ), /// child: const Chip( /// label: Text('Transceiver'), /// ), /// ), /// ``` /// /// Alternatively: /// /// ```dart /// Chip( /// label: const Text('Transceiver'), /// side: WidgetStateBorderSide.resolveWith((Set<WidgetState> states) { /// if (states.contains(WidgetState.selected)) { /// return const BorderSide(color: Colors.red); /// } /// return null; // Defer to default value on the theme or widget. /// }), /// ), /// ``` const factory WidgetStateBorderSide.resolveWith(WidgetPropertyResolver<BorderSide?> callback) = _WidgetStateBorderSide; /// Returns a [BorderSide] that's to be used when a Material component is /// in the specified state. Return null to defer to the default value of the /// widget or theme. @override BorderSide? resolve(Set<WidgetState> states); } class _WidgetStateBorderSide extends WidgetStateBorderSide { const _WidgetStateBorderSide(this._resolve); final WidgetPropertyResolver<BorderSide?> _resolve; @override BorderSide? resolve(Set<WidgetState> states) => _resolve(states); } /// Defines an [OutlinedBorder] whose value depends on a set of [WidgetState]s /// which represent the interactive state of a component. /// /// To use a [WidgetStateOutlinedBorder], you should create a subclass of an /// [OutlinedBorder] and implement [WidgetStateOutlinedBorder]'s abstract /// `resolve` method. /// /// {@tool dartpad} /// This example defines a subclass of [RoundedRectangleBorder] and an /// implementation of [WidgetStateOutlinedBorder], that resolves to /// [RoundedRectangleBorder] when its widget is selected. /// /// ** See code in examples/api/lib/material/material_state/material_state_outlined_border.0.dart ** /// {@end-tool} /// /// This class should only be used for parameters which are documented to take /// [WidgetStateOutlinedBorder], otherwise only the default state will be used. /// /// See also: /// /// * [ShapeBorder] the base class for shape outlines. /// * [MaterialStateOutlinedBorder], the Material specific version of /// `WidgetStateOutlinedBorder`. abstract class WidgetStateOutlinedBorder extends OutlinedBorder implements WidgetStateProperty<OutlinedBorder?> { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const WidgetStateOutlinedBorder(); /// Returns an [OutlinedBorder] that's to be used when a component is in the /// specified state. Return null to defer to the default value of the widget /// or theme. @override OutlinedBorder? resolve(Set<WidgetState> states); } /// Defines a [TextStyle] that is also a [WidgetStateProperty]. /// /// This class exists to enable widgets with [TextStyle] valued properties /// to also accept [WidgetStateProperty<TextStyle>] values. A widget /// state text style property represents a text style which depends on /// a widget's "interactive state". This state is represented as a /// [Set] of [WidgetState]s, like [WidgetState.pressed], /// [WidgetState.focused] and [WidgetState.hovered]. /// /// [WidgetStateTextStyle] should only be used with widgets that document /// their support, like [InputDecoration.labelStyle]. /// /// To use a [WidgetStateTextStyle], you can either: /// 1. Create a subclass of [WidgetStateTextStyle] and implement the abstract `resolve` method. /// 2. Use [WidgetStateTextStyle.resolveWith] and pass in a callback that /// will be used to resolve the color in the given states. /// /// If a [WidgetStateTextStyle] is used for a property or a parameter that doesn't /// support resolving [WidgetStateProperty<TextStyle>]s, then its default color /// value will be used for all states. /// /// To define a `const` [WidgetStateTextStyle], you'll need to extend /// [WidgetStateTextStyle] and override its [resolve] method. You'll also need /// to provide a `defaultValue` to the super constructor, so that we can know /// at compile-time what its default color is. /// See also: /// /// * [MaterialStateTextStyle], the Material specific version of /// `WidgetStateTextStyle`. abstract class WidgetStateTextStyle extends TextStyle implements WidgetStateProperty<TextStyle> { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const WidgetStateTextStyle(); /// Creates a [WidgetStateTextStyle] from a [WidgetPropertyResolver<TextStyle>] /// callback function. /// /// If used as a regular text style, the style resolved in the default state (the /// empty set of states) will be used. /// /// The given callback parameter must return a non-null text style in the default /// state. const factory WidgetStateTextStyle.resolveWith(WidgetPropertyResolver<TextStyle> callback) = _WidgetStateTextStyle; /// Returns a [TextStyle] that's to be used when a component is in the /// specified state. @override TextStyle resolve(Set<WidgetState> states); } class _WidgetStateTextStyle extends WidgetStateTextStyle { const _WidgetStateTextStyle(this._resolve); final WidgetPropertyResolver<TextStyle> _resolve; @override TextStyle resolve(Set<WidgetState> states) => _resolve(states); } /// Interface for classes that [resolve] to a value of type `T` based /// on a widget's interactive "state", which is defined as a set /// of [WidgetState]s. /// /// Widget state properties represent values that depend on a widget's "state". /// The state is encoded as a set of [WidgetState] values, like /// [WidgetState.focused], [WidgetState.hovered], [WidgetState.pressed]. For /// example the [InkWell.overlayColor] defines the color that fills the ink well /// when it's pressed (the "splash color"), focused, or hovered. The [InkWell] /// uses the overlay color's [resolve] method to compute the color for the /// ink well's current state. /// /// [ButtonStyle], which is used to configure the appearance of /// buttons like [TextButton], [ElevatedButton], and [OutlinedButton], /// has many material state properties. The button widgets keep track /// of their current material state and [resolve] the button style's /// material state properties when their value is needed. /// /// See also: /// /// * [MaterialStateProperty], the Material specific version of /// `WidgetStateProperty`. /// {@macro flutter.widgets.WidgetStateProperty.implementations} abstract class WidgetStateProperty<T> { /// Returns a value of type `T` that depends on [states]. /// /// Widgets like [TextButton] and [ElevatedButton] apply this method to their /// current [WidgetState]s to compute colors and other visual parameters /// at build time. T resolve(Set<WidgetState> states); /// Resolves the value for the given set of states if `value` is a /// [WidgetStateProperty], otherwise returns the value itself. /// /// This is useful for widgets that have parameters which can optionally be a /// [WidgetStateProperty]. For example, [InkWell.mouseCursor] can be a /// [MouseCursor] or a [WidgetStateProperty<MouseCursor>]. static T resolveAs<T>(T value, Set<WidgetState> states) { if (value is WidgetStateProperty<T>) { final WidgetStateProperty<T> property = value; return property.resolve(states); } return value; } /// Convenience method for creating a [WidgetStateProperty] from a /// [WidgetPropertyResolver] function alone. static WidgetStateProperty<T> resolveWith<T>(WidgetPropertyResolver<T> callback) => _WidgetStatePropertyWith<T>(callback); /// Convenience method for creating a [WidgetStateProperty] that resolves /// to a single value for all states. /// /// If you need a const value, use [WidgetStatePropertyAll] directly. /// // TODO(darrenaustin): Deprecate this when we have the ability to create // a dart fix that will replace this with WidgetStatePropertyAll: // https://github.com/dart-lang/sdk/issues/49056. static WidgetStateProperty<T> all<T>(T value) => WidgetStatePropertyAll<T>(value); /// Linearly interpolate between two [WidgetStateProperty]s. static WidgetStateProperty<T?>? lerp<T>( WidgetStateProperty<T>? a, WidgetStateProperty<T>? b, double t, T? Function(T?, T?, double) lerpFunction, ) { // Avoid creating a _LerpProperties object for a common case. if (a == null && b == null) { return null; } return _LerpProperties<T>(a, b, t, lerpFunction); } } class _LerpProperties<T> implements WidgetStateProperty<T?> { const _LerpProperties(this.a, this.b, this.t, this.lerpFunction); final WidgetStateProperty<T>? a; final WidgetStateProperty<T>? b; final double t; final T? Function(T?, T?, double) lerpFunction; @override T? resolve(Set<WidgetState> states) { final T? resolvedA = a?.resolve(states); final T? resolvedB = b?.resolve(states); return lerpFunction(resolvedA, resolvedB, t); } } class _WidgetStatePropertyWith<T> implements WidgetStateProperty<T> { _WidgetStatePropertyWith(this._resolve); final WidgetPropertyResolver<T> _resolve; @override T resolve(Set<WidgetState> states) => _resolve(states); } /// Convenience class for creating a [WidgetStateProperty] that /// resolves to the given value for all states. /// /// See also: /// /// * [MaterialStatePropertyAll], the Material specific version of /// `WidgetStatePropertyAll`. class WidgetStatePropertyAll<T> implements WidgetStateProperty<T> { /// Constructs a [WidgetStateProperty] that always resolves to the given /// value. const WidgetStatePropertyAll(this.value); /// The value of the property that will be used for all states. final T value; @override T resolve(Set<WidgetState> states) => value; @override String toString() { if (value is double) { return 'WidgetStatePropertyAll(${debugFormatDouble(value as double)})'; } else { return 'WidgetStatePropertyAll($value)'; } } } /// Manages a set of [WidgetState]s and notifies listeners of changes. /// /// Used by widgets that expose their internal state for the sake of /// extensions that add support for additional states. See /// [TextButton] for an example. /// /// The controller's [value] is its current set of states. Listeners /// are notified whenever the [value] changes. The [value] should only be /// changed with [update]; it should not be modified directly. /// /// The controller's [value] represents the set of states that a /// widget's visual properties, typically [WidgetStateProperty] /// values, are resolved against. It is _not_ the intrinsic state of /// the widget. The widget is responsible for ensuring that the /// controller's [value] tracks its intrinsic state. For example one /// cannot request the keyboard focus for a widget by adding /// [WidgetState.focused] to its controller. When the widget gains the /// or loses the focus it will [update] its controller's [value] and /// notify listeners of the change. /// /// When calling `setState` in a [MaterialStatesController] listener, use the /// [SchedulerBinding.addPostFrameCallback] to delay the call to `setState` after /// the frame has been rendered. It's generally prudent to use the /// [SchedulerBinding.addPostFrameCallback] because some of the widgets that /// depend on [MaterialStatesController] may call [update] in their build method. /// In such cases, listener's that call `setState` - during the build phase - will cause /// an error. /// /// See also: /// /// * [MaterialStatesController], the Material specific version of /// `WidgetStatesController`. class WidgetStatesController extends ValueNotifier<Set<WidgetState>> { /// Creates a WidgetStatesController. WidgetStatesController([Set<WidgetState>? value]) : super(<WidgetState>{...?value}); /// Adds [state] to [value] if [add] is true, and removes it otherwise, /// and notifies listeners if [value] has changed. void update(WidgetState state, bool add) { final bool valueChanged = add ? value.add(state) : value.remove(state); if (valueChanged) { notifyListeners(); } } }
flutter/packages/flutter/lib/src/widgets/widget_state.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/widget_state.dart", "repo_id": "flutter", "token_count": 7035 }
700
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { setUp(() { WidgetsFlutterBinding.ensureInitialized(); WidgetsBinding.instance.resetEpoch(); }); test('AnimationController with mutating listener', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<String> log = <String>[]; void listener1() { log.add('listener1'); } void listener3() { log.add('listener3'); } void listener4() { log.add('listener4'); } void listener2() { log.add('listener2'); controller.removeListener(listener1); controller.removeListener(listener3); controller.addListener(listener4); } controller.addListener(listener1); controller.addListener(listener2); controller.addListener(listener3); controller.value = 0.2; expect(log, <String>['listener1', 'listener2']); log.clear(); controller.value = 0.3; expect(log, <String>['listener2', 'listener4']); log.clear(); controller.value = 0.4; expect(log, <String>['listener2', 'listener4', 'listener4']); log.clear(); }); test('AnimationController with mutating status listener', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<String> log = <String>[]; void listener1(AnimationStatus status) { log.add('listener1'); } void listener3(AnimationStatus status) { log.add('listener3'); } void listener4(AnimationStatus status) { log.add('listener4'); } void listener2(AnimationStatus status) { log.add('listener2'); controller.removeStatusListener(listener1); controller.removeStatusListener(listener3); controller.addStatusListener(listener4); } controller.addStatusListener(listener1); controller.addStatusListener(listener2); controller.addStatusListener(listener3); controller.forward(); expect(log, <String>['listener1', 'listener2']); log.clear(); controller.reverse(); expect(log, <String>['listener2', 'listener4']); log.clear(); controller.forward(); expect(log, <String>['listener2', 'listener4', 'listener4']); log.clear(); controller.dispose(); }); testWidgets('AnimationController with throwing listener', (WidgetTester tester) async { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); addTearDown(controller.dispose); final List<String> log = <String>[]; void listener1() { log.add('listener1'); } void badListener() { log.add('badListener'); throw ArgumentError(); } void listener2() { log.add('listener2'); } controller.addListener(listener1); controller.addListener(badListener); controller.addListener(listener2); controller.value = 0.2; expect(log, <String>['listener1', 'badListener', 'listener2']); expect(tester.takeException(), isArgumentError); log.clear(); }); testWidgets('AnimationController with throwing status listener', (WidgetTester tester) async { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<String> log = <String>[]; void listener1(AnimationStatus status) { log.add('listener1'); } void badListener(AnimationStatus status) { log.add('badListener'); throw ArgumentError(); } void listener2(AnimationStatus status) { log.add('listener2'); } controller.addStatusListener(listener1); controller.addStatusListener(badListener); controller.addStatusListener(listener2); controller.forward(); expect(log, <String>['listener1', 'badListener', 'listener2']); expect(tester.takeException(), isArgumentError); log.clear(); controller.dispose(); }); }
flutter/packages/flutter/test/animation/iteration_patterns_test.dart/0
{ "file_path": "flutter/packages/flutter/test/animation/iteration_patterns_test.dart", "repo_id": "flutter", "token_count": 1453 }
701
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('debugCheckHasCupertinoLocalizations throws', (WidgetTester tester) async { final GlobalKey noLocalizationsAvailable = GlobalKey(); final GlobalKey localizationsAvailable = GlobalKey(); await tester.pumpWidget( Container( key: noLocalizationsAvailable, child: CupertinoApp( home: Container( key: localizationsAvailable, ), ), ), ); expect(() => debugCheckHasCupertinoLocalizations(noLocalizationsAvailable.currentContext!), throwsA(isAssertionError.having( (AssertionError e) => e.message, 'message', contains('No CupertinoLocalizations found'), ))); expect(debugCheckHasCupertinoLocalizations(localizationsAvailable.currentContext!), isTrue); }); }
flutter/packages/flutter/test/cupertino/debug_test.dart/0
{ "file_path": "flutter/packages/flutter/test/cupertino/debug_test.dart", "repo_id": "flutter", "token_count": 365 }
702
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../rendering/rendering_tester.dart'; class SpyFixedExtentScrollController extends FixedExtentScrollController { /// Override for test visibility only. @override bool get hasListeners => super.hasListeners; } void main() { testWidgets('Picker respects theme styling', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( height: 300.0, width: 300.0, child: CupertinoPicker( itemExtent: 50.0, onSelectedItemChanged: (_) { }, children: List<Widget>.generate(3, (int index) { return SizedBox( height: 50.0, width: 300.0, child: Text(index.toString()), ); }), ), ), ), ), ); final RenderParagraph paragraph = tester.renderObject(find.text('1')); expect(paragraph.text.style!.color, isSameColorAs(CupertinoColors.black)); expect(paragraph.text.style!.copyWith(color: CupertinoColors.black), const TextStyle( inherit: false, fontFamily: 'CupertinoSystemDisplay', fontSize: 21.0, fontWeight: FontWeight.w400, letterSpacing: -0.6, color: CupertinoColors.black, )); }); group('layout', () { // Regression test for https://github.com/flutter/flutter/issues/22999 testWidgets('CupertinoPicker.builder test', (WidgetTester tester) async { Widget buildFrame(int childCount) { return Directionality( textDirection: TextDirection.ltr, child: CupertinoPicker.builder( itemExtent: 50.0, onSelectedItemChanged: (_) { }, itemBuilder: (BuildContext context, int index) { return Text('$index'); }, childCount: childCount, ), ); } await tester.pumpWidget(buildFrame(1)); expect(tester.renderObject(find.text('0')).attached, true); await tester.pumpWidget(buildFrame(2)); expect(tester.renderObject(find.text('0')).attached, true); expect(tester.renderObject(find.text('1')).attached, true); }); testWidgets('selected item is in the middle', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 1); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Align( alignment: Alignment.topLeft, child: SizedBox( height: 300.0, width: 300.0, child: CupertinoPicker( scrollController: controller, itemExtent: 50.0, onSelectedItemChanged: (_) { }, children: List<Widget>.generate(3, (int index) { return SizedBox( height: 50.0, width: 300.0, child: Text(index.toString()), ); }), ), ), ), ), ); expect( tester.getTopLeft(find.widgetWithText(SizedBox, '1').first), const Offset(0.0, 125.0), ); controller.jumpToItem(0); await tester.pump(); expect( tester.getTopLeft(find.widgetWithText(SizedBox, '1').first), offsetMoreOrLessEquals(const Offset(0.0, 170.0), epsilon: 0.5), ); expect( tester.getTopLeft(find.widgetWithText(SizedBox, '0').first), const Offset(0.0, 125.0), ); }); }); testWidgets('picker dark mode', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.light), home: Align( alignment: Alignment.topLeft, child: SizedBox( height: 300.0, width: 300.0, child: CupertinoPicker( backgroundColor: const CupertinoDynamicColor.withBrightness( color: Color(0xFF123456), // Set alpha channel to FF to disable under magnifier painting. darkColor: Color(0xFF654321), ), itemExtent: 15.0, children: const <Widget>[Text('1'), Text('1')], onSelectedItemChanged: (int i) { }, ), ), ), ), ); expect(find.byType(CupertinoPicker), paints..rrect(color: const Color.fromARGB(30, 118, 118, 128))); expect(find.byType(CupertinoPicker), paints..rect(color: const Color(0xFF123456))); await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.dark), home: Align( alignment: Alignment.topLeft, child: SizedBox( height: 300.0, width: 300.0, child: CupertinoPicker( backgroundColor: const CupertinoDynamicColor.withBrightness( color: Color(0xFF123456), darkColor: Color(0xFF654321), ), itemExtent: 15.0, children: const <Widget>[Text('1'), Text('1')], onSelectedItemChanged: (int i) { }, ), ), ), ), ); expect(find.byType(CupertinoPicker), paints..rrect(color: const Color.fromARGB(61,118, 118, 128))); expect(find.byType(CupertinoPicker), paints..rect(color: const Color(0xFF654321))); }); testWidgets('picker selectionOverlay', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.light), home: Align( alignment: Alignment.topLeft, child: SizedBox( height: 300.0, width: 300.0, child: CupertinoPicker( itemExtent: 15.0, onSelectedItemChanged: (int i) {}, selectionOverlay: const CupertinoPickerDefaultSelectionOverlay(background: Color(0x12345678)), children: const <Widget>[Text('1'), Text('1')], ), ), ), ), ); expect(find.byType(CupertinoPicker), paints..rrect(color: const Color(0x12345678))); }); testWidgets('CupertinoPicker.selectionOverlay is nullable', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.light), home: Align( alignment: Alignment.topLeft, child: SizedBox( height: 300.0, width: 300.0, child: CupertinoPicker( itemExtent: 15.0, onSelectedItemChanged: (int i) {}, selectionOverlay: null, children: const <Widget>[Text('1'), Text('1')], ), ), ), ), ); expect(find.byType(CupertinoPicker), isNot(paints..rrect())); }); group('scroll', () { testWidgets( 'scrolling calls onSelectedItemChanged and triggers haptic feedback', (WidgetTester tester) async { final List<int> selectedItems = <int>[]; final List<MethodCall> systemCalls = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { systemCalls.add(methodCall); return null; }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CupertinoPicker( itemExtent: 100.0, onSelectedItemChanged: (int index) { selectedItems.add(index); }, children: List<Widget>.generate(100, (int index) { return Center( child: SizedBox( width: 400.0, height: 100.0, child: Text(index.toString()), ), ); }), ), ), ); await tester.drag(find.text('0'), const Offset(0.0, -100.0), warnIfMissed: false); // has an IgnorePointer expect(selectedItems, <int>[1]); expect( systemCalls.single, isMethodCall( 'HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick', ), ); await tester.drag(find.text('0'), const Offset(0.0, 100.0), warnIfMissed: false); // has an IgnorePointer expect(selectedItems, <int>[1, 0]); expect(systemCalls, hasLength(2)); expect( systemCalls.last, isMethodCall( 'HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick', ), ); }, variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); testWidgets( 'do not trigger haptic effects on non-iOS devices', (WidgetTester tester) async { final List<int> selectedItems = <int>[]; final List<MethodCall> systemCalls = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { systemCalls.add(methodCall); return null; }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CupertinoPicker( itemExtent: 100.0, onSelectedItemChanged: (int index) { selectedItems.add(index); }, children: List<Widget>.generate(100, (int index) { return Center( child: SizedBox( width: 400.0, height: 100.0, child: Text(index.toString()), ), ); }), ), ), ); await tester.drag(find.text('0'), const Offset(0.0, -100.0), warnIfMissed: false); // has an IgnorePointer expect(selectedItems, <int>[1]); expect(systemCalls, isEmpty); }, variant: TargetPlatformVariant(TargetPlatform.values.where((TargetPlatform platform) => platform != TargetPlatform.iOS).toSet()), ); testWidgets('a drag in between items settles back', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 10); addTearDown(controller.dispose); final List<int> selectedItems = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CupertinoPicker( scrollController: controller, itemExtent: 100.0, onSelectedItemChanged: (int index) { selectedItems.add(index); }, children: List<Widget>.generate(100, (int index) { return Center( child: SizedBox( width: 400.0, height: 100.0, child: Text(index.toString()), ), ); }), ), ), ); // Drag it by a bit but not enough to move to the next item. await tester.drag(find.text('10'), const Offset(0.0, 30.0), pointer: 1, touchSlopY: 0.0, warnIfMissed: false); // has an IgnorePointer // The item that was in the center now moved a bit. expect( tester.getTopLeft(find.widgetWithText(SizedBox, '10')), const Offset(200.0, 250.0), ); await tester.pumpAndSettle(); expect( tester.getTopLeft(find.widgetWithText(SizedBox, '10')).dy, moreOrLessEquals(250.0, epsilon: 0.5), ); expect(selectedItems.isEmpty, true); // Drag it by enough to move to the next item. await tester.drag(find.text('10'), const Offset(0.0, 70.0), pointer: 1, touchSlopY: 0.0, warnIfMissed: false); // has an IgnorePointer await tester.pumpAndSettle(); expect( tester.getTopLeft(find.widgetWithText(SizedBox, '10')).dy, // It's down by 100.0 now. moreOrLessEquals(340.0, epsilon: 0.5), ); expect(selectedItems, <int>[9]); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('a big fling that overscrolls springs back', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 10); addTearDown(controller.dispose); final List<int> selectedItems = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CupertinoPicker( scrollController: controller, itemExtent: 100.0, onSelectedItemChanged: (int index) { selectedItems.add(index); }, children: List<Widget>.generate(100, (int index) { return Center( child: SizedBox( width: 400.0, height: 100.0, child: Text(index.toString()), ), ); }), ), ), ); // A wild throw appears. await tester.fling( find.text('10'), const Offset(0.0, 10000.0), 1000.0, warnIfMissed: false, // has an IgnorePointer ); if (debugDefaultTargetPlatformOverride == TargetPlatform.iOS) { // Should have been flung far enough that even the first item goes off // screen and gets removed. expect(find.widgetWithText(SizedBox, '0').evaluate().isEmpty, true); } expect( selectedItems, // This specific throw was fast enough that each scroll update landed // on every second item. <int>[8, 6, 4, 2, 0], ); // Let it spring back. await tester.pumpAndSettle(); expect( tester.getTopLeft(find.widgetWithText(SizedBox, '0')).dy, // Should have sprung back to the middle now. moreOrLessEquals(250.0), ); expect( selectedItems, // Falling back to 0 shouldn't produce more callbacks. <int>[8, 6, 4, 2, 0], ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); }); testWidgets('Picker adapts to MaterialApp dark mode', (WidgetTester tester) async { Widget buildCupertinoPicker(Brightness brightness) { return MaterialApp( theme: ThemeData(brightness: brightness), home: Align( alignment: Alignment.topLeft, child: SizedBox( height: 300.0, width: 300.0, child: CupertinoPicker( itemExtent: 50.0, onSelectedItemChanged: (_) { }, children: List<Widget>.generate(3, (int index) { return SizedBox( height: 50.0, width: 300.0, child: Text(index.toString()), ); }), ), ), ), ); } // CupertinoPicker with light theme. await tester.pumpWidget(buildCupertinoPicker(Brightness.light)); RenderParagraph paragraph = tester.renderObject(find.text('1')); expect(paragraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(paragraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse); // CupertinoPicker with dark theme. await tester.pumpWidget(buildCupertinoPicker(Brightness.dark)); paragraph = tester.renderObject(find.text('1')); expect(paragraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(paragraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse); }); group('CupertinoPickerDefaultSelectionOverlay', () { testWidgets('should be using directional decoration', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.light), home: CupertinoPicker( itemExtent: 15.0, onSelectedItemChanged: (int i) {}, selectionOverlay: const CupertinoPickerDefaultSelectionOverlay(background: Color(0x12345678)), children: const <Widget>[Text('1'), Text('1')], ), ), ); final Finder selectionContainer = find.byType(Container); final Container container = tester.firstWidget<Container>(selectionContainer); final EdgeInsetsGeometry? margin = container.margin; final BorderRadiusGeometry? borderRadius = (container.decoration as BoxDecoration?)?.borderRadius; expect(margin, isA<EdgeInsetsDirectional>()); expect(borderRadius, isA<BorderRadiusDirectional>()); }); }); testWidgets('Scroll controller is detached upon dispose', (WidgetTester tester) async { final SpyFixedExtentScrollController controller = SpyFixedExtentScrollController(); addTearDown(controller.dispose); expect(controller.hasListeners, false); expect(controller.positions.length, 0); await tester.pumpWidget(CupertinoApp( home: Align( alignment: Alignment.topLeft, child: Center( child: CupertinoPicker( scrollController: controller, itemExtent: 50.0, onSelectedItemChanged: (_) { }, children: List<Widget>.generate(3, (int index) { return SizedBox( width: 300.0, child: Text(index.toString()), ); }), ), ), ), )); expect(controller.hasListeners, true); expect(controller.positions.length, 1); await tester.pumpWidget(const SizedBox.expand()); expect(controller.hasListeners, false); expect(controller.positions.length, 0); }); testWidgets( 'Registers taps and does not crash with certain diameterRatio', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/126491 final List<int> children = List<int>.generate(100, (int index) => index); final List<int> paintedChildren = <int>[]; final Set<int> tappedChildren = <int>{}; await tester.pumpWidget(CupertinoApp( home: Align( alignment: Alignment.topLeft, child: Center( child: SizedBox( height: 120, child: CupertinoPicker( itemExtent: 55, diameterRatio: 0.9, onSelectedItemChanged: (int index) {}, children: children .map<Widget>((int index) => GestureDetector( key: ValueKey<int>(index), onTap: () { tappedChildren.add(index); }, child: SizedBox( width: 55, height: 55, child: CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ), ), ), ) .toList(), ), ), ), ), )); // Children are painted two times for whatever reason expect(paintedChildren, <int>[0, 1, 0, 1]); // Expect hitting 0 and 1, which are painted await tester.tap(find.byKey(const ValueKey<int>(0))); expect(tappedChildren, const <int>[0]); await tester.tap(find.byKey(const ValueKey<int>(1))); expect(tappedChildren, const <int>[0, 1]); // The third child is not painted, so is not hit await tester.tap(find.byKey(const ValueKey<int>(2)), warnIfMissed: false); expect(tappedChildren, const <int>[0, 1]); }); }
flutter/packages/flutter/test/cupertino/picker_test.dart/0
{ "file_path": "flutter/packages/flutter/test/cupertino/picker_test.dart", "repo_id": "flutter", "token_count": 9577 }
703
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // reduced-test-set: // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle, Color; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart' show DragStartBehavior, PointerDeviceKind, kDoubleTapTimeout, kLongPressTimeout, kSecondaryMouseButton; 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' show OverflowWidgetTextEditingController, isContextMenuProvidedByPlatform; import '../widgets/live_text_utils.dart'; import '../widgets/semantics_tester.dart'; import '../widgets/text_selection_toolbar_utils.dart'; class MockTextSelectionControls extends TextSelectionControls { @override Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) { throw UnimplementedError(); } @override Widget buildToolbar( BuildContext context, Rect globalEditableRegion, double textLineHeight, Offset position, List<TextSelectionPoint> endpoints, TextSelectionDelegate delegate, ValueListenable<ClipboardStatus>? clipboardStatus, Offset? lastSecondaryTapDownPosition, ) { throw UnimplementedError(); } @override Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) { throw UnimplementedError(); } @override Size getHandleSize(double textLineHeight) { throw UnimplementedError(); } } class PathBoundsMatcher extends Matcher { const PathBoundsMatcher({ this.rectMatcher, this.topMatcher, this.leftMatcher, this.rightMatcher, this.bottomMatcher, }) : super(); final Matcher? rectMatcher; final Matcher? topMatcher; final Matcher? leftMatcher; final Matcher? rightMatcher; final Matcher? bottomMatcher; @override bool matches(covariant Path item, Map<dynamic, dynamic> matchState) { final Rect bounds = item.getBounds(); final List<Matcher?> matchers = <Matcher?> [rectMatcher, topMatcher, leftMatcher, rightMatcher, bottomMatcher]; final List<dynamic> values = <dynamic> [bounds, bounds.top, bounds.left, bounds.right, bounds.bottom]; final Map<Matcher, dynamic> failedMatcher = <Matcher, dynamic> {}; for (int idx = 0; idx < matchers.length; idx++) { if (!(matchers[idx]?.matches(values[idx], matchState) ?? true)) { failedMatcher[matchers[idx]!] = values[idx]; } } matchState['failedMatcher'] = failedMatcher; return failedMatcher.isEmpty; } @override Description describe(Description description) => description.add('The actual Rect does not match'); @override Description describeMismatch(covariant Path item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { final Description description = super.describeMismatch(item, mismatchDescription, matchState, verbose); final Map<Matcher, dynamic> map = matchState['failedMatcher'] as Map<Matcher, dynamic>; final Iterable<String> descriptions = map.entries .map<String>( (MapEntry<Matcher, dynamic> entry) => entry.key.describeMismatch(entry.value, StringDescription(), matchState, verbose).toString(), ); // description is guaranteed to be non-null. return description ..add('mismatch Rect: ${item.getBounds()}') .addAll(': ', ', ', '. ', descriptions); } } class PathPointsMatcher extends Matcher { const PathPointsMatcher({ this.includes = const <Offset>[], this.excludes = const <Offset>[], }) : super(); final Iterable<Offset> includes; final Iterable<Offset> excludes; @override bool matches(covariant Path item, Map<dynamic, dynamic> matchState) { final Offset? notIncluded = includes.cast<Offset?>().firstWhere((Offset? offset) => !item.contains(offset!), orElse: () => null); final Offset? notExcluded = excludes.cast<Offset?>().firstWhere((Offset? offset) => item.contains(offset!), orElse: () => null); matchState['notIncluded'] = notIncluded; matchState['notExcluded'] = notExcluded; return (notIncluded ?? notExcluded) == null; } @override Description describe(Description description) => description.add('must include these points $includes and must not include $excludes'); @override Description describeMismatch(covariant Path item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { final Offset? notIncluded = matchState['notIncluded'] as Offset?; final Offset? notExcluded = matchState['notExcluded'] as Offset?; final Description desc = super.describeMismatch(item, mismatchDescription, matchState, verbose); if ((notExcluded ?? notIncluded) != null) { desc.add('Within the bounds of the path ${item.getBounds()}: '); } if (notIncluded != null) { desc.add('$notIncluded is not included. '); } if (notExcluded != null) { desc.add('$notExcluded is not excluded. '); } return desc; } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); final MockClipboard mockClipboard = MockClipboard(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); // Returns the first RenderEditable. 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!; } List<TextSelectionPoint> globalize(Iterable<TextSelectionPoint> points, RenderBox box) { return points.map<TextSelectionPoint>((TextSelectionPoint point) { return TextSelectionPoint( box.localToGlobal(point.point), point.direction, ); }).toList(); } Offset textOffsetToBottomLeftPosition(WidgetTester tester, int offset) { final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection( TextSelection.collapsed(offset: offset), ), renderEditable, ); expect(endpoints.length, 1); return endpoints[0].point; } // Web has a less threshold for downstream/upstream text position. Offset textOffsetToPosition(WidgetTester tester, int offset) => textOffsetToBottomLeftPosition(tester, offset) + const Offset(kIsWeb ? 1 : 0, -2); setUp(() async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); EditableText.debugDeterministicCursor = false; // Fill the clipboard so that the Paste option is available in the text // selection menu. await Clipboard.setData(const ClipboardData(text: 'Clipboard data')); }); testWidgets( 'Live Text button shows and hides correctly when LiveTextStatus changes', (WidgetTester tester) async { final LiveTextInputTester liveTextInputTester = LiveTextInputTester(); addTearDown(liveTextInputTester.dispose); final TextEditingController controller = TextEditingController(text: ''); addTearDown(controller.dispose); const Key key = ValueKey<String>('TextField'); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final Widget app = MaterialApp( theme: ThemeData(platform: TargetPlatform.iOS), home: Scaffold( body: Center( child: CupertinoTextField( key: key, controller: controller, focusNode: focusNode, ), ), ), ); liveTextInputTester.mockLiveTextInputEnabled = true; await tester.pumpWidget(app); focusNode.requestFocus(); await tester.pumpAndSettle(); final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); await tester.pumpAndSettle(); expect( findLiveTextButton(), kIsWeb ? findsNothing : findsOneWidget, ); liveTextInputTester.mockLiveTextInputEnabled = false; await tester.longPress(textFinder); await tester.pumpAndSettle(); expect(findLiveTextButton(), findsNothing); }, ); testWidgets('Look Up shows up on iOS only', (WidgetTester tester) async { String? lastLookUp; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'LookUp.invoke') { expect(methodCall.arguments, isA<String>()); lastLookUp = methodCall.arguments as String; } return null; }); final TextEditingController controller = TextEditingController( text: 'Test', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final bool isTargetPlatformiOS = defaultTargetPlatform == TargetPlatform.iOS; // Long press to put the cursor after the "s". const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 4)); expect(find.text('Look Up'), isTargetPlatformiOS? findsOneWidget : findsNothing); if (isTargetPlatformiOS) { await tester.tap(find.text('Look Up')); expect(lastLookUp, 'Test'); } }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Search Web shows up on iOS only', (WidgetTester tester) async { String? lastSearch; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'SearchWeb.invoke') { expect(methodCall.arguments, isA<String>()); lastSearch = methodCall.arguments as String; } return null; }); final TextEditingController controller = TextEditingController( text: 'Test', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final bool isTargetPlatformiOS = defaultTargetPlatform == TargetPlatform.iOS; // Long press to put the cursor after the "s". const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 4)); expect(find.text('Search Web'), isTargetPlatformiOS? findsOneWidget : findsNothing); if (isTargetPlatformiOS) { await tester.tap(find.text('Search Web')); expect(lastSearch, 'Test'); } }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Share shows up on iOS and Android', (WidgetTester tester) async { String? lastShare; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'Share.invoke') { expect(methodCall.arguments, isA<String>()); lastShare = methodCall.arguments as String; } return null; }); final TextEditingController controller = TextEditingController( text: 'Test', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); // Long press to put the cursor after the "s". const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 4)); expect(find.text('Share...'), findsOneWidget); await tester.tap(find.text('Share...')); expect(lastShare, 'Test'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); 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( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(400, 200)), child: CupertinoTextField(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(baseOffset: 11, extentOffset: 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] the web handles this on its own. ); testWidgets('can get text selection color initially on desktop', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final TextEditingController controller = TextEditingController( text: 'blah1 blah2', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: RepaintBoundary( child: CupertinoTextField( key: const ValueKey<int>(1), controller: controller, focusNode: focusNode, ), ), ), ), ); controller.selection = const TextSelection(baseOffset: 0, extentOffset: 11); focusNode.requestFocus(); await tester.pump(); expect(focusNode.hasFocus, true); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('text_field_golden.text_selection_color.0.png'), ); }); testWidgets('Activates the text field when receives semantics focus on Mac, Windows', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoTextField(focusNode: focusNode), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 3, flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( id: 4, flags: <SemanticsFlag>[ SemanticsFlag.isTextField, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.didGainAccessibilityFocus,], textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, )); expect(focusNode.hasFocus, isFalse); semanticsOwner.performAction(4, SemanticsAction.didGainAccessibilityFocus); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); semantics.dispose(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.windows })); testWidgets( 'takes available space horizontally and takes intrinsic space vertically no-strut', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField(strutStyle: StrutStyle.disabled), ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)), const Size(200, 31), // 31 is the height of the default font + padding etc. ); }, ); testWidgets('sets cursorOpacityAnimates on EditableText correctly', (WidgetTester tester) async { // True await tester.pumpWidget( const CupertinoApp( home: CupertinoTextField(autofocus: true), ), ); await tester.pump(); EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.cursorOpacityAnimates, true); // False await tester.pumpWidget( const CupertinoApp( home: CupertinoTextField(autofocus: true, cursorOpacityAnimates: false), ), ); await tester.pump(); editableText = tester.widget(find.byType(EditableText)); expect(editableText.cursorOpacityAnimates, false); }); testWidgets( 'takes available space horizontally and takes intrinsic space vertically', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField(), ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)), const Size(200, 31), // 31 is the height of the default font (17) + decoration (12). ); }, ); testWidgets('selection handles color respects CupertinoTheme', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/74890. const Color expectedSelectionHandleColor = Color.fromARGB(255, 10, 200, 255); final TextEditingController controller = TextEditingController(text: 'Some text.'); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData( primaryColor: Colors.red, ), home: Center( child: CupertinoTheme( data: const CupertinoThemeData( primaryColor: expectedSelectionHandleColor, ), child: CupertinoTextField(controller: controller), ), ), ), ); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); final Iterable<RenderBox> boxes = tester.renderObjectList<RenderBox>( find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), matching: find.byType(CustomPaint), ), ); expect(boxes.length, 2); for (final RenderBox box in boxes) { expect(box, paints..path(color: expectedSelectionHandleColor)); } }, variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); testWidgets( 'uses DefaultSelectionStyle for selection and cursor colors if provided', (WidgetTester tester) async { const Color selectionColor = Colors.black; const Color cursorColor = Colors.white; await tester.pumpWidget( const CupertinoApp( home: Center( child: DefaultSelectionStyle( selectionColor: selectionColor, cursorColor: cursorColor, child: CupertinoTextField( autofocus: true, ) ), ), ), ); await tester.pump(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.widget.selectionColor, selectionColor); expect(state.widget.cursorColor, cursorColor); }, ); testWidgets('Text field drops selection color when losing focus', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/103341. final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); final TextEditingController controller1 = TextEditingController(); addTearDown(controller1.dispose); const Color selectionColor = Colors.orange; const Color cursorColor = Colors.red; await tester.pumpWidget( CupertinoApp( home: Center( child: DefaultSelectionStyle( selectionColor: selectionColor, cursorColor: cursorColor, child: Column( children: <Widget>[ CupertinoTextField( key: key1, controller: controller1, ), CupertinoTextField(key: key2), ], ), ), ), ), ); const TextSelection selection = TextSelection(baseOffset: 0, extentOffset: 4); final EditableTextState state1 = tester.state<EditableTextState>(find.byType(EditableText).first); final EditableTextState state2 = tester.state<EditableTextState>(find.byType(EditableText).last); await tester.tap(find.byKey(key1)); await tester.enterText(find.byKey(key1), 'abcd'); await tester.pump(); await tester.tap(find.byKey(key2)); await tester.enterText(find.byKey(key2), 'dcba'); await tester.pumpAndSettle(); // Focus and selection is active on first TextField, so the second TextFields // selectionColor should be dropped. await tester.tap(find.byKey(key1)); controller1.selection = const TextSelection(baseOffset: 0, extentOffset: 4); await tester.pump(); expect(controller1.selection, selection); expect(state1.widget.selectionColor, selectionColor); expect(state2.widget.selectionColor, null); // Focus and selection is active on second TextField, so the first TextField // selectionColor should be dropped. await tester.tap(find.byKey(key2)); await tester.pump(); expect(state1.widget.selectionColor, null); expect(state2.widget.selectionColor, selectionColor); }); testWidgets( 'multi-lined text fields are intrinsically taller no-strut', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField( maxLines: 3, strutStyle: StrutStyle.disabled, ), ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)), const Size(200, 65), // 65 is the height of the default font (17) * maxlines (3) + decoration height (12). ); }, ); testWidgets( 'multi-lined text fields are intrinsically taller', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField(maxLines: 3), ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)), const Size(200, 65), ); }, ); testWidgets( 'strut height override', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField( maxLines: 3, strutStyle: StrutStyle( fontSize: 8, forceStrutHeight: true, ), ), ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)), const Size(200, 38), ); }, // TODO(mdebbar): Strut styles support. skip: isBrowser, // https://github.com/flutter/flutter/issues/32243 ); testWidgets( 'strut forces field taller', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField( maxLines: 3, style: TextStyle(fontSize: 10), strutStyle: StrutStyle( fontSize: 18, forceStrutHeight: true, ), ), ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)), const Size(200, 68), ); }, // TODO(mdebbar): Strut styles support. skip: isBrowser, // https://github.com/flutter/flutter/issues/32243 ); testWidgets( 'default text field has a border', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField(), ), ), ); BoxDecoration decoration = tester.widget<DecoratedBox>( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(DecoratedBox), ), ).decoration as BoxDecoration; expect( decoration.borderRadius, const BorderRadius.all(Radius.circular(5)), ); expect( decoration.border!.bottom.color.value, 0x33000000, ); // Dark mode. await tester.pumpWidget( const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.dark), home: Center( child: CupertinoTextField(), ), ), ); decoration = tester.widget<DecoratedBox>( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(DecoratedBox), ), ).decoration as BoxDecoration; expect( decoration.borderRadius, const BorderRadius.all(Radius.circular(5)), ); expect( decoration.border!.bottom.color.value, 0x33FFFFFF, ); }, ); testWidgets( 'decoration can be overridden', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( decoration: null, ), ), ), ); expect( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(DecoratedBox), ), findsNothing, ); }, ); testWidgets( 'text entries are padded by default', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(text: 'initial'); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); expect( tester.getTopLeft(find.text('initial')) - tester.getTopLeft(find.byType(CupertinoTextField)), const Offset(7.0, 7.0), ); }, ); testWidgets('iOS cursor has offset', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: CupertinoTextField(), ), ); final EditableText editableText = tester.firstWidget(find.byType(EditableText)); expect(editableText.cursorOffset, const Offset(-2.0 / 3.0, 0)); }); testWidgets('Cursor radius is 2.0', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: CupertinoTextField(), ), ); final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); final RenderEditable renderEditable = editableTextState.renderEditable; expect(renderEditable.cursorRadius, const Radius.circular(2.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Cupertino cursor android golden', (WidgetTester tester) async { final Widget widget = CupertinoApp( home: Center( child: RepaintBoundary( key: const ValueKey<int>(1), child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(400, 400)), child: const CupertinoTextField(), ), ), ), ); await tester.pumpWidget(widget); const String testValue = 'A short phrase'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pump(); await tester.tapAt(textOffsetToPosition(tester, testValue.length)); await tester.pumpAndSettle(); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('text_field_cursor_test.cupertino.0.png'), ); }); testWidgets('Cupertino cursor golden', (WidgetTester tester) async { final Widget widget = CupertinoApp( home: Center( child: RepaintBoundary( key: const ValueKey<int>(1), child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(400, 400)), child: const CupertinoTextField(), ), ), ), ); await tester.pumpWidget(widget); const String testValue = 'A short phrase'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pump(); await tester.tapAt(textOffsetToPosition(tester, testValue.length)); await tester.pumpAndSettle(); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile( 'text_field_cursor_test.cupertino_${debugDefaultTargetPlatformOverride!.name.toLowerCase()}.1.png', ), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets( 'can control text content via controller', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); controller.text = 'controller text'; await tester.pump(); expect(find.text('controller text'), findsOneWidget); controller.text = ''; await tester.pump(); expect(find.text('controller text'), findsNothing); }, ); testWidgets( 'placeholder respects textAlign', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( placeholder: 'placeholder', textAlign: TextAlign.right, ), ), ), ); final Text placeholder = tester.widget(find.text('placeholder')); expect(placeholder.textAlign, TextAlign.right); await tester.enterText(find.byType(CupertinoTextField), 'input'); await tester.pump(); final EditableText inputText = tester.widget(find.text('input')); expect(placeholder.textAlign, inputText.textAlign); }, ); testWidgets('placeholder dark mode', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.dark), home: Center( child: CupertinoTextField( placeholder: 'placeholder', textAlign: TextAlign.right, ), ), ), ); final Text placeholder = tester.widget(find.text('placeholder')); expect(placeholder.style!.color!.value, CupertinoColors.placeholderText.darkColor.value); }); testWidgets( 'placeholders are lightly colored and disappears once typing starts', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( placeholder: 'placeholder', ), ), ), ); final Text placeholder = tester.widget(find.text('placeholder')); expect(placeholder.style!.color!.value, CupertinoColors.placeholderText.color.value); await tester.enterText(find.byType(CupertinoTextField), 'input'); await tester.pump(); final Element element = tester.element(find.text('placeholder')); expect(Visibility.of(element), false); }, ); testWidgets( "placeholderStyle modifies placeholder's style and doesn't affect text's style", (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( placeholder: 'placeholder', style: TextStyle( color: Color(0x00FFFFFF), fontWeight: FontWeight.w300, ), placeholderStyle: TextStyle( color: Color(0xAAFFFFFF), fontWeight: FontWeight.w600, ), ), ), ), ); final Text placeholder = tester.widget(find.text('placeholder')); expect(placeholder.style!.color, const Color(0xAAFFFFFF)); expect(placeholder.style!.fontWeight, FontWeight.w600); await tester.enterText(find.byType(CupertinoTextField), 'input'); await tester.pump(); final EditableText inputText = tester.widget(find.text('input')); expect(inputText.style.color, const Color(0x00FFFFFF)); expect(inputText.style.fontWeight, FontWeight.w300); }, ); testWidgets( 'prefix widget is in front of the text', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final TextEditingController controller = TextEditingController(text: 'input'); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( focusNode: focusNode, prefix: const Icon(CupertinoIcons.add), controller: controller, ), ), ), ); expect( tester.getTopRight(find.byIcon(CupertinoIcons.add)).dx + 7.0, // 7px standard padding around input. tester.getTopLeft(find.byType(EditableText)).dx, ); expect( tester.getTopLeft(find.byType(EditableText)).dx, tester.getTopLeft(find.byType(CupertinoTextField)).dx + tester.getSize(find.byIcon(CupertinoIcons.add)).width + 7.0, ); }, ); testWidgets( 'prefix widget respects visibility mode', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( prefix: Icon(CupertinoIcons.add), prefixMode: OverlayVisibilityMode.editing, ), ), ), ); expect(find.byIcon(CupertinoIcons.add), findsNothing); // The position should just be the edge of the whole text field plus padding. expect( tester.getTopLeft(find.byType(EditableText)).dx, tester.getTopLeft(find.byType(CupertinoTextField)).dx + 7.0, ); await tester.enterText(find.byType(CupertinoTextField), 'text input'); await tester.pump(); expect(find.text('text input'), findsOneWidget); expect(find.byIcon(CupertinoIcons.add), findsOneWidget); // Text is now moved to the right. expect( tester.getTopLeft(find.byType(EditableText)).dx, tester.getTopLeft(find.byType(CupertinoTextField)).dx + tester.getSize(find.byIcon(CupertinoIcons.add)).width + 7.0, ); }, ); testWidgets( 'suffix widget is after the text', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( focusNode: focusNode, suffix: const Icon(CupertinoIcons.add), ), ), ), ); expect( tester.getTopRight(find.byType(EditableText)).dx + 7.0, tester.getTopLeft(find.byIcon(CupertinoIcons.add)).dx, // 7px standard padding around input. ); expect( tester.getTopRight(find.byType(EditableText)).dx, tester.getTopRight(find.byType(CupertinoTextField)).dx - tester.getSize(find.byIcon(CupertinoIcons.add)).width - 7.0, ); }, ); testWidgets( 'suffix widget respects visibility mode', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( suffix: Icon(CupertinoIcons.add), suffixMode: OverlayVisibilityMode.notEditing, ), ), ), ); expect(find.byIcon(CupertinoIcons.add), findsOneWidget); await tester.enterText(find.byType(CupertinoTextField), 'text input'); await tester.pump(); expect(find.text('text input'), findsOneWidget); expect(find.byIcon(CupertinoIcons.add), findsNothing); }, ); testWidgets( 'can customize padding', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( padding: EdgeInsets.zero, ), ), ), ); expect( tester.getSize(find.byType(EditableText)), tester.getSize(find.byType(CupertinoTextField)), ); }, ); testWidgets( 'padding is in between prefix and suffix no-strut', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( padding: EdgeInsets.all(20.0), prefix: SizedBox(height: 100.0, width: 100.0), suffix: SizedBox(height: 50.0, width: 50.0), strutStyle: StrutStyle.disabled, ), ), ), ); expect( tester.getTopLeft(find.byType(EditableText)).dx, // Size of prefix + padding. 100.0 + 20.0, ); expect(tester.getTopLeft(find.byType(EditableText)).dy, 291.5); expect( tester.getTopRight(find.byType(EditableText)).dx, 800.0 - 50.0 - 20.0, ); await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( padding: EdgeInsets.all(30.0), prefix: SizedBox(height: 100.0, width: 100.0), suffix: SizedBox(height: 50.0, width: 50.0), strutStyle: StrutStyle.disabled, ), ), ), ); expect( tester.getTopLeft(find.byType(EditableText)).dx, 100.0 + 30.0, ); // Since the highest component, the prefix box, is higher than // the text + paddings, the text's vertical position isn't affected. expect(tester.getTopLeft(find.byType(EditableText)).dy, 291.5); expect( tester.getTopRight(find.byType(EditableText)).dx, 800.0 - 50.0 - 30.0, ); }, ); testWidgets( 'padding is in between prefix and suffix', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( padding: EdgeInsets.all(20.0), prefix: SizedBox(height: 100.0, width: 100.0), suffix: SizedBox(height: 50.0, width: 50.0), ), ), ), ); expect( tester.getTopLeft(find.byType(EditableText)).dx, // Size of prefix + padding. 100.0 + 20.0, ); expect(tester.getTopLeft(find.byType(EditableText)).dy, 291.5); expect( tester.getTopRight(find.byType(EditableText)).dx, 800.0 - 50.0 - 20.0, ); await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( padding: EdgeInsets.all(30.0), prefix: SizedBox(height: 100.0, width: 100.0), suffix: SizedBox(height: 50.0, width: 50.0), ), ), ), ); expect( tester.getTopLeft(find.byType(EditableText)).dx, 100.0 + 30.0, ); // Since the highest component, the prefix box, is higher than // the text + paddings, the text's vertical position isn't affected. expect(tester.getTopLeft(find.byType(EditableText)).dy, 291.5); expect( tester.getTopRight(find.byType(EditableText)).dx, 800.0 - 50.0 - 30.0, ); }, ); testWidgets( 'clear button shows with right visibility mode', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, placeholder: 'placeholder does not affect clear button', clearButtonMode: OverlayVisibilityMode.always, ), ), ), ); expect(find.byIcon(CupertinoIcons.clear_thick_circled), findsOneWidget); expect( tester.getTopRight(find.byType(EditableText)).dx, 800.0 - 30.0 /* size of button */ - 7.0 /* padding */, ); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, placeholder: 'placeholder does not affect clear button', clearButtonMode: OverlayVisibilityMode.editing, ), ), ), ); expect(find.byIcon(CupertinoIcons.clear_thick_circled), findsNothing); expect( tester.getTopRight(find.byType(EditableText)).dx, 800.0 - 7.0 /* padding */, ); await tester.enterText(find.byType(CupertinoTextField), 'text input'); await tester.pump(); expect(find.byIcon(CupertinoIcons.clear_thick_circled), findsOneWidget); expect(find.text('text input'), findsOneWidget); expect( tester.getTopRight(find.byType(EditableText)).dx, 800.0 - 30.0 - 7.0, ); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, placeholder: 'placeholder does not affect clear button', clearButtonMode: OverlayVisibilityMode.notEditing, ), ), ), ); expect(find.byIcon(CupertinoIcons.clear_thick_circled), findsNothing); controller.text = ''; await tester.pump(); expect(find.byIcon(CupertinoIcons.clear_thick_circled), findsOneWidget); }, ); testWidgets( 'clear button removes text', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, placeholder: 'placeholder', clearButtonMode: OverlayVisibilityMode.editing, ), ), ), ); controller.text = 'text entry'; await tester.pump(); await tester.tap(find.byIcon(CupertinoIcons.clear_thick_circled)); await tester.pump(); expect(controller.text, ''); expect(find.text('placeholder'), findsOneWidget); expect(find.text('text entry'), findsNothing); expect(find.byIcon(CupertinoIcons.clear_thick_circled), findsNothing); }, ); testWidgets( 'tapping clear button also calls onChanged when text not empty', (WidgetTester tester) async { String value = 'text entry'; final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, placeholder: 'placeholder', onChanged: (String newValue) => value = newValue, clearButtonMode: OverlayVisibilityMode.always, ), ), ), ); controller.text = value; await tester.pump(); await tester.tap(find.byIcon(CupertinoIcons.clear_thick_circled)); await tester.pump(); expect(controller.text, isEmpty); expect(find.text('text entry'), findsNothing); expect(value, isEmpty); }, ); testWidgets( 'clear button yields precedence to suffix', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, clearButtonMode: OverlayVisibilityMode.always, suffix: const Icon(CupertinoIcons.add_circled_solid), suffixMode: OverlayVisibilityMode.editing, ), ), ), ); expect(find.byIcon(CupertinoIcons.clear_thick_circled), findsOneWidget); expect(find.byIcon(CupertinoIcons.add_circled_solid), findsNothing); expect( tester.getTopRight(find.byType(EditableText)).dx, 800.0 - 30.0 /* size of button */ - 7.0 /* padding */, ); controller.text = 'non empty text'; await tester.pump(); expect(find.byIcon(CupertinoIcons.clear_thick_circled), findsNothing); expect(find.byIcon(CupertinoIcons.add_circled_solid), findsOneWidget); // Still just takes the space of one widget. expect( tester.getTopRight(find.byType(EditableText)).dx, 800.0 - 24.0 /* size of button */ - 7.0 /* padding */, ); }, ); testWidgets( 'font style controls intrinsic height no-strut', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( strutStyle: StrutStyle.disabled, ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)).height, 31.0, ); await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( style: TextStyle( // A larger font. fontSize: 50.0, ), strutStyle: StrutStyle.disabled, ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)).height, 64.0, ); }, ); testWidgets( 'font style controls intrinsic height', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField(), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)).height, 31.0, ); await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( style: TextStyle( // A larger font. fontSize: 50.0, ), ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)).height, 64.0, ); }, ); testWidgets( 'RTL puts attachments to the right places', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Directionality( textDirection: TextDirection.rtl, child: Center( child: CupertinoTextField( padding: EdgeInsets.all(20.0), prefix: Icon(CupertinoIcons.book), clearButtonMode: OverlayVisibilityMode.always, ), ), ), ), ); expect( tester.getTopLeft(find.byIcon(CupertinoIcons.book)).dx, 800.0 - 24.0, ); expect( tester.getTopRight(find.byIcon(CupertinoIcons.clear_thick_circled)).dx, 24.0, ); }, ); testWidgets( 'text fields with no max lines can grow no-strut', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( maxLines: null, strutStyle: StrutStyle.disabled, ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)).height, 31.0, // Initially one line high. ); await tester.enterText(find.byType(CupertinoTextField), '\n'); await tester.pump(); expect( tester.getSize(find.byType(CupertinoTextField)).height, 48.0, // Initially one line high. ); }, ); testWidgets( 'text fields with no max lines can grow', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( maxLines: null, ), ), ), ); expect( tester.getSize(find.byType(CupertinoTextField)).height, 31.0, // Initially one line high. ); await tester.enterText(find.byType(CupertinoTextField), '\n'); await tester.pump(); expect( tester.getSize(find.byType(CupertinoTextField)).height, 48.0, // Initially one line high. ); }, ); testWidgets('cannot enter new lines onto single line TextField', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), 'abc\ndef'); expect(controller.text, 'abcdef'); }); testWidgets('toolbar colors change with theme brightness, but nothing else', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: "j'aime la poutine", ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Column( children: <Widget>[ CupertinoTextField( controller: controller, ), ], ), ), ); await tester.longPressAt( tester.getTopRight(find.text("j'aime la poutine")), ); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 200)); Text text = tester.widget<Text>(find.text('Paste')); expect(text.style!.color!.value, CupertinoColors.black.value); expect(text.style!.fontSize, 15); expect(text.style!.letterSpacing, -0.15); expect(text.style!.fontWeight, FontWeight.w400); // Change the theme. await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData( brightness: Brightness.dark, textTheme: CupertinoTextThemeData( textStyle: TextStyle(fontSize: 100, fontWeight: FontWeight.w800), ), ), home: Column( children: <Widget>[ CupertinoTextField( controller: controller, ), ], ), ), ); await tester.longPressAt( tester.getTopRight(find.text("j'aime la poutine")), ); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 200)); text = tester.widget<Text>(find.text('Paste')); // The toolbar buttons' text are still the same style. expect(text.style!.color!.value, CupertinoColors.white.value); expect(text.style!.fontSize, 15); expect(text.style!.letterSpacing, -0.15); expect(text.style!.fontWeight, FontWeight.w400); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('text field toolbar options correctly changes options on Apple Platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Column( children: <Widget>[ CupertinoTextField( autofocus: true, controller: controller, toolbarOptions: const ToolbarOptions(copy: true), ), ], ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); // Long press to put the cursor after the "w". const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: index), ); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); // Selected text shows 'Copy'. expect(find.text('Paste'), findsNothing); expect(find.text('Copy'), findsOneWidget); expect(find.text('Cut'), findsNothing); expect(find.text('Select All'), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('text field toolbar options correctly changes options on non-Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Column( children: <Widget>[ CupertinoTextField( controller: controller, toolbarOptions: const ToolbarOptions(copy: true), ), ], ), ), ); // Long press to select 'Atwater' const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); // Tap elsewhere to hide the context menu so that subsequent taps don't // collide with it. await tester.tapAt(textOffsetToPosition(tester, controller.text.length)); await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 35, affinity: TextAffinity.upstream), ); // Double tap on the same location to select the word around the cursor. await tester.tapAt(textOffsetToPosition(tester, 10)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 10)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // Selected text shows 'Copy'. expect(find.text('Paste'), findsNothing); expect(find.text('Copy'), findsOneWidget); expect(find.text('Cut'), findsNothing); expect(find.text('Select All'), findsNothing); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('Read only text field', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(text: 'readonly'); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Column( children: <Widget>[ CupertinoTextField( controller: controller, readOnly: true, ), ], ), ), ); // Read only text field cannot open keyboard. await tester.showKeyboard(find.byType(CupertinoTextField)); expect(tester.testTextInput.hasAnyClients, false); await tester.longPressAt( tester.getTopRight(find.text('readonly')), ); await tester.pumpAndSettle(); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); expect(find.text('Select All'), findsOneWidget); await tester.tap(find.text('Select All')); await tester.pump(); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets('copy paste', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Column( children: <Widget>[ CupertinoTextField( placeholder: 'field 1', ), CupertinoTextField( placeholder: 'field 2', ), ], ), ), ); await tester.enterText( find.widgetWithText(CupertinoTextField, 'field 1'), "j'aime la poutine", ); await tester.pump(); // Tap an area inside the EditableText but with no text. await tester.longPressAt( tester.getTopRight(find.text("j'aime la poutine")), ); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 200)); await tester.tap(find.text('Select All')); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); await tester.tap(find.text('Cut')); await tester.pump(); // Placeholder 1 is back since the text is cut. expect(find.text('field 1'), findsOneWidget); expect(find.text('field 2'), findsOneWidget); await tester.longPress(find.text('field 2'), warnIfMissed: false); // can't actually hit placeholder await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); await tester.tap(find.text('Paste')); await tester.pump(); expect(find.text('field 1'), findsOneWidget); expect(find.text("j'aime la poutine"), findsOneWidget); final Element placeholder2Element = tester.element(find.text('field 2')); expect(Visibility.of(placeholder2Element), false); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets( 'tap moves cursor to the edge of the word it tapped on', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.tapAt(textFieldStart + const Offset(50.0, 5.0)); await tester.pump(); // We moved the cursor. expect( controller.selection, const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), ); // But don't trigger the toolbar. expect(find.byType(CupertinoButton), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); testWidgets( 'slow double tap does not trigger double tap', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset pos = textOffsetToPosition(tester, 6); // Index of 'Atwate|r'. await tester.tapAt(pos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(pos); await tester.pump(); // Plain collapsed selection. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformIOS ? 7 : 6); // Toolbar shows on mobile. if (isTargetPlatformIOS) { expectCupertinoToolbarForCollapsedSelection(); } else { // After a tap, macOS does not show a selection toolbar for a collapsed selection. expectNoCupertinoToolbar(); } }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets( 'Tapping on a collapsed selection toggles the toolbar', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neigse Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); addTearDown(controller.dispose); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, maxLines: 2, ), ), ), ); final double lineHeight = findRenderEditable(tester).preferredLineHeight; final Offset begPos = textOffsetToPosition(tester, 0); final Offset endPos = textOffsetToPosition(tester, 35) + const Offset(200.0, 0.0); // Index of 'Bonaventure|' + Offset(200.0,0), which is at the end of the first line. final Offset vPos = textOffsetToPosition(tester, 29); // Index of 'Bonav|enture'. final Offset wPos = textOffsetToPosition(tester, 3); // Index of 'Atw|ater'. // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(wPos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(vPos); await tester.pump(const Duration(milliseconds: 500)); // First tap moved the cursor. Here we tap the position where 'v' is located. // On iOS this will select the closest word edge, in this case the cursor is placed // at the end of the word 'Bonaventure|'. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 35); expect(find.byType(CupertinoButton), findsNothing); await tester.tapAt(vPos); await tester.pumpAndSettle(const Duration(milliseconds: 500)); // Second tap toggles the toolbar. Here we tap on 'v' again, and select the word edge. Since // the selection has not changed we toggle the toolbar. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 35); expectCupertinoToolbarForCollapsedSelection(); // Tap the 'v' position again to hide the toolbar. await tester.tapAt(vPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 35); expect(find.byType(CupertinoButton), findsNothing); // Long press at the end of the first line to move the cursor to the end of the first line // where the word wrap is. Since there is a word wrap here, and the direction of the text is LTR, // the TextAffinity will be upstream and against the natural direction. The toolbar is also // shown after a long press. await tester.longPressAt(endPos); await tester.pumpAndSettle(const Duration(milliseconds: 500)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 46); expect(controller.selection.affinity, TextAffinity.upstream); expectCupertinoToolbarForCollapsedSelection(); // Tap at the same position to toggle the toolbar. await tester.tapAt(endPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 46); expect(controller.selection.affinity, TextAffinity.upstream); expectNoCupertinoToolbar(); // Tap at the beginning of the second line to move the cursor to the front of the first word on the // second line, where the word wrap is. Since there is a word wrap here, and the direction of the text is LTR, // the TextAffinity will be downstream and following the natural direction. The toolbar will be hidden after this tap. await tester.tapAt(begPos + Offset(0.0, lineHeight)); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 46); expect(controller.selection.affinity, TextAffinity.downstream); expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'Tapping on a non-collapsed selection toggles the toolbar and retains the selection', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset vPos = textOffsetToPosition(tester, 29); // Index of 'Bonav|enture'. final Offset ePos = textOffsetToPosition(tester, 35) + const Offset(7.0, 0.0); // Index of 'Bonaventure|' + Offset(7.0,0), which taps slightly to the right of the end of the text. final Offset wPos = textOffsetToPosition(tester, 3); // Index of 'Atw|ater'. // This tap just puts the cursor somewhere different than where the double // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(wPos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(vPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect(controller.selection.isCollapsed, true); expect( controller.selection.baseOffset, 35, ); await tester.tapAt(vPos); await tester.pumpAndSettle(const Duration(milliseconds: 500)); // Second tap selects the word around the cursor. expect( controller.selection, const TextSelection(baseOffset: 24, extentOffset: 35), ); expectCupertinoToolbarForPartialSelection(); // Tap the selected word to hide the toolbar and retain the selection. await tester.tapAt(vPos); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 24, extentOffset: 35), ); expect(find.byType(CupertinoButton), findsNothing); // Tap the selected word to show the toolbar and retain the selection. await tester.tapAt(vPos); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 24, extentOffset: 35), ); expectCupertinoToolbarForPartialSelection(); // Tap past the selected word to move the cursor and hide the toolbar. await tester.tapAt(ePos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 35); expect(find.byType(CupertinoButton), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'double tap selects word for non-Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); // Long press to select 'Atwater'. const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); // Tap elsewhere to hide the context menu so that subsequent taps don't // collide with it. await tester.tapAt(textOffsetToPosition(tester, controller.text.length)); await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 35, affinity: TextAffinity.upstream), ); // Double tap in the middle of 'Peel' to select the word. await tester.tapAt(textOffsetToPosition(tester, 10)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 10)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); // The toolbar now shows up. expectCupertinoToolbarForPartialSelection(); // Tap somewhere else to move the cursor. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect(controller.selection, const TextSelection.collapsed(offset: index)); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS}), ); testWidgets( 'double tap selects word for Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( autofocus: true, controller: controller, ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); // Long press to put the cursor after the "w". const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: index), ); // Double tap to select the word around the cursor. Move slightly left of // the previous tap in order to avoid hitting the text selection toolbar // on Mac. await tester.tapAt(textOffsetToPosition(tester, index) - const Offset(1.0, 0.0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'double tap does not select word on read-only obscured field', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( readOnly: true, obscureText: true, controller: controller, ), ), ), ); // Long press to put the cursor after the "w". const int index = 3; await tester.longPressAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); // Second tap doesn't select anything. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 35), ); // Selected text shows nothing. expect(find.byType(CupertinoButton), findsNothing); }, ); testWidgets( 'Can double click + drag with a mouse to select word by word', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(const Duration(milliseconds: 200)); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset hPos = textOffsetToPosition(tester, testValue.indexOf('h')); // Tap on text field to gain focus, and set selection to '|e'. final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('e')); // Here we tap on '|e' again, to register a double tap. This will select // the word at the tapped position. await gesture.down(ePos); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 7); // Drag, right after the double tap, to select word by word. // Moving to the position of 'h', will extend the selection to 'ghi'. await gesture.moveTo(hPos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, testValue.indexOf('d')); expect(controller.selection.extentOffset, testValue.indexOf('i') + 1); }, ); testWidgets( 'Can double tap + drag to select word by word', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(const Duration(milliseconds: 200)); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset hPos = textOffsetToPosition(tester, testValue.indexOf('h')); // Tap on text field to gain focus, and set selection to '|e'. final TestGesture gesture = await tester.startGesture(ePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('e')); // Here we tap on '|e' again, to register a double tap. This will select // the word at the tapped position. await gesture.down(ePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 7); // Drag, right after the double tap, to select word by word. // Moving to the position of 'h', will extend the selection to 'ghi'. await gesture.moveTo(hPos); await tester.pumpAndSettle(); // Toolbar should be hidden during a drag. expect(find.byType(CupertinoButton), findsNothing); expect(controller.selection.baseOffset, testValue.indexOf('d')); expect(controller.selection.extentOffset, testValue.indexOf('i') + 1); // Toolbar should re-appear after a drag. await gesture.up(); await tester.pump(); expectCupertinoToolbarForPartialSelection(); // Skip the magnifier hide animation, so it can release resources. await tester.pump(const Duration(milliseconds: 150)); }, ); testWidgets('Readonly text field does not have tap action', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( maxLength: 10, readOnly: true, ), ), ), ); expect(semantics, isNot(includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap]))); semantics.dispose(); }); testWidgets( 'double tap selects word and first tap of double tap moves cursor', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset ePos = textOffsetToPosition(tester, 6); // Index of 'Atwate|r'. final Offset pPos = textOffsetToPosition(tester, 9); // Index of 'P|eel'. await tester.tapAt(ePos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformIOS ? 12 : 9); await tester.tapAt(pPos); await tester.pumpAndSettle(); // Second tap selects the word around the cursor. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets( 'double tap hold selects word', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.tapAt(textFieldStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final TestGesture gesture = await tester.startGesture(textFieldStart + const Offset(150.0, 5.0)); // Hold the press. await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoToolbarForPartialSelection(); await gesture.up(); await tester.pump(); // Still selected. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoToolbarForPartialSelection(); }, variant: TargetPlatformVariant.all()); testWidgets( 'tap after a double tap select is not affected', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset pPos = textOffsetToPosition(tester, 9); // Index of 'P|eel'. final Offset ePos = textOffsetToPosition(tester, 6); // Index of 'Atwate|r' await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformIOS ? 12 : 9); await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(ePos); await tester.pump(); // Plain collapsed selection at the edge of first word. In iOS 12, the // first tap after a double tap ends up putting the cursor at where // you tapped instead of the edge like every other single tap. This is // likely a bug in iOS 12 and not present in other versions. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformIOS ? 7 : 6); // No toolbar. expect(find.byType(CupertinoButton), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('double tapping a space selects the previous word on iOS', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: ' blah blah \n blah', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, maxLines: 2, ), ), ), ); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, -1); expect(controller.value.selection.extentOffset, -1); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 19)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 19); expect(controller.value.selection.extentOffset, 19); // Double tapping the second space selects the previous word. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 1); expect(controller.value.selection.extentOffset, 5); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 19)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 19); expect(controller.value.selection.extentOffset, 19); // Double tapping the first space selects the space. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 0); expect(controller.value.selection.extentOffset, 1); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 19)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 19); expect(controller.value.selection.extentOffset, 19); // Double tapping the last space selects all previous contiguous spaces on // both lines and the previous word. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 14)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 14)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 6); expect(controller.value.selection.extentOffset, 14); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); testWidgets('double tapping a space selects the space on Mac', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: ' blah blah', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, -1); expect(controller.value.selection.extentOffset, -1); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, 10)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 10); expect(controller.value.selection.extentOffset, 10); // Double tapping the second space selects it. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 5); expect(controller.value.selection.extentOffset, 6); // Tap at the end of the text to move the selection to the end. On some // platforms, the context menu "Cut" button blocks this tap, so move it out // of the way by an Offset. await tester.tapAt(textOffsetToPosition(tester, 10) + const Offset(200.0, 0.0)); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 10); expect(controller.value.selection.extentOffset, 10); // Double tapping the first space selects it. await tester.pump(const Duration(milliseconds: 500)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 0); expect(controller.value.selection.extentOffset, 1); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS })); testWidgets('double clicking a space selects the space on Mac', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: ' blah blah', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, -1); expect(controller.value.selection.extentOffset, -1); // Put the cursor at the end of the field. final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 10), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 10); expect(controller.value.selection.extentOffset, 10); // Double tapping the second space selects it. await tester.pump(const Duration(milliseconds: 500)); await gesture.down(textOffsetToPosition(tester, 5)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); await gesture.down(textOffsetToPosition(tester, 5)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 5); expect(controller.value.selection.extentOffset, 6); // Put the cursor at the end of the field. await gesture.down(textOffsetToPosition(tester, 10)); await tester.pump(); await gesture.up(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 10); expect(controller.value.selection.extentOffset, 10); // Double tapping the first space selects it. await tester.pump(const Duration(milliseconds: 500)); await gesture.down(textOffsetToPosition(tester, 0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); await gesture.down(textOffsetToPosition(tester, 0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.value.selection, isNotNull); expect(controller.value.selection.baseOffset, 0); expect(controller.value.selection.extentOffset, 1); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS })); testWidgets( 'An obscured CupertinoTextField is not selectable when disabled', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, obscureText: true, enableInteractiveSelection: false, ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.tapAt(textFieldStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final TestGesture gesture = await tester.startGesture(textFieldStart + const Offset(150.0, 5.0)); // Hold the press. await tester.pump(const Duration(milliseconds: 500)); // Nothing is selected despite the double tap long press gesture. expect( controller.selection, const TextSelection(baseOffset: 35, extentOffset: 35), ); // The selection menu is not present. expectNoCupertinoToolbar(); await gesture.up(); await tester.pump(); // Still nothing selected and no selection menu. expect( controller.selection, const TextSelection(baseOffset: 35, extentOffset: 35), ); expectNoCupertinoToolbar(); }, ); testWidgets( 'A read-only obscured CupertinoTextField is not selectable', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, obscureText: true, readOnly: true, ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.tapAt(textFieldStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final TestGesture gesture = await tester.startGesture(textFieldStart + const Offset(150.0, 5.0)); // Hold the press. await tester.pump(const Duration(milliseconds: 500)); // Nothing is selected despite the double tap long press gesture. expect( controller.selection, const TextSelection(baseOffset: 35, extentOffset: 35), ); // The selection menu is not present. expectNoCupertinoToolbar(); await gesture.up(); await tester.pump(); // Still nothing selected and no selection menu. expect( controller.selection, const TextSelection.collapsed(offset: 35), ); expectNoCupertinoToolbar(); }, ); testWidgets( 'An obscured CupertinoTextField is selectable by default', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, obscureText: true, ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.tapAt(textFieldStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); final TestGesture gesture = await tester.startGesture(textFieldStart + const Offset(150.0, 5.0)); // Hold the press. await tester.pumpAndSettle(); // The obscured text is treated as one word, should select all expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 35), ); // Selected text shows paste toolbar button. expect(find.byType(CupertinoButton), isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(1)); await gesture.up(); await tester.pump(); // Still selected. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 35), ); expect(find.byType(CupertinoButton), isContextMenuProvidedByPlatform ? findsNothing : findsNWidgets(1)); }, ); testWidgets('An obscured TextField has correct default context menu', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, obscureText: true, ), ), ), ); final Offset textFieldStart = tester.getCenter(find.byType(CupertinoTextField)); await tester.tapAt(textFieldStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); await tester.longPressAt(textFieldStart + const Offset(150.0, 5.0)); await tester.pumpAndSettle(); // Should only have paste option when whole obscure text is selected. expect(find.text('Paste'), findsOneWidget); expect(find.text('Copy'), findsNothing); expect(find.text('Cut'), findsNothing); expect(find.text('Select All'), findsNothing); // Tap to cancel selection. final Offset textFieldEnd = tester.getTopRight(find.byType(CupertinoTextField)); await tester.tapAt(textFieldEnd + const Offset(-10.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); // Long tap at the end. await tester.longPressAt(textFieldEnd + const Offset(-10.0, 5.0)); await tester.pumpAndSettle(); // Should have paste and select all options when collapse. expect(find.text('Paste'), findsOneWidget); expect(find.text('Select All'), findsOneWidget); expect(find.text('Copy'), findsNothing); expect(find.text('Cut'), findsNothing); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. testWidgets( 'long press selects the word at the long press position and shows toolbar on non-Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.longPressAt(textFieldStart + const Offset(50.0, 5.0)); await tester.pumpAndSettle(); // Select word, 'Atwater, on long press. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7, affinity: TextAffinity.upstream), ); expectCupertinoToolbarForPartialSelection(); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS}), ); testWidgets( 'long press moves cursor to the exact long press position and shows toolbar on Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( autofocus: true, controller: controller, ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.longPressAt(textFieldStart + const Offset(50.0, 5.0)); await tester.pumpAndSettle(); // Collapsed cursor for iOS long press. expect( controller.selection, const TextSelection.collapsed(offset: 3, affinity: TextAffinity.upstream), ); expectCupertinoToolbarForCollapsedSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press tap cannot initiate a double tap', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( autofocus: true, controller: controller, ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); final Offset ePos = textOffsetToPosition(tester, 6); // Index of 'Atwate|r' await tester.longPressAt(ePos); await tester.pumpAndSettle(const Duration(milliseconds: 50)); expectCupertinoToolbarForCollapsedSelection(); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 6); // Tap in a slightly different position to avoid hitting the context menu // on desktop. final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; final Offset secondTapPos = isTargetPlatformIOS ? ePos : ePos + const Offset(-1.0, 0.0); await tester.tapAt(secondTapPos); await tester.pump(); // The cursor does not move and the toolbar is toggled. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 6); // The toolbar from the long press is now dismissed by the second tap. expectNoCupertinoToolbar(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets( 'long press drag selects word by word and shows toolbar on lift on non-Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); final TestGesture gesture = await tester.startGesture(textFieldStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); // Long press on non-Apple platforms selects the word at the long press position. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7, affinity: TextAffinity.upstream), ); // Toolbar only shows up on long press up. expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(100, 0)); await tester.pump(); // The selection is extended word by word to the drag position. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 12, affinity: TextAffinity.upstream), ); expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(200, 0)); await tester.pump(); // The selection is extended word by word to the drag position. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 23, affinity: TextAffinity.upstream), ); expectNoCupertinoToolbar(); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 23, affinity: TextAffinity.upstream), ); // The toolbar now shows up. expectCupertinoToolbarForPartialSelection(); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'long press drag on a focused TextField moves the cursor under the drag and shows toolbar on lift on Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( autofocus: true, controller: controller, ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); final TestGesture gesture = await tester.startGesture(textFieldStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); // Long press on iOS shows collapsed selection cursor. expect( controller.selection, const TextSelection.collapsed(offset: 3, affinity: TextAffinity.upstream), ); // Toolbar only shows up on long press up. expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(50, 0)); await tester.pump(); // The selection position is now moved with the drag. expect( controller.selection, const TextSelection.collapsed(offset: 6, affinity: TextAffinity.upstream), ); expectNoCupertinoToolbar(); await gesture.moveBy(const Offset(50, 0)); await tester.pump(); // The selection position is now moved with the drag. expect( controller.selection, const TextSelection.collapsed(offset: 9, affinity: TextAffinity.upstream), ); expectNoCupertinoToolbar(); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection.collapsed(offset: 9, affinity: TextAffinity.upstream), ); // The toolbar now shows up. expectCupertinoToolbarForCollapsedSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets('long press drag can edge scroll on non-Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // Just testing the test and making sure that the last character is off // the right side of the screen. expect(lastCharEndpoint[0].point.dx, moreOrLessEquals(1094.73, epsilon: 0.25)); final Offset textfieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); final TestGesture gesture = await tester.startGesture(textfieldStart); await tester.pump(const Duration(milliseconds: 500)); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7, affinity: TextAffinity.upstream), ); expect(find.byType(CupertinoButton), findsNothing); await gesture.moveBy(const Offset(950, 5)); // To the edge of the screen basically. await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 59), ); // Keep moving out. await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 66), ); await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 66, affinity: TextAffinity.upstream), ); // We're at the edge now. expect(find.byType(CupertinoButton), findsNothing); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 66, affinity: TextAffinity.upstream), ); // The toolbar now shows up. expectCupertinoToolbarForFullSelection(); lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // The last character is now on screen near the right edge. expect(lastCharEndpoint[0].point.dx, moreOrLessEquals(785.40, epsilon: 1)); final List<TextSelectionPoint> firstCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 0), // First character's position. ); expect(firstCharEndpoint.length, 1); // The first character is now offscreen to the left. expect(firstCharEndpoint[0].point.dx, moreOrLessEquals(-310.30, epsilon: 1)); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('long press drag can edge scroll on Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( autofocus: true, controller: controller, ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); final RenderEditable renderEditable = tester.renderObject<RenderEditable>( find.byElementPredicate((Element element) => element.renderObject is RenderEditable).last, ); List<TextSelectionPoint> lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // Just testing the test and making sure that the last character is off // the right side of the screen. expect(lastCharEndpoint[0].point.dx, moreOrLessEquals(1094.73, epsilon: 0.25)); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); final TestGesture gesture = await tester.startGesture(textFieldStart + const Offset(300, 5)); await tester.pump(const Duration(milliseconds: 500)); expect( controller.selection, const TextSelection.collapsed(offset: 18, affinity: TextAffinity.upstream), ); expect(find.byType(CupertinoButton), findsNothing); await gesture.moveBy(const Offset(600, 0)); // To the edge of the screen basically. await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 54, affinity: TextAffinity.upstream), ); // Keep moving out. await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 61, affinity: TextAffinity.upstream), ); await gesture.moveBy(const Offset(1, 0)); await tester.pump(); expect( controller.selection, const TextSelection.collapsed(offset: 66, affinity: TextAffinity.upstream), ); // We're at the edge now. expect(find.byType(CupertinoButton), findsNothing); await gesture.up(); await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. expect( controller.selection, const TextSelection.collapsed(offset: 66, affinity: TextAffinity.upstream), ); // The toolbar now shows up. expectCupertinoToolbarForCollapsedSelection(); lastCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 66), // Last character's position. ); expect(lastCharEndpoint.length, 1); // The last character is now on screen. expect(lastCharEndpoint[0].point.dx, moreOrLessEquals(784.73, epsilon: 0.25)); final List<TextSelectionPoint> firstCharEndpoint = renderEditable.getEndpointsForSelection( const TextSelection.collapsed(offset: 0), // First character's position. ); expect(firstCharEndpoint.length, 1); // The first character is now offscreen to the left. expect(firstCharEndpoint[0].point.dx, moreOrLessEquals(-310.20, epsilon: 0.25)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets( 'long tap after a double tap select is not affected', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset pPos = textOffsetToPosition(tester, 9); // Index of 'P|eel' final Offset ePos = textOffsetToPosition(tester, 6); // Index of 'Atwate|r' await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor to the beginning of the second word. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformIOS ? 12 : 9); await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 500)); await tester.longPressAt(ePos); await tester.pumpAndSettle(); // Plain collapsed selection at the exact tap position. expect( controller.selection, const TextSelection.collapsed(offset: 6), ); // Long press toolbar. expectCupertinoToolbarForCollapsedSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets( 'double tap after a long tap is not affected', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( autofocus: true, controller: controller, ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); // Use a position higher than wPos to avoid tapping the context menu on // desktop. final Offset pPos = textOffsetToPosition(tester, 9) + const Offset(0.0, -20.0); // Index of 'P|eel' final Offset wPos = textOffsetToPosition(tester, 3); // Index of 'Atw|ater' await tester.longPressAt(wPos); await tester.pumpAndSettle(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 3); expectCupertinoToolbarForCollapsedSelection(); await tester.tapAt(pPos); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor. expect(find.byType(CupertinoButton), findsNothing); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformIOS ? 12 : 9); await tester.tapAt(pPos); await tester.pumpAndSettle(); // Double tap selection. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets( 'double tap chains work', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.tapAt(textFieldStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), ); await tester.tapAt(textFieldStart + const Offset(50.0, 5.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); // Double tap selecting the same word somewhere else is fine. await tester.tapAt(textFieldStart + const Offset(100.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap hides the toolbar, and retains the selection. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expect(find.byType(CupertinoButton), findsNothing); // Second tap shows the toolbar, and retains the selection. await tester.tapAt(textFieldStart + const Offset(100.0, 5.0)); // Wait for the consecutive tap timer to timeout so the next // tap is not detected as a triple tap. await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); await tester.tapAt(textFieldStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor and hides the toolbar. expect( controller.selection, const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), ); expect(find.byType(CupertinoButton), findsNothing); await tester.tapAt(textFieldStart + const Offset(150.0, 5.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); group('Triple tap/click', () { const String testValueA = 'Now is the time for\n' // 20 'all good people\n' // 20 + 16 => 36 'to come to the aid\n' // 36 + 19 => 55 'of their country.'; // 55 + 17 => 72 const String testValueB = 'Today is the time for\n' // 22 'all good people\n' // 22 + 16 => 38 'to come to the aid\n' // 38 + 19 => 57 'of their country.'; // 57 + 17 => 74 testWidgets( 'Can triple tap to select a paragraph on mobile platforms when tapping at a word edge', (WidgetTester tester) async { // TODO(Renzo-Olivares): Enable, currently broken because selection overlay blocks the TextSelectionGestureDetector. final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final bool isTargetPlatformApple = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValueA); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(controller.value.text, testValueA); final Offset firstLinePos = tester.getTopLeft(find.byType(CupertinoTextField)) + const Offset(110.0, 9.0); // Tap on text field to gain focus, and set selection to 'is|' on the first line. final TestGesture gesture = await tester.startGesture(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 6); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. On iOS, tapping a whitespace selects the previous word. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, isTargetPlatformApple ? 4 : 6); expect(controller.selection.extentOffset, isTargetPlatformApple ? 6 : 7); // Here we tap on same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 20); }, variant: TargetPlatformVariant.mobile(), skip: true, // https://github.com/flutter/flutter/issues/123415 ); testWidgets( 'Can triple tap to select a paragraph on mobile platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final bool isTargetPlatformApple = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValueB); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(controller.value.text, testValueB); final Offset firstLinePos = tester.getTopLeft(find.byType(CupertinoTextField)) + const Offset(50.0, 9.0); // Tap on text field to gain focus, and move the selection. final TestGesture gesture = await tester.startGesture(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, isTargetPlatformApple ? 5 : 3); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 5); // Here we tap on same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 22); }, variant: TargetPlatformVariant.mobile(), ); testWidgets( 'Triple click at the beginning of a line should not select the previous paragraph', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/132126 final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValueB); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(controller.value.text, testValueB); final Offset thirdLinePos = textOffsetToPosition(tester, 38); // Click on text field to gain focus, and move the selection. final TestGesture gesture = await tester.startGesture(thirdLinePos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 38); // Here we click on same position again, to register a double click. This will select // the word at the clicked position. await gesture.down(thirdLinePos); await gesture.up(); expect(controller.selection.baseOffset, 38); expect(controller.selection.extentOffset, 40); // Here we click on same position again, to register a triple click. This will select // the paragraph at the clicked position. await gesture.down(thirdLinePos); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 38); expect(controller.selection.extentOffset, 57); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.linux }), ); testWidgets( 'Triple click at the end of text should select the previous paragraph', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/132126. final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValueB); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(controller.value.text, testValueB); final Offset endOfTextPos = textOffsetToPosition(tester, 74); // Click on text field to gain focus, and move the selection. final TestGesture gesture = await tester.startGesture(endOfTextPos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 74); // Here we click on same position again, to register a double click. await gesture.down(endOfTextPos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 74); expect(controller.selection.extentOffset, 74); // Here we click on same position again, to register a triple click. This will select // the paragraph at the clicked position. await gesture.down(endOfTextPos); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 57); expect(controller.selection.extentOffset, 74); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.linux }), ); testWidgets( 'triple tap chains work on Non-Apple mobile platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: Center( child: CupertinoTextField( controller: controller, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 3); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 35), ); // Triple tap selecting the same paragraph somewhere else is fine. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap hides the toolbar and moves the selection. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 6); expectNoCupertinoToolbar(); // Second tap shows the toolbar and selects the word. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); // Third tap shows the toolbar and selects the paragraph. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 35), ); expectCupertinoToolbarForFullSelection(); await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor and hid the toolbar. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 9); expect(find.byType(CupertinoButton), findsNothing); // Second tap selects the word. await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); expectCupertinoToolbarForPartialSelection(); // Third tap selects the paragraph and shows the toolbar. await tester.tapAt(textfieldStart + const Offset(150.0, 9.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 35), ); expectCupertinoToolbarForFullSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia }), ); testWidgets( 'triple tap chains work on Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure\nThe fox jumped over the fence.', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: Center( child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textfieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 7); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); await tester.tapAt(textfieldStart + const Offset(50.0, 9.0)); await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 36), ); // Triple tap selecting the same paragraph somewhere else is fine. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap hides the toolbar and retains the selection. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 36), ); expect(find.byType(CupertinoButton), findsNothing); // Second tap shows the toolbar and selects the word. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7), ); expectCupertinoToolbarForPartialSelection(); // Third tap shows the toolbar and selects the paragraph. await tester.tapAt(textfieldStart + const Offset(100.0, 9.0)); await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 36), ); expectCupertinoToolbarForPartialSelection(); await tester.tapAt(textfieldStart + const Offset(150.0, 25.0)); await tester.pump(const Duration(milliseconds: 50)); // First tap moved the cursor and hid the toolbar. expect( controller.selection, const TextSelection.collapsed(offset: 50, affinity: TextAffinity.upstream), ); expect(find.byType(CupertinoButton), findsNothing); // Second tap selects the word. await tester.tapAt(textfieldStart + const Offset(150.0, 25.0)); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 44, extentOffset: 50), ); expectCupertinoToolbarForPartialSelection(); // Third tap selects the paragraph and shows the toolbar. await tester.tapAt(textfieldStart + const Offset(150.0, 25.0)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 36, extentOffset: 66), ); expectCupertinoToolbarForPartialSelection(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets( 'triple click chains work', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: testValueA, ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: Center( child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); final bool platformSelectsByLine = defaultTargetPlatform == TargetPlatform.linux; // First click moves the cursor to the point of the click, not the edge of // the clicked word. final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(200.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 12); // Second click selects the word. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); // Triple click selects the paragraph. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); // Wait for the consecutive tap timer to timeout so the next // tap is not detected as a triple tap. await tester.pumpAndSettle(kDoubleTapTimeout); expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); // Triple click selecting the same paragraph somewhere else is fine. await gesture.down(textFieldStart + const Offset(100.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // First click moved the cursor. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 6); await gesture.down(textFieldStart + const Offset(100.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Second click selected the word. expect( controller.selection, const TextSelection(baseOffset: 4, extentOffset: 6), ); await gesture.down(textFieldStart + const Offset(100.0, 9.0)); await tester.pump(); await gesture.up(); // Wait for the consecutive tap timer to timeout so the tap count // is reset. await tester.pumpAndSettle(kDoubleTapTimeout); // Third click selected the paragraph. expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // First click moved the cursor. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 9); await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Second click selected the word. expect( controller.selection, const TextSelection(baseOffset: 7, extentOffset: 10), ); await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Third click selects the paragraph. expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); }, variant: TargetPlatformVariant.desktop(), ); testWidgets( 'triple click after a click on desktop platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: testValueA, ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: Center( child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); final bool platformSelectsByLine = defaultTargetPlatform == TargetPlatform.linux; final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(50.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 3); // First click moves the selection. await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 9); // Double click selection to select a word. await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 7, extentOffset: 10), ); // Triple click selection to select a paragraph. await gesture.down(textFieldStart + const Offset(150.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); }, variant: TargetPlatformVariant.desktop(), ); testWidgets( 'Can triple tap to select all on a single-line textfield on mobile platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: testValueB, ); addTearDown(controller.dispose); final bool isTargetPlatformApple = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset firstLinePos = tester.getTopLeft(find.byType(CupertinoTextField)) + const Offset(50.0, 9.0); // Tap on text field to gain focus, and set selection somewhere on the first word. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, isTargetPlatformApple ? 5 : 3); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 5); // Here we tap on same position again, to register a triple tap. This will select // the entire text field if it is a single-line field. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 74); }, variant: TargetPlatformVariant.mobile(), ); testWidgets( 'Can triple click to select all on a single-line textfield on desktop platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: testValueA, ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); final Offset firstLinePos = textOffsetToPosition(tester, 5); // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on same position again, to register a triple tap. This will select // the entire text field if it is a single-line field. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 72); }, variant: TargetPlatformVariant.desktop(), ); testWidgets( 'Can triple click to select a line on Linux', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValueA); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(controller.value.text, testValueA); final Offset firstLinePos = textOffsetToPosition(tester, 5); // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 19); }, variant: TargetPlatformVariant.only(TargetPlatform.linux), ); testWidgets( 'Can triple click to select a paragraph', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValueA); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(controller.value.text, testValueA); final Offset firstLinePos = textOffsetToPosition(tester, 5); // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 20); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.linux }), ); testWidgets( 'Can triple click + drag to select line by line on Linux', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValueA); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(controller.value.text, testValueA); final Offset firstLinePos = textOffsetToPosition(tester, 5); // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on the same position again, to register a triple tap. This will select // the line at the tapped position. await gesture.down(firstLinePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 19); // Drag, down after the triple tap, to select line by line. // Moving down will extend the selection to the second line. await gesture.moveTo(firstLinePos + const Offset(0, 10.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 35); // Moving down will extend the selection to the third line. await gesture.moveTo(firstLinePos + const Offset(0, 20.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 54); // Moving down will extend the selection to the last line. await gesture.moveTo(firstLinePos + const Offset(0, 40.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 72); // Moving up will extend the selection to the third line. await gesture.moveTo(firstLinePos + const Offset(0, 20.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 54); // Moving up will extend the selection to the second line. await gesture.moveTo(firstLinePos + const Offset(0, 10.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 35); // Moving up will extend the selection to the first line. await gesture.moveTo(firstLinePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 19); }, variant: TargetPlatformVariant.only(TargetPlatform.linux), ); testWidgets( 'Can triple click + drag to select paragraph by paragraph', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValueA); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(controller.value.text, testValueA); final Offset firstLinePos = textOffsetToPosition(tester, 5); // Tap on text field to gain focus, and set selection to 'i|s' on the first line. final TestGesture gesture = await tester.startGesture( firstLinePos, pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); // Here we tap on same position again, to register a double tap. This will select // the word at the tapped position. await gesture.down(firstLinePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 6); // Here we tap on the same position again, to register a triple tap. This will select // the paragraph at the tapped position. await gesture.down(firstLinePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 20); // Drag, down after the triple tap, to select paragraph by paragraph. // Moving down will extend the selection to the second line. await gesture.moveTo(firstLinePos + const Offset(0, 10.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 36); // Moving down will extend the selection to the third line. await gesture.moveTo(firstLinePos + const Offset(0, 20.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 55); // Moving down will extend the selection to the last line. await gesture.moveTo(firstLinePos + const Offset(0, 40.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 72); // Moving up will extend the selection to the third line. await gesture.moveTo(firstLinePos + const Offset(0, 20.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 55); // Moving up will extend the selection to the second line. await gesture.moveTo(firstLinePos + const Offset(0, 10.0)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 36); // Moving up will extend the selection to the first line. await gesture.moveTo(firstLinePos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 20); }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.linux }), ); testWidgets( 'Going past triple click retains the selection on Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: testValueA, ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: Center( child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); // First click moves the cursor to the point of the click, not the edge of // the clicked word. final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(200.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 12); // Second click selects the word. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); // Triple click selects the paragraph. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); // Clicking again retains the selection. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again retains the selection. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again retains the selection. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), ); testWidgets( 'Tap count resets when going past a triple tap on Android, Fuchsia, and Linux', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: testValueA, ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: Center( child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); final bool platformSelectsByLine = defaultTargetPlatform == TargetPlatform.linux; // First click moves the cursor to the point of the click, not the edge of // the clicked word. final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(200.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 12); // Second click selects the word. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); // Triple click selects the paragraph. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); // Clicking again moves the caret to the tapped position. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 12); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again selects the word. expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again selects the paragraph. expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // Clicking again moves the caret to the tapped position. expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 12); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again selects the word. expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again selects the paragraph. expect( controller.selection, TextSelection(baseOffset: 0, extentOffset: platformSelectsByLine ? 19 : 20), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux }), ); testWidgets( 'Double click and triple click alternate on Windows', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: testValueA, ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: Center( child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); // First click moves the cursor to the point of the click, not the edge of // the clicked word. final TestGesture gesture = await tester.startGesture( textFieldStart + const Offset(200.0, 9.0), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 12); // Second click selects the word. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); // Triple click selects the paragraph. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); // Clicking again selects the word. await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again selects the paragraph. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again selects the word. expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(const Duration(milliseconds: 50)); // Clicking again selects the paragraph. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pump(); // Clicking again selects the word. expect( controller.selection, const TextSelection(baseOffset: 11, extentOffset: 15), ); await gesture.down(textFieldStart + const Offset(200.0, 9.0)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); // Clicking again selects the paragraph. expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 20), ); }, variant: TargetPlatformVariant.only(TargetPlatform.windows), ); }); testWidgets('force press selects word', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset textFieldStart = tester.getTopLeft(find.byType(CupertinoTextField)); final int pointerValue = tester.nextPointer; final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( textFieldStart + const Offset(150.0, 5.0), PointerDownEvent( pointer: pointerValue, position: textFieldStart + const Offset(150.0, 5.0), pressure: 3.0, pressureMax: 6.0, pressureMin: 0.0, ), ); // We expect the force press to select a word at the given location. expect( controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12), ); await gesture.up(); await tester.pumpAndSettle(); // Shows toolbar. expectCupertinoToolbarForPartialSelection(); }); testWidgets('force press on unsupported devices falls back to tap', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final Offset pPos = textOffsetToPosition(tester, 9); // Index of 'P|eel' final int pointerValue = tester.nextPointer; final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( pPos, PointerDownEvent( pointer: pointerValue, position: pPos, // iPhone 6 and below report 0 across the board. pressure: 0, pressureMax: 0, pressureMin: 0, ), ); await gesture.up(); // Fall back to a single tap which selects the edge of the word on iOS, and // a precise position on macOS. expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformIOS ? 12 : 9); await tester.pump(); // Falling back to a single tap doesn't trigger a toolbar. expect(find.byType(CupertinoButton), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Cannot drag one handle past the other', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'abc def ghi', ); addTearDown(controller.dispose); // On iOS/iPadOS, during a tap we select the edge of the word closest to the tap. // On macOS, we select the precise position of the tap. final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, style: const TextStyle(fontSize: 10.0), ), ), ), ); // Double tap on 'e' to select 'def'. final Offset ePos = textOffsetToPosition(tester, 5); await tester.tapAt(ePos, pointer: 7); await tester.pump(const Duration(milliseconds: 50)); expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, isTargetPlatformIOS ? 7 : 5); await tester.tapAt(ePos, pointer: 7); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 7); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); expect(endpoints.length, 2); // On Mac, the toolbar blocks the drag on the right handle, so hide it. final EditableTextState editableTextState = tester.state(find.byType(EditableText)); editableTextState.hideToolbar(false); await tester.pumpAndSettle(); // Drag the right handle until there's only 1 char selected. // We use a small offset because the endpoint is on the very corner // of the handle. final Offset handlePos = endpoints[1].point; Offset newHandlePos = textOffsetToPosition(tester, 5); // Position of 'e'. final TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 5); newHandlePos = textOffsetToPosition(tester, 2); // Position of 'c'. await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 4); // The selection doesn't move beyond the left handle. There's always at // least 1 char selected. expect(controller.selection.extentOffset, 5); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); testWidgets('Dragging between multiple lines keeps the contact point at the same place on the handle on Android', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( // 11 first line, 19 second line, 17 third line = length 49 text: 'a big house\njumped over a mouse\nOne more line yay', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: 3, minLines: 3, ), ), ), ); // Double tap to select 'over'. final Offset pos = textOffsetToPosition(tester, controller.text.indexOf('v')); // The first tap. TestGesture gesture = await tester.startGesture(pos, pointer: 7); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero // The second tap. await gesture.down(pos); await tester.pump(); await gesture.up(); await tester.pump(); final TextSelection selection = controller.selection; expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 23, ), ); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle 4 letters to the right. // The adjustment moves the tap from the text position to the handle. const Offset endHandleAdjustment = Offset(1.0, 6.0); Offset handlePos = endpoints[1].point + endHandleAdjustment; Offset newHandlePos = textOffsetToPosition(tester, 27) + endHandleAdjustment; await tester.pump(); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 27, ), ); // Drag the right handle 1 line down. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[1].point + endHandleAdjustment; final Offset toNextLine = Offset( 0.0, findRenderEditable(tester).preferredLineHeight + 3.0, ); newHandlePos = handlePos + toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 47, ), ); // Drag the right handle back up 1 line. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[1].point + endHandleAdjustment; newHandlePos = handlePos - toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 27, ), ); // Drag the left handle 4 letters to the left. // The adjustment moves the tap from the text position to the handle. const Offset startHandleAdjustment = Offset(-1.0, 6.0); endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = textOffsetToPosition(tester, 15) + startHandleAdjustment; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 15, extentOffset: 27, ), ); // Drag the left handle 1 line up. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; // Move handle a sufficient global distance so it can be considered a drag // by the selection handle's [PanGestureRecognizer]. newHandlePos = handlePos - (toNextLine * 2); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 3, extentOffset: 27, ), ); // Drag the left handle 1 line back down. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = handlePos + toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); // Move handle up a small amount before dragging it down so the total global // distance travelled can be accepted by the selection handle's [PanGestureRecognizer] as a drag. // This way it can declare itself the winner before the [TapAndDragGestureRecognizer] that // is on the selection overlay. await tester.pump(); await gesture.moveTo(handlePos - toNextLine); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 15, extentOffset: 27, ), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), ); testWidgets('Dragging between multiple lines keeps the contact point at the same place on the handle on iOS', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( // 11 first line, 19 second line, 17 third line = length 49 text: 'a big house\njumped over a mouse\nOne more line yay', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: 3, minLines: 3, ), ), ), ); // Double tap to select 'over'. final Offset pos = textOffsetToPosition(tester, controller.text.indexOf('v')); // The first tap. TestGesture gesture = await tester.startGesture(pos, pointer: 7); await tester.pump(); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero // The second tap. await gesture.down(pos); await tester.pump(); await gesture.up(); await tester.pump(); final TextSelection selection = controller.selection; expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 23, ), ); final RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Drag the right handle 4 letters to the right. // The adjustment moves the tap from the text position to the handle. const Offset endHandleAdjustment = Offset(1.0, 6.0); Offset handlePos = endpoints[1].point + endHandleAdjustment; Offset newHandlePos = textOffsetToPosition(tester, 27) + endHandleAdjustment; await tester.pump(); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 27, ), ); // Drag the right handle 1 line down. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[1].point + endHandleAdjustment; final double lineHeight = findRenderEditable(tester).preferredLineHeight; final Offset toNextLine = Offset(0.0, lineHeight + 3.0); newHandlePos = handlePos + toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 47, ), ); // Drag the right handle back up 1 line. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[1].point + endHandleAdjustment; newHandlePos = handlePos - toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 19, extentOffset: 27, ), ); // Drag the left handle 4 letters to the left. // The adjustment moves the tap from the text position to the handle. final Offset startHandleAdjustment = Offset(-1.0, -lineHeight + 6.0); endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = textOffsetToPosition(tester, 15) + startHandleAdjustment; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); // On Apple platforms, dragging the base handle makes it the extent. expect( controller.selection, const TextSelection( baseOffset: 27, extentOffset: 15, ), ); // Drag the left handle 1 line up. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = handlePos - toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 27, extentOffset: 3, ), ); // Drag the left handle 1 line back down. endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); handlePos = endpoints[0].point + startHandleAdjustment; newHandlePos = handlePos + toNextLine; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect( controller.selection, const TextSelection( baseOffset: 27, extentOffset: 15, ), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Selection updates on tap down (Desktop platforms)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField(controller: controller), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); final Offset ePos = textOffsetToPosition(tester, 5); final Offset gPos = textOffsetToPosition(tester, 8); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 5); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); await gesture.down(gPos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); // This should do nothing. The selection is set on tap down on desktop platforms. await gesture.up(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); }, variant: TargetPlatformVariant.desktop(), ); testWidgets('Selection updates on tap up (Mobile platforms)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final bool isTargetPlatformApple = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField(controller: controller), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); final Offset ePos = textOffsetToPosition(tester, 5); final Offset gPos = textOffsetToPosition(tester, 8); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); await gesture.down(gPos); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 5); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); final TestGesture touchGesture = await tester.startGesture(ePos); await touchGesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); // On iOS, a tap to select, selects the word edge instead of the exact tap position. expect(controller.selection.baseOffset, isTargetPlatformApple ? 7 : 5); expect(controller.selection.extentOffset, isTargetPlatformApple ? 7 : 5); // Selection should stay the same since it is set on tap up for mobile platforms. await touchGesture.down(gPos); await tester.pump(); expect(controller.selection.baseOffset, isTargetPlatformApple ? 7 : 5); expect(controller.selection.extentOffset, isTargetPlatformApple ? 7 : 5); await touchGesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); }, variant: TargetPlatformVariant.mobile(), ); testWidgets('Can select text by dragging with a mouse', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, style: const TextStyle(fontSize: 10.0), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); // Skip past scrolling animation. await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.moveTo(gPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, testValue.indexOf('e')); expect(controller.selection.extentOffset, testValue.indexOf('g')); }); testWidgets('Cursor should not move on a quick touch drag when touch does not begin on previous selection (iOS)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(const Duration(milliseconds: 200)); final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); final Offset iPos = textOffsetToPosition(tester, testValue.indexOf('i')); // Tap on text field to gain focus, and set selection to '|a'. On iOS // the selection is set to the word edge closest to the tap position. // We await for [kDoubleTapTimeout] after the up event, so our next down // event does not register as a double tap. final TestGesture gesture = await tester.startGesture(aPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); // The position we tap during a drag start is not on the collapsed selection, // so the cursor should not move. await gesture.down(textOffsetToPosition(tester, 7)); await gesture.moveTo(iPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Can move cursor when dragging, when tap is on collapsed selection (iOS)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(const Duration(milliseconds: 200)); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset iPos = textOffsetToPosition(tester, testValue.indexOf('i')); // Tap on text field to gain focus, and set selection to '|g'. On iOS // the selection is set to the word edge closest to the tap position. // We await for [kDoubleTapTimeout] after the up event, so our next down // event does not register as a double tap. final TestGesture gesture = await tester.startGesture(ePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 7); // If the position we tap during a drag start is on the collapsed selection, then // we can move the cursor with a drag. // Here we tap on '|g', where our selection was previously, and move to '|i'. await gesture.down(textOffsetToPosition(tester, 7)); await tester.pump(); await gesture.moveTo(iPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('i')); // End gesture and skip the magnifier hide animation, so it can release // resources. await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 150)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Can move cursor when dragging, when tap is on collapsed selection (iOS) - multiline', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); const String testValue = 'abc\ndef\nghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(const Duration(milliseconds: 200)); final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); final Offset iPos = textOffsetToPosition(tester, testValue.indexOf('i')); // Tap on text field to gain focus, and set selection to '|a'. On iOS // the selection is set to the word edge closest to the tap position. // We await for kDoubleTapTimeout after the up event, so our next down event // does not register as a double tap. final TestGesture gesture = await tester.startGesture(aPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); // If the position we tap during a drag start is on the collapsed selection, then // we can move the cursor with a drag. // Here we tap on '|a', where our selection was previously, and move to '|i'. await gesture.down(aPos); await tester.pump(); await gesture.moveTo(iPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('i')); // End gesture and skip the magnifier hide animation, so it can release // resources. await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 150)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Can move cursor when dragging, when tap is on collapsed selection (iOS) - ListView', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/122519 final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, maxLines: null, ), ), ), ); const String testValue = 'abc\ndef\nghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(const Duration(milliseconds: 200)); final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); final Offset iPos = textOffsetToPosition(tester, testValue.indexOf('i')); // Tap on text field to gain focus, and set selection to '|a'. On iOS // the selection is set to the word edge closest to the tap position. // We await for kDoubleTapTimeout after the up event, so our next down event // does not register as a double tap. final TestGesture gesture = await tester.startGesture(aPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); // If the position we tap during a drag start is on the collapsed selection, then // we can move the cursor with a drag. // Here we tap on '|a', where our selection was previously, and attempt move // to '|g'. The cursor will not move because the `VerticalDragGestureRecognizer` // in the scrollable will beat the `TapAndHorizontalDragGestureRecognizer` // in the TextField. This is because moving from `|a` to `|g` is a completely // vertical movement. await gesture.down(aPos); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); // Release the pointer. await gesture.up(); await tester.pumpAndSettle(); // If the position we tap during a drag start is on the collapsed selection, then // we can move the cursor with a drag. // Here we tap on '|a', where our selection was previously, and move to '|i'. // Unlike our previous attempt to drag to `|g`, this works because moving // to `|i` includes a horizontal movement so the `TapAndHorizontalDragGestureRecognizer` // in TextField can beat the `VerticalDragGestureRecognizer` in the scrollable. await gesture.down(aPos); await tester.pump(); await gesture.moveTo(iPos); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('i')); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), ); testWidgets('Can move cursor when dragging (Android)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(const Duration(milliseconds: 200)); final Offset ePos = textOffsetToPosition(tester, testValue.indexOf('e')); final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); // Tap on text field to gain focus, and set selection to '|e'. // We await for [kDoubleTapTimeout] after the up event, so our // next down event does not register as a double tap. final TestGesture gesture = await tester.startGesture(ePos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('e')); // Here we tap on '|d', and move to '|g'. await gesture.down(textOffsetToPosition(tester, testValue.indexOf('d'))); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, testValue.indexOf('g')); // End gesture and skip the magnifier hide animation, so it can release // resources. await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 150)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia }), ); testWidgets('Continuous dragging does not cause flickering', (WidgetTester tester) async { int selectionChangedCount = 0; const String testValue = 'abc def ghi'; final TextEditingController controller = TextEditingController(text: testValue); addTearDown(controller.dispose); controller.addListener(() { selectionChangedCount++; }); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, style: const TextStyle(fontSize: 10.0), ), ), ), ); final Offset cPos = textOffsetToPosition(tester, 2); // Index of 'c'. final Offset gPos = textOffsetToPosition(tester, 8); // Index of 'g'. final Offset hPos = textOffsetToPosition(tester, 9); // Index of 'h'. // Drag from 'c' to 'g'. final TestGesture gesture = await tester.startGesture(cPos, kind: PointerDeviceKind.mouse); await tester.pump(); await gesture.moveTo(gPos); await tester.pumpAndSettle(); expect(selectionChangedCount, isNonZero); selectionChangedCount = 0; expect(controller.selection.baseOffset, 2); expect(controller.selection.extentOffset, 8); // Tiny movement shouldn't cause text selection to change. await gesture.moveTo(gPos + const Offset(2.0, 0.0)); await tester.pumpAndSettle(); expect(selectionChangedCount, 0); // Now a text selection change will occur after a significant movement. await gesture.moveTo(hPos); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(selectionChangedCount, 1); expect(controller.selection.baseOffset, 2); expect(controller.selection.extentOffset, 9); }); testWidgets('Tap does not show handles nor toolbar', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'abc def ghi', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField(controller: controller), ), ), ); // Tap to trigger the text field. await tester.tap(find.byType(CupertinoTextField)); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); }); testWidgets('Long press shows toolbar but not handles', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'abc def ghi', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField(controller: controller), ), ), ); // Long press to trigger the text field. await tester.longPress(find.byType(CupertinoTextField)); await tester.pump(); // A long press in Cupertino should position the cursor without any selection. expect(controller.selection.isCollapsed, isTrue); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); expect(editableText.selectionOverlay!.toolbarIsVisible, isContextMenuProvidedByPlatform ? isFalse : isTrue); }); testWidgets( 'Double tap shows handles and toolbar if selection is not collapsed', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'abc def ghi', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField(controller: controller), ), ), ); final Offset hPos = textOffsetToPosition(tester, 9); // Position of 'h'. // Double tap on 'h' to select 'ghi'. await tester.tapAt(hPos); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(hPos); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); expect(editableText.selectionOverlay!.toolbarIsVisible, isContextMenuProvidedByPlatform ? isFalse : isTrue); }, ); testWidgets( 'Double tap shows toolbar but not handles if selection is collapsed', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'abc def ghi', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField(controller: controller), ), ), ); final Offset textEndPos = textOffsetToPosition(tester, 11); // Position at the end of text. // Double tap to place the cursor at the end. await tester.tapAt(textEndPos); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(textEndPos); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); expect(editableText.selectionOverlay!.toolbarIsVisible, isContextMenuProvidedByPlatform ? isFalse : isTrue); }, ); testWidgets( 'Mouse long press does not show handles nor toolbar', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'abc def ghi', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField(controller: controller), ), ), ); // Long press to trigger the text field. final Offset textFieldPos = tester.getCenter(find.byType(CupertinoTextField)); final TestGesture gesture = await tester.startGesture( textFieldPos, kind: PointerDeviceKind.mouse, ); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); final EditableTextState editableText = tester.state(find.byType(EditableText)); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); }, ); testWidgets( 'Mouse double tap does not show handles nor toolbar', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'abc def ghi', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField(controller: controller), ), ), ); final EditableTextState editableText = tester.state(find.byType(EditableText)); // Double tap at the end of text. final Offset textEndPos = textOffsetToPosition(tester, 11); // Position at the end of text. final TestGesture gesture = await tester.startGesture( textEndPos, kind: PointerDeviceKind.mouse, ); await tester.pump(const Duration(milliseconds: 50)); await gesture.up(); await tester.pump(); await gesture.down(textEndPos); await tester.pump(); await gesture.up(); await tester.pump(); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); final Offset hPos = textOffsetToPosition(tester, 9); // Position of 'h'. // Double tap on 'h' to select 'ghi'. await gesture.down(hPos); await tester.pump(const Duration(milliseconds: 50)); await gesture.up(); await tester.pump(); await gesture.down(hPos); await tester.pump(); await gesture.up(); await tester.pump(); expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); }, ); testWidgets('onTap is called upon tap', (WidgetTester tester) async { int tapCount = 0; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( onTap: () => tapCount++, ), ), ), ); expect(tapCount, 0); await tester.tap(find.byType(CupertinoTextField)); await tester.pump(); expect(tapCount, 1); // Wait out the double tap interval so the next tap doesn't end up being // recognized as a double tap. await tester.pump(const Duration(seconds: 1)); // Double tap count as one single tap. await tester.tap(find.byType(CupertinoTextField)); await tester.pump(const Duration(milliseconds: 100)); await tester.tap(find.byType(CupertinoTextField)); await tester.pump(); expect(tapCount, 2); }); testWidgets( 'onTap does not work when the text field is disabled', (WidgetTester tester) async { int tapCount = 0; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( enabled: false, onTap: () => tapCount++, ), ), ), ); expect(tapCount, 0); await tester.tap(find.byType(CupertinoTextField), warnIfMissed: false); // disabled await tester.pump(); expect(tapCount, 0); // Wait out the double tap interval so the next tap doesn't end up being // recognized as a double tap. await tester.pump(const Duration(seconds: 1)); // Enabling the text field, now it should accept taps. await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( onTap: () => tapCount++, ), ), ), ); await tester.tap(find.byType(CupertinoTextField)); expect(tapCount, 1); await tester.pump(const Duration(seconds: 1)); // Disable it again. await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( enabled: false, onTap: () => tapCount++, ), ), ), ); await tester.tap(find.byType(CupertinoTextField), warnIfMissed: false); // disabled await tester.pump(); expect(tapCount, 1); }, ); testWidgets('Focus test when the text field is disabled', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( focusNode: focusNode, ), ), ), ); expect(focusNode.hasFocus, false); // initial status // Should accept requestFocus. focusNode.requestFocus(); await tester.pump(); expect(focusNode.hasFocus, true); // Disable the text field, now it should not accept requestFocus. await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( enabled: false, focusNode: focusNode, ), ), ), ); // Should not accept requestFocus. focusNode.requestFocus(); await tester.pump(); expect(focusNode.hasFocus, false); }); testWidgets( 'text field respects theme', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( theme: CupertinoThemeData( brightness: Brightness.dark, ), home: Center( child: CupertinoTextField(), ), ), ); final BoxDecoration decoration = tester.widget<DecoratedBox>( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(DecoratedBox), ), ).decoration as BoxDecoration; expect( decoration.border!.bottom.color.value, 0x33FFFFFF, ); await tester.enterText(find.byType(CupertinoTextField), 'smoked meat'); await tester.pump(); expect( tester.renderObject<RenderEditable>( find.byElementPredicate((Element element) => element.renderObject is RenderEditable).last, ).text!.style!.color, isSameColorAs(CupertinoColors.white), ); }, ); testWidgets( 'Check the toolbar appears below the TextField when there is not enough space above the TextField to show it', (WidgetTester tester) async { // This is a regression test for // https://github.com/flutter/flutter/issues/29808 const String testValue = 'abc def ghi'; final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Container( padding: const EdgeInsets.all(30), child: CupertinoTextField( controller: controller, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValue); // Tap the selection handle to bring up the "paste / select all" menu. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero RenderEditable renderEditable = findRenderEditable(tester); List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); await tester.tapAt(endpoints[0].point + const Offset(1.0, 1.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 300)); // skip past the frame where the opacity is zero // Verify the selection toolbar position Offset toolbarTopLeft = tester.getTopLeft(find.text('Paste')); Offset textFieldTopLeft = tester.getTopLeft(find.byType(CupertinoTextField)); expect(textFieldTopLeft.dy, lessThan(toolbarTopLeft.dy)); await tester.pumpWidget( CupertinoApp( home: Container( padding: const EdgeInsets.all(150), child: CupertinoTextField( controller: controller, ), ), ), ); await tester.enterText(find.byType(CupertinoTextField), testValue); // Tap the selection handle to bring up the "paste / select all" menu. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero renderEditable = findRenderEditable(tester); endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); await tester.tapAt(endpoints[0].point + const Offset(1.0, 1.0)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero // Verify the selection toolbar position toolbarTopLeft = tester.getTopLeft(find.text('Paste')); textFieldTopLeft = tester.getTopLeft(find.byType(CupertinoTextField)); expect(toolbarTopLeft.dy, lessThan(textFieldTopLeft.dy)); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); testWidgets('text field respects keyboardAppearance from theme', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); await tester.pumpWidget( const CupertinoApp( theme: CupertinoThemeData( brightness: Brightness.dark, ), home: Center( child: CupertinoTextField(), ), ), ); await tester.showKeyboard(find.byType(EditableText)); final MethodCall setClient = log.first; expect(setClient.method, 'TextInput.setClient'); expect(((setClient.arguments as List<dynamic>).last as Map<String, dynamic>)['keyboardAppearance'], 'Brightness.dark'); }); testWidgets('text field can override keyboardAppearance from theme', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { log.add(methodCall); return null; }); await tester.pumpWidget( const CupertinoApp( theme: CupertinoThemeData( brightness: Brightness.dark, ), home: Center( child: CupertinoTextField( keyboardAppearance: Brightness.light, ), ), ), ); await tester.showKeyboard(find.byType(EditableText)); final MethodCall setClient = log.first; expect(setClient.method, 'TextInput.setClient'); expect(((setClient.arguments as List<dynamic>).last as Map<String, dynamic>)['keyboardAppearance'], 'Brightness.light'); }); testWidgets('cursorColor respects theme', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: CupertinoTextField(), ), ); final Finder textFinder = find.byType(CupertinoTextField); await tester.tap(textFinder); await tester.pump(); final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); final RenderEditable renderEditable = editableTextState.renderEditable; expect(renderEditable.cursorColor, CupertinoColors.activeBlue.color); await tester.pumpWidget( const CupertinoApp( home: CupertinoTextField(), theme: CupertinoThemeData( brightness: Brightness.dark, ), ), ); await tester.pump(); expect(renderEditable.cursorColor, CupertinoColors.activeBlue.darkColor); await tester.pumpWidget( const CupertinoApp( home: CupertinoTextField(), theme: CupertinoThemeData( primaryColor: Color(0xFFF44336), ), ), ); await tester.pump(); expect(renderEditable.cursorColor, const Color(0xFFF44336)); }); testWidgets('cursor can override color from theme', (WidgetTester tester) async { const CupertinoDynamicColor cursorColor = CupertinoDynamicColor.withBrightness( color: Color(0x12345678), darkColor: Color(0x87654321), ); await tester.pumpWidget( const CupertinoApp( theme: CupertinoThemeData(), home: Center( child: CupertinoTextField( cursorColor: cursorColor, ), ), ), ); EditableText editableText = tester.firstWidget(find.byType(EditableText)); expect(editableText.cursorColor.value, 0x12345678); await tester.pumpWidget( const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.dark), home: Center( child: CupertinoTextField( cursorColor: cursorColor, ), ), ), ); editableText = tester.firstWidget(find.byType(EditableText)); expect(editableText.cursorColor.value, 0x87654321); }); testWidgets('shows selection handles', (WidgetTester tester) async { const String testText = 'lorem ipsum'; final TextEditingController controller = TextEditingController(text: testText); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(), home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); final RenderEditable renderEditable = tester.state<EditableTextState>(find.byType(EditableText)).renderEditable; await tester.tapAt(textOffsetToPosition(tester, 5)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pumpAndSettle(); final List<Widget> transitions = find.byType(FadeTransition).evaluate().map((Element e) => e.widget).toList(); expect(transitions.length, 2); final FadeTransition left = transitions[0] as FadeTransition; final FadeTransition right = transitions[1] as FadeTransition; expect(left.opacity.value, equals(1.0)); expect(right.opacity.value, equals(1.0)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('when CupertinoTextField would be blocked by keyboard, it is shown with enough space for the selection handle', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget(CupertinoApp( theme: const CupertinoThemeData(), home: Center( child: ListView( controller: scrollController, children: <Widget>[ Container(height: 583), // Push field almost off screen. CupertinoTextField(controller: controller), Container(height: 1000), ], ), ), )); // Tap the TextField to put the cursor into it and bring it into view. expect(scrollController.offset, 0.0); await tester.tap(find.byType(CupertinoTextField)); await tester.pumpAndSettle(); // The ListView has scrolled to keep the TextField and cursor handle // visible. expect(scrollController.offset, 27.0); }); testWidgets('disabled state golden', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(text: 'lorem'); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: DecoratedBox( decoration: const BoxDecoration(color: Color(0xFFFFFFFF)), child: Center( child: SizedBox( width: 200, height: 200, child: RepaintBoundary( key: const ValueKey<int>(1), child: CupertinoTextField( controller: controller, enabled: false, ), ), ), ), ), ), ); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('text_field_test.disabled.png'), ); }); testWidgets( 'Can drag the left handle while the right handle remains off-screen', (WidgetTester tester) async { // Text is longer than textfield width. const String testValue = 'aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb'; final TextEditingController controller = TextEditingController(text: testValue); addTearDown(controller.dispose); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, scrollController: scrollController, ), ), ), ); // Double tap 'b' to show handles. final Offset bPos = textOffsetToPosition(tester, testValue.indexOf('b')); await tester.tapAt(bPos); await tester.pump(kDoubleTapTimeout ~/ 2); await tester.tapAt(bPos); await tester.pumpAndSettle(); final TextSelection selection = controller.selection; expect(selection.baseOffset, 28); expect(selection.extentOffset, testValue.length); // Move to the left edge. scrollController.jumpTo(0); await tester.pumpAndSettle(); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Left handle should appear between textfield's left and right position. final Offset textFieldLeftPosition = tester.getTopLeft(find.byType(CupertinoTextField)); expect(endpoints[0].point.dx - textFieldLeftPosition.dx, isPositive); final Offset textFieldRightPosition = tester.getTopRight(find.byType(CupertinoTextField)); expect(textFieldRightPosition.dx - endpoints[0].point.dx, isPositive); // Right handle should remain off-screen. expect(endpoints[1].point.dx - textFieldRightPosition.dx, isPositive); // Drag the left handle to the right by 25 offset. const int toOffset = 25; final double beforeScrollOffset = scrollController.offset; final Offset handlePos = endpoints[0].point + const Offset(-1.0, 1.0); final Offset newHandlePos = textOffsetToPosition(tester, toOffset); final TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: // On Apple platforms, dragging the base handle makes it the extent. expect(controller.selection.baseOffset, testValue.length); expect(controller.selection.extentOffset, toOffset); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection.baseOffset, toOffset); expect(controller.selection.extentOffset, testValue.length); } // The scroll area of text field should not move. expect(scrollController.offset, beforeScrollOffset); }, ); testWidgets( 'Can drag the right handle while the left handle remains off-screen', (WidgetTester tester) async { // Text is longer than textfield width. const String testValue = 'aaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbb'; final TextEditingController controller = TextEditingController(text: testValue); addTearDown(controller.dispose); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, scrollController: scrollController, ), ), ), ); // Double tap 'a' to show handles. final Offset aPos = textOffsetToPosition(tester, testValue.indexOf('a')); await tester.tapAt(aPos); await tester.pump(kDoubleTapTimeout ~/ 2); await tester.tapAt(aPos); await tester.pumpAndSettle(); final TextSelection selection = controller.selection; expect(selection.baseOffset, 0); expect(selection.extentOffset, 27); // Move to the right edge. scrollController.jumpTo(800); await tester.pumpAndSettle(); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); expect(endpoints.length, 2); // Right handle should appear between textfield's left and right position. final Offset textFieldLeftPosition = tester.getTopLeft(find.byType(CupertinoTextField)); expect(endpoints[1].point.dx - textFieldLeftPosition.dx, isPositive); final Offset textFieldRightPosition = tester.getTopRight(find.byType(CupertinoTextField)); expect(textFieldRightPosition.dx - endpoints[1].point.dx, isPositive); // Left handle should remain off-screen. expect(endpoints[0].point.dx, isNegative); // Drag the right handle to the left by 50 offset. const int toOffset = 50; final double beforeScrollOffset = scrollController.offset; final Offset handlePos = endpoints[1].point + const Offset(1.0, 1.0); final Offset newHandlePos = textOffsetToPosition(tester, toOffset); final TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, toOffset); // The scroll area of text field should not move. expect(scrollController.offset, beforeScrollOffset); }, ); group('Text selection toolbar', () { testWidgets('Collapsed selection works', (WidgetTester tester) async { tester.view.physicalSize = const Size(400, 400); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); EditableText.debugDeterministicCursor = true; TextEditingController controller; EditableTextState state; Offset bottomLeftSelectionPosition; controller = TextEditingController(text: 'a'); // Top left collapsed selection. The toolbar should flip vertically, and // the arrow should not point exactly to the caret because the caret is // too close to the left. await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( alignment: Alignment.topLeft, child: SizedBox( width: 200, height: 200, child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ), ); state = tester.state<EditableTextState>(find.byType(EditableText)); final double lineHeight = state.renderEditable.preferredLineHeight; state.renderEditable.selectPositionAt(from: textOffsetToPosition(tester, 0), cause: SelectionChangedCause.tap); expect(state.showToolbar(), true); await tester.pumpAndSettle(); bottomLeftSelectionPosition = textOffsetToBottomLeftPosition(tester, 0); expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathPointsMatcher( excludes: <Offset> [ // Arrow should not point to the selection handle. bottomLeftSelectionPosition.translate(0, 8 + 0.1), ], includes: <Offset> [ // Expected center of the arrow. The arrow should stay clear of // the edges of the selection toolbar. Offset(26.0, bottomLeftSelectionPosition.dy + 8.0 + 0.1), ], ), ), ); expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathBoundsMatcher( topMatcher: moreOrLessEquals(bottomLeftSelectionPosition.dy + 8, epsilon: 0.01), leftMatcher: moreOrLessEquals(8), rightMatcher: lessThanOrEqualTo(400 - 8), bottomMatcher: moreOrLessEquals(bottomLeftSelectionPosition.dy + 8 + 44, epsilon: 0.01), ), ), ); // Top Right collapsed selection. The toolbar should flip vertically, and // the arrow should not point exactly to the caret because the caret is // too close to the right. controller.dispose(); controller = TextEditingController(text: 'a' * 200); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( alignment: Alignment.topRight, child: SizedBox( width: 200, height: 200, child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ), ); state = tester.state<EditableTextState>(find.byType(EditableText)); state.renderEditable.selectPositionAt( from: tester.getTopRight(find.byType(CupertinoApp)), cause: SelectionChangedCause.tap, ); await tester.pumpAndSettle(); // -1 because we want to reach the end of the line, not the start of a new line. bottomLeftSelectionPosition = textOffsetToBottomLeftPosition(tester, state.renderEditable.selection!.baseOffset - 1); expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathPointsMatcher( excludes: <Offset> [ // Arrow should not point to the selection handle. bottomLeftSelectionPosition.translate(0, 8 + 0.1), ], includes: <Offset> [ // Expected center of the arrow. Offset(400 - 26.0, bottomLeftSelectionPosition.dy + 8 + 0.1), ], ), ), ); expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathBoundsMatcher( topMatcher: moreOrLessEquals(bottomLeftSelectionPosition.dy + 8, epsilon: 0.01), rightMatcher: moreOrLessEquals(400.0 - 8), bottomMatcher: moreOrLessEquals(bottomLeftSelectionPosition.dy + 8 + 44, epsilon: 0.01), leftMatcher: greaterThanOrEqualTo(8), ), ), ); // Normal centered collapsed selection. The toolbar arrow should point down, and // it should point exactly to the caret. controller.dispose(); controller = TextEditingController(text: 'a' * 200); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: 200, height: 200, child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ), ); state = tester.state<EditableTextState>(find.byType(EditableText)); state.renderEditable.selectPositionAt( from: tester.getCenter(find.byType(EditableText)), cause: SelectionChangedCause.tap, ); await tester.pumpAndSettle(); bottomLeftSelectionPosition = textOffsetToBottomLeftPosition(tester, state.renderEditable.selection!.baseOffset); expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathPointsMatcher( includes: <Offset> [ // Expected center of the arrow. bottomLeftSelectionPosition.translate(0, -lineHeight - 8 - 0.1), ], ), ), ); expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathBoundsMatcher( bottomMatcher: moreOrLessEquals(bottomLeftSelectionPosition.dy - 8 - lineHeight, epsilon: 0.01), topMatcher: moreOrLessEquals(bottomLeftSelectionPosition.dy - 8 - lineHeight - 44, epsilon: 0.01), rightMatcher: lessThanOrEqualTo(400 - 8), leftMatcher: greaterThanOrEqualTo(8), ), ), ); }); testWidgets('selecting multiple words works', (WidgetTester tester) async { tester.view.physicalSize = const Size(400, 400); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); EditableText.debugDeterministicCursor = true; final TextEditingController controller; final EditableTextState state; // Normal multiword collapsed selection. The toolbar arrow should point down, and // it should point exactly to the caret. controller = TextEditingController(text: List<String>.filled(20, 'a').join(' ')); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: 200, height: 200, child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ), ); state = tester.state<EditableTextState>(find.byType(EditableText)); final double lineHeight = state.renderEditable.preferredLineHeight; // Select the first 2 words. state.renderEditable.selectPositionAt( from: textOffsetToPosition(tester, 0), to: textOffsetToPosition(tester, 4), cause: SelectionChangedCause.tap, ); expect(state.showToolbar(), true); await tester.pumpAndSettle(); final Offset selectionPosition = (textOffsetToBottomLeftPosition(tester, 0) + textOffsetToBottomLeftPosition(tester, 4)) / 2; expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathPointsMatcher( includes: <Offset> [ // Expected center of the arrow. selectionPosition.translate(0, -lineHeight - 8 - 0.1), ], ), ), ); expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathBoundsMatcher( bottomMatcher: moreOrLessEquals(selectionPosition.dy - 8 - lineHeight, epsilon: 0.01), topMatcher: moreOrLessEquals(selectionPosition.dy - 8 - lineHeight - 44, epsilon: 0.01), rightMatcher: lessThanOrEqualTo(400 - 8), leftMatcher: greaterThanOrEqualTo(8), ), ), ); }); testWidgets('selecting multiline works', (WidgetTester tester) async { tester.view.physicalSize = const Size(400, 400); tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); EditableText.debugDeterministicCursor = true; final TextEditingController controller; final EditableTextState state; // Normal multiline collapsed selection. The toolbar arrow should point down, and // it should point exactly to the horizontal center of the text field. controller = TextEditingController(text: List<String>.filled(20, 'a a ').join('\n')); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: 200, height: 200, child: CupertinoTextField( controller: controller, maxLines: null, ), ), ), ), ), ); state = tester.state<EditableTextState>(find.byType(EditableText)); final double lineHeight = state.renderEditable.preferredLineHeight; // Select the first 2 words. state.renderEditable.selectPositionAt( from: textOffsetToPosition(tester, 0), to: textOffsetToPosition(tester, 10), cause: SelectionChangedCause.tap, ); expect(state.showToolbar(), true); await tester.pumpAndSettle(); final Offset selectionPosition = Offset( // Toolbar should be centered. 200, textOffsetToBottomLeftPosition(tester, 0).dy, ); expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathPointsMatcher( includes: <Offset> [ // Expected center of the arrow. selectionPosition.translate(0, -lineHeight - 8 - 0.1), ], ), ), ); expect( find.byType(CupertinoTextSelectionToolbar), paints..clipPath( pathMatcher: PathBoundsMatcher( bottomMatcher: moreOrLessEquals(selectionPosition.dy - 8 - lineHeight, epsilon: 0.01), topMatcher: moreOrLessEquals(selectionPosition.dy - 8 - lineHeight - 44, epsilon: 0.01), rightMatcher: lessThanOrEqualTo(400 - 8), leftMatcher: greaterThanOrEqualTo(8), ), ), ); }); // This is a regression test for // https://github.com/flutter/flutter/issues/37046. testWidgets('No exceptions when showing selection menu inside of nested Navigators', (WidgetTester tester) async { const String testValue = '123456'; final TextEditingController controller = TextEditingController( text: testValue, ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: Center( child: Column( children: <Widget>[ Container( height: 100, color: CupertinoColors.black, ), Expanded( child: Navigator( onGenerateRoute: (_) => CupertinoPageRoute<void>( builder: (_) => CupertinoTextField( controller: controller, ), ), ), ), ], ), ), ), ), ); // No text selection toolbar. expect(find.byType(CupertinoTextSelectionToolbar), findsNothing); // Double tap on the text in the input. await tester.pumpAndSettle(); await tester.tapAt(textOffsetToPosition(tester, testValue.length ~/ 2)); await tester.pump(const Duration(milliseconds: 100)); await tester.tapAt(textOffsetToPosition(tester, testValue.length ~/ 2)); await tester.pumpAndSettle(); // Now the text selection toolbar is showing and there were no exceptions. expect(find.byType(CupertinoTextSelectionToolbar), findsOneWidget); expect(tester.takeException(), null); }); testWidgets('Drag selection hides the selection menu', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'blah1 blah2', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); // Initially, the menu is not shown and there is no selection. 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(); // The toolbar is shown. expect(find.text('Paste'), findsOneWidget); // Drag the mouse to the first word. final TestGesture gesture2 = await tester.startGesture( midBlah1, kind: PointerDeviceKind.mouse, ); await tester.pump(); await gesture2.moveTo(midBlah2); await tester.pump(); await gesture2.up(); await tester.pumpAndSettle(); // The toolbar is hidden. expect(find.text('Paste'), findsNothing); }, variant: TargetPlatformVariant.desktop()); }, skip: isContextMenuProvidedByPlatform); // [intended] only applies to platforms where we supply the context menu. group('textAlignVertical position', () { group('simple case', () { testWidgets('align top (default)', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Size size = Size(200.0, 200.0); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: size.width, height: size.height, child: CupertinoTextField( focusNode: focusNode, expands: true, maxLines: null, ), ), ), ), ), ); // Fills the whole container since expands is true. expect(tester.getSize(find.byType(CupertinoTextField)), size); // Tapping anywhere inside focuses it. expect(focusNode.hasFocus, false); await tester.tapAt(tester.getTopLeft(find.byType(CupertinoTextField))); await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, false); final Offset justInside = tester .getBottomLeft(find.byType(CupertinoTextField)) .translate(0.0, -1.0); await tester.tapAt(justInside); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 300)); expect(focusNode.hasFocus, true); // The EditableText is at the top. expect(tester.getTopLeft(find.byType(CupertinoTextField)).dy, moreOrLessEquals(size.height, epsilon: .0001)); expect(tester.getTopLeft(find.byType(EditableText)).dy, moreOrLessEquals(207.0, epsilon: .0001)); }); testWidgets('align center', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Size size = Size(200.0, 200.0); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: size.width, height: size.height, child: CupertinoTextField( textAlignVertical: TextAlignVertical.center, focusNode: focusNode, expands: true, maxLines: null, ), ), ), ), ), ); // Fills the whole container since expands is true. expect(tester.getSize(find.byType(CupertinoTextField)), size); // Tapping anywhere inside focuses it. expect(focusNode.hasFocus, false); await tester.tapAt(tester.getTopLeft(find.byType(CupertinoTextField))); await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, false); final Offset justInside = tester .getBottomLeft(find.byType(CupertinoTextField)) .translate(0.0, -1.0); await tester.tapAt(justInside); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 300)); expect(focusNode.hasFocus, true); // The EditableText is at the center. expect(tester.getTopLeft(find.byType(CupertinoTextField)).dy, moreOrLessEquals(size.height, epsilon: .0001)); expect(tester.getTopLeft(find.byType(EditableText)).dy, moreOrLessEquals(291.5, epsilon: .0001)); }); testWidgets('align bottom', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Size size = Size(200.0, 200.0); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: size.width, height: size.height, child: CupertinoTextField( textAlignVertical: TextAlignVertical.bottom, focusNode: focusNode, expands: true, maxLines: null, ), ), ), ), ), ); // Fills the whole container since expands is true. expect(tester.getSize(find.byType(CupertinoTextField)), size); // Tapping anywhere inside focuses it. expect(focusNode.hasFocus, false); await tester.tapAt(tester.getTopLeft(find.byType(CupertinoTextField))); await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, false); final Offset justInside = tester .getBottomLeft(find.byType(CupertinoTextField)) .translate(0.0, -1.0); await tester.tapAt(justInside); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 300)); expect(focusNode.hasFocus, true); // The EditableText is at the bottom. expect(tester.getTopLeft(find.byType(CupertinoTextField)).dy, moreOrLessEquals(size.height, epsilon: .0001)); expect(tester.getTopLeft(find.byType(EditableText)).dy, moreOrLessEquals(376.0, epsilon: .0001)); }); testWidgets('align as a double', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Size size = Size(200.0, 200.0); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: size.width, height: size.height, child: CupertinoTextField( textAlignVertical: const TextAlignVertical(y: 0.75), focusNode: focusNode, expands: true, maxLines: null, ), ), ), ), ), ); // Fills the whole container since expands is true. expect(tester.getSize(find.byType(CupertinoTextField)), size); // Tapping anywhere inside focuses it. expect(focusNode.hasFocus, false); await tester.tapAt(tester.getTopLeft(find.byType(CupertinoTextField))); await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, false); final Offset justInside = tester .getBottomLeft(find.byType(CupertinoTextField)) .translate(0.0, -1.0); await tester.tapAt(justInside); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 300)); expect(focusNode.hasFocus, true); // The EditableText is near the bottom. expect(tester.getTopLeft(find.byType(CupertinoTextField)).dy, moreOrLessEquals(size.height, epsilon: .0001)); expect(tester.getTopLeft(find.byType(EditableText)).dy, moreOrLessEquals(354.875, epsilon: .0001)); }); }); group('tall prefix', () { testWidgets('align center (default when prefix)', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Size size = Size(200.0, 200.0); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: size.width, height: size.height, child: CupertinoTextField( focusNode: focusNode, expands: true, maxLines: null, prefix: const SizedBox( height: 100, width: 10, ), ), ), ), ), ), ); // Fills the whole container since expands is true. expect(tester.getSize(find.byType(CupertinoTextField)), size); // Tapping anywhere inside focuses it. This includes tapping on the // prefix, because in this case it is transparent. expect(focusNode.hasFocus, false); await tester.tapAt(tester.getTopLeft(find.byType(CupertinoTextField))); await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, false); final Offset justInside = tester .getBottomLeft(find.byType(CupertinoTextField)) .translate(0.0, -1.0); await tester.tapAt(justInside); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 300)); expect(focusNode.hasFocus, true); // The EditableText is at the center. Same as without prefix. expect(tester.getTopLeft(find.byType(CupertinoTextField)).dy, moreOrLessEquals(size.height, epsilon: .0001)); expect(tester.getTopLeft(find.byType(EditableText)).dy, moreOrLessEquals(291.5, epsilon: .0001)); }); testWidgets('align top', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Size size = Size(200.0, 200.0); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: size.width, height: size.height, child: CupertinoTextField( textAlignVertical: TextAlignVertical.top, focusNode: focusNode, expands: true, maxLines: null, prefix: const SizedBox( height: 100, width: 10, ), ), ), ), ), ), ); // Fills the whole container since expands is true. expect(tester.getSize(find.byType(CupertinoTextField)), size); // Tapping anywhere inside focuses it. This includes tapping on the // prefix, because in this case it is transparent. expect(focusNode.hasFocus, false); await tester.tapAt(tester.getTopLeft(find.byType(CupertinoTextField))); await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, false); final Offset justInside = tester .getBottomLeft(find.byType(CupertinoTextField)) .translate(0.0, -1.0); await tester.tapAt(justInside); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 300)); expect(focusNode.hasFocus, true); // The prefix is at the top, and the EditableText is centered within its // height. expect(tester.getTopLeft(find.byType(CupertinoTextField)).dy, moreOrLessEquals(size.height, epsilon: .0001)); expect(tester.getTopLeft(find.byType(EditableText)).dy, moreOrLessEquals(241.5, epsilon: .0001)); }); testWidgets('align bottom', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Size size = Size(200.0, 200.0); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: size.width, height: size.height, child: CupertinoTextField( textAlignVertical: TextAlignVertical.bottom, focusNode: focusNode, expands: true, maxLines: null, prefix: const SizedBox( height: 100, width: 10, ), ), ), ), ), ), ); // Fills the whole container since expands is true. expect(tester.getSize(find.byType(CupertinoTextField)), size); // Tapping anywhere inside focuses it. This includes tapping on the // prefix, because in this case it is transparent. expect(focusNode.hasFocus, false); await tester.tapAt(tester.getTopLeft(find.byType(CupertinoTextField))); await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, false); final Offset justInside = tester .getBottomLeft(find.byType(CupertinoTextField)) .translate(0.0, -1.0); await tester.tapAt(justInside); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 300)); expect(focusNode.hasFocus, true); // The prefix is at the bottom, and the EditableText is centered within // its height. expect(tester.getTopLeft(find.byType(CupertinoTextField)).dy, moreOrLessEquals(size.height, epsilon: .0001)); expect(tester.getTopLeft(find.byType(EditableText)).dy, moreOrLessEquals(341.5, epsilon: .0001)); }); testWidgets('align as a double', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); const Size size = Size(200.0, 200.0); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: size.width, height: size.height, child: CupertinoTextField( textAlignVertical: const TextAlignVertical(y: 0.75), focusNode: focusNode, expands: true, maxLines: null, prefix: const SizedBox( height: 100, width: 10, ), ), ), ), ), ), ); // Fills the whole container since expands is true. expect(tester.getSize(find.byType(CupertinoTextField)), size); // Tapping anywhere inside focuses it. This includes tapping on the // prefix, because in this case it is transparent. expect(focusNode.hasFocus, false); await tester.tapAt(tester.getTopLeft(find.byType(CupertinoTextField))); await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, false); final Offset justInside = tester .getBottomLeft(find.byType(CupertinoTextField)) .translate(0.0, -1.0); await tester.tapAt(justInside); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 300)); expect(focusNode.hasFocus, true); // The EditableText is near the bottom. expect(tester.getTopLeft(find.byType(CupertinoTextField)).dy, moreOrLessEquals(size.height, epsilon: .0001)); expect(tester.getTopLeft(find.byType(EditableText)).dy, moreOrLessEquals(329.0, epsilon: .0001)); }); }); testWidgets( 'Long press on an autofocused field shows the selection menu', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField( autofocus: true, ), ), ), ), ); // This extra pump allows the selection set by autofocus to propagate to // the RenderEditable. await tester.pump(); // Long press shows the selection menu. await tester.longPressAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(); expect(find.text('Paste'), isContextMenuProvidedByPlatform ? findsNothing : findsOneWidget); }, ); }); testWidgets("Arrow keys don't move input focus", (WidgetTester tester) async { final TextEditingController controller1 = TextEditingController(); final TextEditingController controller2 = TextEditingController(); final TextEditingController controller3 = TextEditingController(); final TextEditingController controller4 = TextEditingController(); final TextEditingController controller5 = TextEditingController(); final FocusNode focusNode1 = FocusNode(debugLabel: 'Field 1'); final FocusNode focusNode2 = FocusNode(debugLabel: 'Field 2'); final FocusNode focusNode3 = FocusNode(debugLabel: 'Field 3'); final FocusNode focusNode4 = FocusNode(debugLabel: 'Field 4'); final FocusNode focusNode5 = FocusNode(debugLabel: 'Field 5'); addTearDown(focusNode1.dispose); addTearDown(focusNode2.dispose); addTearDown(focusNode3.dispose); addTearDown(focusNode4.dispose); addTearDown(focusNode5.dispose); addTearDown(controller1.dispose); addTearDown(controller2.dispose); addTearDown(controller3.dispose); addTearDown(controller4.dispose); addTearDown(controller5.dispose); // Lay out text fields in a "+" formation, and focus the center one. await tester.pumpWidget(CupertinoApp( home: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox( width: 100.0, child: CupertinoTextField( controller: controller1, focusNode: focusNode1, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox( width: 100.0, child: CupertinoTextField( controller: controller2, focusNode: focusNode2, ), ), SizedBox( width: 100.0, child: CupertinoTextField( controller: controller3, focusNode: focusNode3, ), ), SizedBox( width: 100.0, child: CupertinoTextField( controller: controller4, focusNode: focusNode4, ), ), ], ), SizedBox( width: 100.0, child: CupertinoTextField( controller: controller5, focusNode: focusNode5, ), ), ], ), ), ), ); focusNode3.requestFocus(); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); expect(focusNode3.hasPrimaryFocus, isTrue); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Scrolling shortcuts are disabled in text fields', (WidgetTester tester) async { bool scrollInvoked = false; await tester.pumpWidget( CupertinoApp( home: Actions( actions: <Type, Action<Intent>>{ ScrollIntent: CallbackAction<ScrollIntent>(onInvoke: (Intent intent) { scrollInvoked = true; return null; }), }, child: ListView( children: const <Widget>[ Padding(padding: EdgeInsets.symmetric(vertical: 200)), CupertinoTextField(), Padding(padding: EdgeInsets.symmetric(vertical: 800)), ], ), ), ), ); await tester.pump(); expect(scrollInvoked, isFalse); // Set focus on the text field. await tester.tapAt(tester.getTopLeft(find.byType(CupertinoTextField))); await tester.sendKeyEvent(LogicalKeyboardKey.space); expect(scrollInvoked, isFalse); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); expect(scrollInvoked, isFalse); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Cupertino text field semantics', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField(), ), ), ), ); expect( tester.getSemantics( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(Semantics), ).first, ), matchesSemantics( isTextField: true, isEnabled: true, hasEnabledState: true, hasTapAction: true, ), ); }); testWidgets('Disabled Cupertino text field semantics', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField( enabled: false, ), ), ), ), ); expect( tester.getSemantics( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(Semantics), ).first, ), matchesSemantics( hasEnabledState: true, isTextField: true, isReadOnly: true, ), ); }); testWidgets('Cupertino text field clear button semantics', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField( clearButtonMode: OverlayVisibilityMode.always, ), ), ), ), ); expect(find.bySemanticsLabel('Clear'), findsOneWidget); expect( tester.getSemantics( find.bySemanticsLabel('Clear').first, ), matchesSemantics( isButton: true, hasTapAction: true, label: 'Clear' ), ); }); testWidgets('Cupertino text field clear semantic label', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(200, 200)), child: const CupertinoTextField( clearButtonMode: OverlayVisibilityMode.always, clearButtonSemanticLabel: 'Delete Text' ), ), ), ), ); expect(find.bySemanticsLabel('Clear'), findsNothing); expect(find.bySemanticsLabel('Delete Text'), findsOneWidget); expect( tester.getSemantics( find.bySemanticsLabel('Delete Text').first, ), matchesSemantics( isButton: true, hasTapAction: true, label: 'Delete Text' ), ); }); testWidgets('text selection style 1', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure\nhi\nwassssup!', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: RepaintBoundary( child: Container( width: 650.0, height: 600.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: Column( children: <Widget>[ CupertinoTextField( autofocus: true, key: const Key('field0'), controller: controller, style: const TextStyle(height: 4, color: ui.Color.fromARGB(100, 0, 0, 0)), toolbarOptions: const ToolbarOptions(selectAll: true), selectionHeightStyle: ui.BoxHeightStyle.includeLineSpacingTop, selectionWidthStyle: ui.BoxWidthStyle.max, maxLines: 3, ), ], ), ), ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); final Offset textFieldStart = tester.getTopLeft(find.byKey(const Key('field0'))); await tester.longPressAt(textFieldStart + const Offset(50.0, 2.0)); await tester.pumpAndSettle(const Duration(milliseconds: 150)); // Tap the Select All button. await tester.tapAt(textFieldStart + const Offset(20.0, 100.0)); await tester.pump(const Duration(milliseconds: 300)); await expectLater( find.byType(CupertinoApp), matchesGoldenFile('text_field_golden.TextSelectionStyle.1.png'), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), skip: kIsWeb, // [intended] the web has its own Select All. ); testWidgets('text selection style 2', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure\nhi\nwassssup!', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: RepaintBoundary( child: Container( width: 650.0, height: 600.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: Column( children: <Widget>[ CupertinoTextField( autofocus: true, key: const Key('field0'), controller: controller, style: const TextStyle(height: 4, color: ui.Color.fromARGB(100, 0, 0, 0)), toolbarOptions: const ToolbarOptions(selectAll: true), selectionHeightStyle: ui.BoxHeightStyle.includeLineSpacingBottom, maxLines: 3, ), ], ), ), ), ), ), ); // This extra pump is so autofocus can propagate to renderEditable. await tester.pump(); final Offset textFieldStart = tester.getTopLeft(find.byKey(const Key('field0'))); await tester.longPressAt(textFieldStart + const Offset(50.0, 2.0)); await tester.pumpAndSettle(const Duration(milliseconds: 150)); // Tap the Select All button. await tester.tapAt(textFieldStart + const Offset(20.0, 100.0)); await tester.pump(const Duration(milliseconds: 300)); await expectLater( find.byType(CupertinoApp), matchesGoldenFile('text_field_golden.TextSelectionStyle.2.png'), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), skip: kIsWeb, // [intended] the web has its own Select All. ); testWidgets('textSelectionControls is passed to EditableText', (WidgetTester tester) async { final MockTextSelectionControls selectionControl = MockTextSelectionControls(); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( selectionControls: selectionControl, ), ), ), ); final EditableText widget = tester.widget(find.byType(EditableText)); expect(widget.selectionControls, equals(selectionControl)); }); testWidgets('Do not add LengthLimiting formatter to the user supplied list', (WidgetTester tester) async { final List<TextInputFormatter> formatters = <TextInputFormatter>[]; await tester.pumpWidget( CupertinoApp( home: CupertinoTextField(maxLength: 5, inputFormatters: formatters), ), ); expect(formatters.isEmpty, isTrue); }); group('MaxLengthEnforcement', () { const int maxLength = 5; Future<void> setupWidget( WidgetTester tester, MaxLengthEnforcement? enforcement, ) async { final Widget widget = CupertinoApp( home: Center( child: CupertinoTextField( maxLength: maxLength, maxLengthEnforcement: enforcement, ), ), ); await tester.pumpWidget(widget); await tester.pumpAndSettle(); } testWidgets('using none enforcement.', (WidgetTester tester) async { const MaxLengthEnforcement enforcement = MaxLengthEnforcement.none; await setupWidget(tester, enforcement); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.text, 'abc'); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 3, end: 6))); expect(state.currentTextEditingValue.text, 'abcdef'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 6)); state.updateEditingValue(const TextEditingValue(text: 'abcdef')); expect(state.currentTextEditingValue.text, 'abcdef'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); testWidgets('using enforced.', (WidgetTester tester) async { const MaxLengthEnforcement enforcement = MaxLengthEnforcement.enforced; await setupWidget(tester, enforcement); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.text, 'abc'); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 3, end: 6))); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); state.updateEditingValue(const TextEditingValue(text: 'abcdef')); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); }); testWidgets('using truncateAfterCompositionEnds.', (WidgetTester tester) async { const MaxLengthEnforcement enforcement = MaxLengthEnforcement.truncateAfterCompositionEnds; await setupWidget(tester, enforcement); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'abc')); expect(state.currentTextEditingValue.text, 'abc'); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 3, end: 6))); expect(state.currentTextEditingValue.text, 'abcdef'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 6)); state.updateEditingValue(const TextEditingValue(text: 'abcdef')); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); testWidgets('using default behavior for different platforms.', (WidgetTester tester) async { await setupWidget(tester, null); final EditableTextState state = tester.state(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: '侬好啊')); expect(state.currentTextEditingValue.text, '侬好啊'); expect(state.currentTextEditingValue.composing, TextRange.empty); state.updateEditingValue(const TextEditingValue(text: '侬好啊旁友', composing: TextRange(start: 3, end: 5))); expect(state.currentTextEditingValue.text, '侬好啊旁友'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); state.updateEditingValue(const TextEditingValue(text: '侬好啊旁友们', composing: TextRange(start: 3, end: 6))); if (kIsWeb || defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.linux || defaultTargetPlatform == TargetPlatform.fuchsia ) { expect(state.currentTextEditingValue.text, '侬好啊旁友们'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 6)); } else { expect(state.currentTextEditingValue.text, '侬好啊旁友'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); } state.updateEditingValue(const TextEditingValue(text: '侬好啊旁友')); expect(state.currentTextEditingValue.text, '侬好啊旁友'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); }); testWidgets('disabled widget changes background color', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( enabled: false, ), ), ), ); BoxDecoration decoration = tester .widget<DecoratedBox>( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(DecoratedBox), ), ) .decoration as BoxDecoration; expect( decoration.color!.value, 0xFFFAFAFA, ); await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField(), ), ), ); decoration = tester .widget<DecoratedBox>( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(DecoratedBox), ), ) .decoration as BoxDecoration; expect( decoration.color!.value, CupertinoColors.white.value, ); await tester.pumpWidget( const CupertinoApp( theme: CupertinoThemeData( brightness: Brightness.dark, ), home: Center( child: CupertinoTextField( enabled: false, ), ), ), ); decoration = tester .widget<DecoratedBox>( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(DecoratedBox), ), ) .decoration as BoxDecoration; expect( decoration.color!.value, 0xFF050505, ); }); // Regression test for https://github.com/flutter/flutter/issues/78097. testWidgets( 'still gets disabled background color when decoration is null', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( decoration: null, enabled: false, ), ), ), ); final Color disabledColor = tester.widget<ColoredBox>( find.descendant( of: find.byType(CupertinoTextField), matching: find.byType(ColoredBox), ), ).color; expect(disabledColor, isSameColorAs(const Color(0xFFFAFAFA))); }, ); testWidgets('autofill info has placeholder text', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: CupertinoTextField( placeholder: 'placeholder text', ), ), ); await tester.tap(find.byType(CupertinoTextField)); expect( tester.testTextInput.setClientArgs?['autofill'], containsPair('hintText', 'placeholder text'), ); }); testWidgets('textDirection is passed to EditableText', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( textDirection: TextDirection.ltr, ), ), ), ); final EditableText ltrWidget = tester.widget(find.byType(EditableText)); expect(ltrWidget.textDirection, TextDirection.ltr); await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoTextField( textDirection: TextDirection.rtl, ), ), ), ); final EditableText rtlWidget = tester.widget(find.byType(EditableText)); expect(rtlWidget.textDirection, TextDirection.rtl); }); testWidgets('clipBehavior has expected defaults', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: CupertinoTextField( ), ), ); final CupertinoTextField textField = tester.firstWidget(find.byType(CupertinoTextField)); expect(textField.clipBehavior, Clip.hardEdge); }); testWidgets('Overflow clipBehavior none golden', (WidgetTester tester) async { final OverflowWidgetTextEditingController controller = OverflowWidgetTextEditingController(); addTearDown(controller.dispose); final Widget widget = CupertinoApp( home: RepaintBoundary( key: const ValueKey<int>(1), child: SizedBox( height: 200.0, width: 200.0, child: Center( child: SizedBox( // Make sure the input field is not high enough for the WidgetSpan. height: 50, child: CupertinoTextField( controller: controller, clipBehavior: Clip.none, ), ), ), ), ), ); await tester.pumpWidget(widget); final CupertinoTextField textField = tester.firstWidget(find.byType(CupertinoTextField)); expect(textField.clipBehavior, Clip.none); final EditableText editableText = tester.firstWidget(find.byType(EditableText)); expect(editableText.clipBehavior, Clip.none); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('overflow_clipbehavior_none.cupertino.0.png'), ); }); testWidgets('can shift + tap to select with a keyboard (Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); await tester.tapAt(textOffsetToPosition(tester, 13)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 13); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.tapAt(textOffsetToPosition(tester, 20)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 20); await tester.pump(kDoubleTapTimeout); await tester.tapAt(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 23); await tester.pump(kDoubleTapTimeout); await tester.tapAt(textOffsetToPosition(tester, 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 4); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 4); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('can shift + tap to select with a keyboard (non-Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); await tester.tapAt(textOffsetToPosition(tester, 13)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 13); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.tapAt(textOffsetToPosition(tester, 20)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 20); await tester.pump(kDoubleTapTimeout); await tester.tapAt(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 23); await tester.pump(kDoubleTapTimeout); await tester.tapAt(textOffsetToPosition(tester, 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 4); await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 13); expect(controller.selection.extentOffset, 4); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows })); testWidgets('shift tapping an unfocused field', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, focusNode: focusNode, ), ), ), ); expect(focusNode.hasFocus, isFalse); // Put the cursor at the end of the field. await tester.tapAt(textOffsetToPosition(tester, controller.text.length)); await tester.pump(kDoubleTapTimeout); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); expect(controller.selection.baseOffset, 35); expect(controller.selection.extentOffset, 35); // Unfocus the field, but the selection remains. focusNode.unfocus(); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isFalse); expect(controller.selection.baseOffset, 35); expect(controller.selection.extentOffset, 35); // Shift tap in the middle of the field. await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.tapAt(textOffsetToPosition(tester, 20)); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); switch (defaultTargetPlatform) { // Apple platforms start the selection from 0. case TargetPlatform.iOS: case TargetPlatform.macOS: expect(controller.selection.baseOffset, 0); // Other platforms start from the previous selection. case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: expect(controller.selection.baseOffset, 35); } expect(controller.selection.extentOffset, 20); }, variant: TargetPlatformVariant.all()); testWidgets('can shift + tap + drag to select with a keyboard (Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); await tester.tapAt(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 23), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); if (isTargetPlatformIOS) { await gesture.up(); // Not a double tap + drag. await tester.pumpAndSettle(kDoubleTapTimeout); } expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Expand the selection a bit. if (isTargetPlatformIOS) { await gesture.down(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); } await gesture.moveTo(textOffsetToPosition(tester, 28)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 28); // Move back to the original selection. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Collapse the selection. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); // Invert the selection. The base jumps to the original extent. await gesture.moveTo(textOffsetToPosition(tester, 7)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 7); // Continuing to move in the inverted direction expands the selection. await gesture.moveTo(textOffsetToPosition(tester, 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 4); // Move back to the original base. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Continue to move past the original base, which will cause the selection // to invert back to the original orientation. await gesture.moveTo(textOffsetToPosition(tester, 9)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 9); // Continuing to select in this direction selects just like it did // originally. await gesture.moveTo(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); // Releasing the shift key has no effect; the selection continues as the // mouse continues to move. await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); await gesture.moveTo(textOffsetToPosition(tester, 26)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 26); await gesture.up(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 26); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('can shift + tap + drag to select with a keyboard (non-Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.fuchsia; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); await tester.tapAt(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 23), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); if (isTargetPlatformMobile) { await gesture.up(); // Not a double tap + drag. await tester.pumpAndSettle(kDoubleTapTimeout); } expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Expand the selection a bit. if (isTargetPlatformMobile) { await gesture.down(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); } await gesture.moveTo(textOffsetToPosition(tester, 28)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 28); // Move back to the original selection. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Collapse the selection. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); // Invert the selection. The original selection is not restored like on iOS // and Mac. await gesture.moveTo(textOffsetToPosition(tester, 7)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 7); // Continuing to move in the inverted direction expands the selection. await gesture.moveTo(textOffsetToPosition(tester, 4)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 4); // Move back to the original base. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 8); // Continue to move past the original base. await gesture.moveTo(textOffsetToPosition(tester, 9)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 9); // Continuing to select in this direction selects just like it did // originally. await gesture.moveTo(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); // Releasing the shift key has no effect; the selection continues as the // mouse continues to move. await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); await gesture.moveTo(textOffsetToPosition(tester, 26)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 26); await gesture.up(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 26); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.linux, TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.windows })); testWidgets('can shift + tap + drag to select with a keyboard, reversed (Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); final bool isTargetPlatformIOS = defaultTargetPlatform == TargetPlatform.iOS; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); // Make a selection from right to left. await tester.tapAt(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 8), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); if (isTargetPlatformIOS) { await gesture.up(); // Not a double tap + drag. await tester.pumpAndSettle(kDoubleTapTimeout); } await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Expand the selection a bit. if (isTargetPlatformIOS) { await gesture.down(textOffsetToPosition(tester, 7)); await tester.pumpAndSettle(); } await gesture.moveTo(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 5); // Move back to the original selection. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Collapse the selection. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); // Invert the selection. The base jumps to the original extent. await gesture.moveTo(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 24); // Continuing to move in the inverted direction expands the selection. await gesture.moveTo(textOffsetToPosition(tester, 27)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 27); // Move back to the original base. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 8); expect(controller.selection.extentOffset, 23); // Continue to move past the original base, which will cause the selection // to invert back to the original orientation. await gesture.moveTo(textOffsetToPosition(tester, 22)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 22); // Continuing to select in this direction selects just like it did // originally. await gesture.moveTo(textOffsetToPosition(tester, 16)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 16); // Releasing the shift key has no effect; the selection continues as the // mouse continues to move. await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 16); await gesture.moveTo(textOffsetToPosition(tester, 14)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 14); await gesture.up(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 14); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('can shift + tap + drag to select with a keyboard, reversed (non-Apple platforms)', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Atwater Peel Sherbrooke Bonaventure', ); addTearDown(controller.dispose); final bool isTargetPlatformMobile = defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.fuchsia; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); // Make a selection from right to left. await tester.tapAt(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); await tester.pump(kDoubleTapTimeout); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); final TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 8), pointer: 7, kind: PointerDeviceKind.mouse, ); await tester.pumpAndSettle(); if (isTargetPlatformMobile) { await gesture.up(); // Not a double tap + drag. await tester.pumpAndSettle(kDoubleTapTimeout); } expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Expand the selection a bit. if (isTargetPlatformMobile) { await gesture.down(textOffsetToPosition(tester, 7)); await tester.pumpAndSettle(); } await gesture.moveTo(textOffsetToPosition(tester, 5)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 5); // Move back to the original selection. await gesture.moveTo(textOffsetToPosition(tester, 8)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 8); // Collapse the selection. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); // Invert the selection. The selection is not restored like it would be on // iOS and Mac. await gesture.moveTo(textOffsetToPosition(tester, 24)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 24); // Continuing to move in the inverted direction expands the selection. await gesture.moveTo(textOffsetToPosition(tester, 27)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 27); // Move back to the original base. await gesture.moveTo(textOffsetToPosition(tester, 23)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 23); // Continue to move past the original base. await gesture.moveTo(textOffsetToPosition(tester, 22)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 22); // Continuing to select in this direction selects just like it did // originally. await gesture.moveTo(textOffsetToPosition(tester, 16)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 16); // Releasing the shift key has no effect; the selection continues as the // mouse continues to move. await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 16); await gesture.moveTo(textOffsetToPosition(tester, 14)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 14); await gesture.up(); expect(controller.selection.baseOffset, 23); expect(controller.selection.extentOffset, 14); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.linux, TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.windows })); // 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( CupertinoApp( home: Center( child: CupertinoTextField( 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); } // 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); } }, variant: TargetPlatformVariant.all(), skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. ); group('Right click focus', () { testWidgets('Can right click to focus multiple times', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/103228 final FocusNode focusNode1 = FocusNode(); final FocusNode focusNode2 = FocusNode(); addTearDown(focusNode1.dispose); addTearDown(focusNode2.dispose); final UniqueKey key1 = UniqueKey(); final UniqueKey key2 = UniqueKey(); await tester.pumpWidget( CupertinoApp( home: Column( children: <Widget>[ CupertinoTextField( key: key1, focusNode: focusNode1, ), // This spacer prevents the context menu in one field from // overlapping with the other field. const SizedBox(height: 100.0), CupertinoTextField( key: key2, focusNode: focusNode2, ), ], ), ), ); // Interact with the field to establish the input connection. await tester.tapAt( tester.getCenter(find.byKey(key1)), buttons: kSecondaryMouseButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); await tester.tapAt( tester.getCenter(find.byKey(key2)), buttons: kSecondaryMouseButton, ); await tester.pump(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isTrue); await tester.tapAt( tester.getCenter(find.byKey(key1)), buttons: kSecondaryMouseButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); }); testWidgets('Can right click to focus on previously selected word on Apple platforms', (WidgetTester tester) async { final FocusNode focusNode1 = FocusNode(); final FocusNode focusNode2 = FocusNode(); addTearDown(focusNode1.dispose); addTearDown(focusNode2.dispose); final TextEditingController controller = TextEditingController( text: 'first second', ); addTearDown(controller.dispose); final UniqueKey key1 = UniqueKey(); await tester.pumpWidget( CupertinoApp( home: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CupertinoTextField( key: key1, controller: controller, focusNode: focusNode1, ), Focus( focusNode: focusNode2, child: const Text('focusable'), ), ], ), ), ); // Interact with the field to establish the input connection. await tester.tapAt( tester.getCenter(find.byKey(key1)), buttons: kSecondaryMouseButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); // Select the second word. controller.selection = const TextSelection( baseOffset: 6, extentOffset: 12, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect(controller.selection.isCollapsed, isFalse); expect(controller.selection.baseOffset, 6); expect(controller.selection.extentOffset, 12); // Unfocus the first field. focusNode2.requestFocus(); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isTrue); // Right click the second word in the first field, which is still selected // even though the selection is not visible. await tester.tapAt( textOffsetToPosition(tester, 8), buttons: kSecondaryMouseButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect(controller.selection.baseOffset, 6); expect(controller.selection.extentOffset, 12); // Select everything. controller.selection = const TextSelection( baseOffset: 0, extentOffset: 12, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 12); // Unfocus the first field. focusNode2.requestFocus(); await tester.pumpAndSettle(); // Right click the first word in the first field. await tester.tapAt( textOffsetToPosition(tester, 2), buttons: kSecondaryMouseButton, ); await tester.pump(); expect(focusNode1.hasFocus, isTrue); expect(focusNode2.hasFocus, isFalse); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 5); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); }); group('context menu', () { testWidgets('builds CupertinoAdaptiveTextSelectionToolbar by default', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(text: ''); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CupertinoTextField( controller: controller, ), ], ), ), ); await tester.pump(); // Wait for autofocus to take effect. expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing); // Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsOneWidget); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); testWidgets('contextMenuBuilder is used in place of the default text selection toolbar', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final TextEditingController controller = TextEditingController(text: ''); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ CupertinoTextField( controller: controller, contextMenuBuilder: ( BuildContext context, EditableTextState editableTextState, ) { return Placeholder(key: key); }, ), ], ), ), ); await tester.pump(); // Wait for autofocus to take effect. expect(find.byKey(key), findsNothing); // Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle(); expect(find.byKey(key), findsOneWidget); }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); }); group('magnifier', () { late ValueNotifier<MagnifierInfo> magnifierInfo; final Widget fakeMagnifier = Container(key: UniqueKey()); group('magnifier builder', () { testWidgets('should build custom magnifier if given', (WidgetTester tester) async { final Widget customMagnifier = Container( key: UniqueKey(), ); final CupertinoTextField defaultCupertinoTextField = CupertinoTextField( magnifierConfiguration: TextMagnifierConfiguration(magnifierBuilder: (_, __, ___) => customMagnifier), ); await tester.pumpWidget(const CupertinoApp( home: Placeholder(), )); final BuildContext context = tester.firstElement(find.byType(Placeholder)); final ValueNotifier<MagnifierInfo> magnifierInfo = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); addTearDown(magnifierInfo.dispose); expect( defaultCupertinoTextField.magnifierConfiguration!.magnifierBuilder( context, MagnifierController(), magnifierInfo, ), isA<Widget>().having((Widget widget) => widget.key, 'key', equals(customMagnifier.key))); }); group('defaults', () { testWidgets('should build CupertinoMagnifier on iOS and Android', (WidgetTester tester) async { await tester.pumpWidget(const CupertinoApp( home: CupertinoTextField(), )); final BuildContext context = tester.firstElement(find.byType(CupertinoTextField)); final EditableText editableText = tester.widget(find.byType(EditableText)); final ValueNotifier<MagnifierInfo> magnifierInfo = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); addTearDown(magnifierInfo.dispose); expect( editableText.magnifierConfiguration.magnifierBuilder( context, MagnifierController(), magnifierInfo, ), isA<CupertinoTextMagnifier>()); }, variant: const TargetPlatformVariant( <TargetPlatform>{TargetPlatform.iOS, TargetPlatform.android})); }); testWidgets('should build nothing on all platforms but iOS and Android', (WidgetTester tester) async { await tester.pumpWidget(const CupertinoApp( home: CupertinoTextField(), )); final BuildContext context = tester.firstElement(find.byType(CupertinoTextField)); final EditableText editableText = tester.widget(find.byType(EditableText)); final ValueNotifier<MagnifierInfo> magnifierInfo = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); addTearDown(magnifierInfo.dispose); expect( editableText.magnifierConfiguration.magnifierBuilder( context, MagnifierController(), magnifierInfo, ), isNull); }, variant: TargetPlatformVariant.all( excluding: <TargetPlatform>{TargetPlatform.iOS, TargetPlatform.android})); }); testWidgets('Can drag handles to show, unshow, and update magnifier', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: Builder( builder: (BuildContext context) => CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: (_, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }), ), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); // Double tap the 'e' to select 'def'. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(const Duration(milliseconds: 30)); await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(const Duration(milliseconds: 30)); final TextSelection selection = controller.selection; final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(selection), renderEditable, ); // Drag the right handle 2 letters to the right. final Offset handlePos = endpoints.last.point + const Offset(1.0, 1.0); final TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); Offset? firstDragGesturePosition; await gesture.moveTo(textOffsetToPosition(tester, testValue.length - 2)); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); firstDragGesturePosition = magnifierInfo.value.globalGesturePosition; await gesture.moveTo(textOffsetToPosition(tester, testValue.length)); await tester.pump(); // Expect the position the magnifier gets to have moved. expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); await gesture.up(); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsNothing); }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); testWidgets('Can drag to show, unshow, and update magnifier', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: ( _, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo ) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(); // Tap at '|a' to move the selection to position 0. await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pumpAndSettle(kDoubleTapTimeout); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); expect(find.byKey(fakeMagnifier.key!), findsNothing); // Start a drag gesture to move the selection to the dragged position, showing // the magnifier. final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, 0)); await tester.pump(); await gesture.moveTo(textOffsetToPosition(tester, 5)); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 5); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); Offset firstDragGesturePosition = magnifierInfo.value.globalGesturePosition; await gesture.moveTo(textOffsetToPosition(tester, 10)); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 10); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); // Expect the position the magnifier gets to have moved. expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); // The magnifier should hide when the drag ends. await gesture.up(); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 10); expect(find.byKey(fakeMagnifier.key!), findsNothing); // Start a double-tap select the word at the tapped position. await gesture.down(textOffsetToPosition(tester, 1)); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(tester, 1)); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 3); // Start a drag gesture to extend the selection word-by-word, showing the // magnifier. await gesture.moveTo(textOffsetToPosition(tester, 5)); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 7); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); firstDragGesturePosition = magnifierInfo.value.globalGesturePosition; await gesture.moveTo(textOffsetToPosition(tester, 10)); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 11); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); // Expect the position the magnifier gets to have moved. expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); // The magnifier should hide when the drag ends. await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 11); expect(find.byKey(fakeMagnifier.key!), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); testWidgets('Can long press to show, unshow, and update magnifier on non-Apple platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final bool isTargetPlatformAndroid = defaultTargetPlatform == TargetPlatform.android; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: ( _, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo ) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(); // Tap at 'e' to move the cursor before the 'e'. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pumpAndSettle(const Duration(milliseconds: 300)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, isTargetPlatformAndroid ? 5 : 4); expect(find.byKey(fakeMagnifier.key!), findsNothing); // Long press the 'e' to select 'def' and show the magnifier. final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 7); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); final Offset firstLongPressGesturePosition = magnifierInfo.value.globalGesturePosition; // Move the gesture to 'h' to extend the selection to 'ghi'. await gesture.moveTo(textOffsetToPosition(tester, testValue.indexOf('h'))); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 11); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); // Expect the position the magnifier gets to have moved. expect(firstLongPressGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); // End the long press to hide the magnifier. await gesture.up(); await tester.pumpAndSettle(); expect(find.byKey(fakeMagnifier.key!), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android })); testWidgets('Can long press to show, unshow, and update magnifier on iOS', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final bool isTargetPlatformAndroid = defaultTargetPlatform == TargetPlatform.android; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: ( _, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo ) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ), ), ), ), ); const String testValue = 'abc def ghi'; await tester.enterText(find.byType(CupertinoTextField), testValue); await tester.pumpAndSettle(); // Tap at 'e' to set the selection to position 5 on Android. // Tap at 'e' to set the selection to the closest word edge, which is position 4 on iOS. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pumpAndSettle(const Duration(milliseconds: 300)); expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, isTargetPlatformAndroid ? 5 : 7); expect(find.byKey(fakeMagnifier.key!), findsNothing); // Long press the 'e' to move the cursor in front of the 'e' and show the magnifier. final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); expect(controller.selection.baseOffset, 5); expect(controller.selection.extentOffset, 5); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); final Offset firstLongPressGesturePosition = magnifierInfo.value.globalGesturePosition; // Move the gesture to 'h' to update the magnifier and move the cursor to 'h'. await gesture.moveTo(textOffsetToPosition(tester, testValue.indexOf('h'))); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 9); expect(controller.selection.extentOffset, 9); expect(find.byKey(fakeMagnifier.key!), findsOneWidget); // Expect the position the magnifier gets to have moved. expect(firstLongPressGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); // End the long press to hide the magnifier. await gesture.up(); await tester.pumpAndSettle(); expect(find.byKey(fakeMagnifier.key!), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); }); group('TapRegion integration', () { testWidgets('Tapping outside loses focus on desktop', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( width: 100, height: 100, child: CupertinoTextField( autofocus: true, focusNode: focusNode, ), ), ), ), ); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); // Tap outside the border. await tester.tapAt(const Offset(10, 10)); await tester.pump(); expect(focusNode.hasPrimaryFocus, isFalse); }, variant: TargetPlatformVariant.desktop()); testWidgets("Tapping outside doesn't lose focus on mobile", (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( width: 100, height: 100, child: CupertinoTextField( autofocus: true, focusNode: focusNode, ), ), ), ), ); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); // Tap just outside the border, but not inside the EditableText. await tester.tapAt(const Offset(10, 10)); await tester.pump(); // Focus is lost on mobile browsers, but not mobile apps. expect(focusNode.hasPrimaryFocus, kIsWeb ? isFalse : isTrue); }, variant: TargetPlatformVariant.mobile()); testWidgets("tapping on toolbar doesn't lose focus", (WidgetTester tester) async { final TextEditingController controller; final EditableTextState state; controller = TextEditingController(text: 'A B C'); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: Align( child: SizedBox( width: 200, height: 200, child: CupertinoTextField( autofocus: true, focusNode: focusNode, controller: controller, ), ), ), ), ), ); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); state = tester.state<EditableTextState>(find.byType(EditableText)); // Select the first 2 words. state.renderEditable.selectPositionAt( from: textOffsetToPosition(tester, 0), to: textOffsetToPosition(tester, 2), cause: SelectionChangedCause.tap, ); final Offset midSelection = textOffsetToPosition(tester, 2); // Right click the selection. final TestGesture gesture = await tester.startGesture( midSelection, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(find.text('Copy'), findsOneWidget); // Copy the first word. await tester.tap(find.text('Copy')); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); }, variant: TargetPlatformVariant.all(), skip: kIsWeb, // [intended] The toolbar isn't rendered by Flutter on the web, it's rendered by the browser. ); testWidgets("Tapping on border doesn't lose focus", (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( width: 100, height: 100, child: CupertinoTextField( autofocus: true, focusNode: focusNode, ), ), ), ), ); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); final Rect borderBox = tester.getRect(find.byType(CupertinoTextField)); // Tap just inside the border, but not inside the EditableText. await tester.tapAt(borderBox.topLeft + const Offset(1, 1)); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); }, variant: TargetPlatformVariant.all()); }); testWidgets('Can drag handles to change selection correctly in multiline', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( debugShowCheckedModeBanner: false, home: CupertinoPageScaffold( child: CupertinoTextField( dragStartBehavior: DragStartBehavior.down, controller: controller, style: const TextStyle(color: Colors.black, fontSize: 34.0), maxLines: 3, ), ), ), ); const String testValue = 'First line of text is\n' 'Second line goes until\n' 'Third line of stuff'; const String cutValue = 'First line of text is\n' 'Second until\n' 'Third line of stuff'; await tester.enterText(find.byType(CupertinoTextField), testValue); // Skip past scrolling animation. await tester.pump(); await tester.pumpAndSettle(const Duration(milliseconds: 200)); // Check that the text spans multiple lines. final Offset firstPos = textOffsetToPosition(tester, testValue.indexOf('First')); final Offset secondPos = textOffsetToPosition(tester, testValue.indexOf('Second')); final Offset thirdPos = textOffsetToPosition(tester, testValue.indexOf('Third')); expect(firstPos.dx, secondPos.dx); expect(firstPos.dx, thirdPos.dx); expect(firstPos.dy, lessThan(secondPos.dy)); expect(secondPos.dy, lessThan(thirdPos.dy)); // Double tap on the 'n' in 'until' to select the word. final Offset untilPos = textOffsetToPosition(tester, testValue.indexOf('until')+1); await tester.tapAt(untilPos); await tester.pump(const Duration(milliseconds: 50)); await tester.tapAt(untilPos); await tester.pumpAndSettle(); // Skip past the frame where the opacity is zero. await tester.pump(const Duration(milliseconds: 200)); expect(controller.selection.baseOffset, 39); expect(controller.selection.extentOffset, 44); final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), renderEditable, ); expect(endpoints.length, 2); final Offset offsetFromEndPointToMiddlePoint = Offset(0.0, -renderEditable.preferredLineHeight / 2); // Drag the left handle to just after 'Second', still on the second line. Offset handlePos = endpoints[0].point + offsetFromEndPointToMiddlePoint; Offset newHandlePos = textOffsetToPosition(tester, testValue.indexOf('Second') + 6) + offsetFromEndPointToMiddlePoint; TestGesture gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 28); expect(controller.selection.extentOffset, 44); // Drag the right handle to just after 'goes', still on the second line. handlePos = endpoints[1].point + offsetFromEndPointToMiddlePoint; newHandlePos = textOffsetToPosition(tester, testValue.indexOf('goes') + 4) + offsetFromEndPointToMiddlePoint; gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(); await gesture.moveTo(newHandlePos); await tester.pump(); await gesture.up(); await tester.pump(); expect(controller.selection.baseOffset, 28); expect(controller.selection.extentOffset, 38); if (!isContextMenuProvidedByPlatform) { await tester.tap(find.text('Cut')); await tester.pump(); expect(controller.selection.isCollapsed, true); expect(controller.text, cutValue); } }); testWidgets('placeholder style overflow works', (WidgetTester tester) async { final String placeholder = 'hint text' * 20; const TextStyle placeholderStyle = TextStyle( fontSize: 14.0, overflow: TextOverflow.fade, ); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( placeholder: placeholder, placeholderStyle: placeholderStyle, ), ), ), ); await tester.pumpAndSettle(); final Finder placeholderFinder = find.text(placeholder); final Text placeholderWidget = tester.widget(placeholderFinder); expect(placeholderWidget.overflow, placeholderStyle.overflow); expect(placeholderWidget.style!.overflow, placeholderStyle.overflow); }); testWidgets('tapping on a misspelled word on iOS hides the handles and shows red selection', (WidgetTester tester) async { tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; // The default derived color for the iOS text selection highlight. const Color defaultSelectionColor = Color(0x33007aff); final TextEditingController controller = TextEditingController( text: 'test test testt', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: CupertinoTextField.cupertinoMisspelledTextStyle, spellCheckSuggestionsToolbarBuilder: CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, ), ), ), ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.spellCheckResults = SpellCheckResults( controller.value.text, const <SuggestionSpan>[ SuggestionSpan(TextRange(start: 10, end: 15), <String>['test']), ]); // Double tapping a non-misspelled word shows the normal blue selection and // the selection handles. expect(state.selectionOverlay, isNull); await tester.tapAt(textOffsetToPosition(tester, 2)); await tester.pump(const Duration(milliseconds: 50)); expect(state.selectionOverlay!.handlesAreVisible, isFalse); await tester.tapAt(textOffsetToPosition(tester, 2)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 0, extentOffset: 4), ); expect(state.selectionOverlay!.handlesAreVisible, isTrue); expect(state.renderEditable.selectionColor, defaultSelectionColor); // Single tapping a non-misspelled word shows a collapsed cursor. await tester.tapAt(textOffsetToPosition(tester, 7)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection.collapsed(offset: 9, affinity: TextAffinity.upstream), ); expect(state.selectionOverlay!.handlesAreVisible, isFalse); expect(state.renderEditable.selectionColor, defaultSelectionColor); // Single tapping a misspelled word selects it in red with no handles. await tester.tapAt(textOffsetToPosition(tester, 13)); await tester.pumpAndSettle(); expect( controller.selection, const TextSelection(baseOffset: 10, extentOffset: 15), ); expect(state.selectionOverlay!.handlesAreVisible, isFalse); expect( state.renderEditable.selectionColor, CupertinoTextField.kMisspelledSelectionColor, ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), skip: kIsWeb, // [intended] ); testWidgets('text selection toolbar is hidden on tap down on desktop platforms', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'blah1 blah2', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, ), ), ), ); expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing); TestGesture gesture = await tester.startGesture( textOffsetToPosition(tester, 8), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsOneWidget); gesture = await tester.startGesture( textOffsetToPosition(tester, 2), kind: PointerDeviceKind.mouse, ); await tester.pump(); // After the gesture is down but not up, the toolbar is already gone. expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing); await gesture.up(); await tester.pumpAndSettle(); expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing); }, skip: isContextMenuProvidedByPlatform, // [intended] only applies to platforms where we supply the context menu. variant: TargetPlatformVariant.all(excluding: TargetPlatformVariant.mobile().values), ); testWidgets('Does not shrink in height when enters text when there is large single-line placeholder', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/133241. final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Align( alignment: Alignment.topCenter, child: CupertinoTextField( placeholderStyle: const TextStyle(fontSize: 100), placeholder: 'p', controller: controller, ), ), ), ); final Rect rectWithPlaceholder = tester.getRect(find.byType(CupertinoTextField)); controller.value = const TextEditingValue(text: 'input'); await tester.pump(); final Rect rectWithText = tester.getRect(find.byType(CupertinoTextField)); expect(rectWithPlaceholder, rectWithText); }); testWidgets('Does not match the height of a multiline placeholder', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Align( alignment: Alignment.topCenter, child: CupertinoTextField( placeholderStyle: const TextStyle(fontSize: 100), placeholder: 'p' * 50, maxLines: null, controller: controller, ), ), ), ); final Rect rectWithPlaceholder = tester.getRect(find.byType(CupertinoTextField)); controller.value = const TextEditingValue(text: 'input'); await tester.pump(); final Rect rectWithText = tester.getRect(find.byType(CupertinoTextField)); // The text field is still top aligned. expect(rectWithPlaceholder.top, rectWithText.top); // But after entering text the text field should shrink since the // placeholder text is huge and multiline. expect(rectWithPlaceholder.height, greaterThan(rectWithText.height)); // But still should be taller than or the same height of the first line of // placeholder. expect(rectWithText.height, greaterThan(100)); }); testWidgets('Start the floating cursor on long tap', (WidgetTester tester) async { EditableText.debugDeterministicCursor = true; final TextEditingController controller = TextEditingController( text: 'abcd', ); addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: RepaintBoundary( key: const ValueKey<int>(1), child: CupertinoTextField( autofocus: true, controller: controller, ), ) ), ), ), ); // Wait for autofocus. await tester.pumpAndSettle(); final Offset textFieldCenter = tester.getCenter(find.byType(CupertinoTextField)); final TestGesture gesture = await tester.startGesture(textFieldCenter); await tester.pump(kLongPressTimeout); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('text_field_floating_cursor.regular_and_floating_both.cupertino.0.png'), ); await gesture.moveTo(Offset(10, textFieldCenter.dy)); await tester.pump(); await expectLater( find.byKey(const ValueKey<int>(1)), matchesGoldenFile('text_field_floating_cursor.only_floating_cursor.cupertino.0.png'), ); await gesture.up(); EditableText.debugDeterministicCursor = false; }, variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); }
flutter/packages/flutter/test/cupertino/text_field_test.dart/0
{ "file_path": "flutter/packages/flutter/test/cupertino/text_field_test.dart", "repo_id": "flutter", "token_count": 145850 }
704
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'capture_output.dart'; void main() { test('debugPrintStack', () { final List<String> log = captureOutput(() { debugPrintStack(label: 'Example label', maxFrames: 7); }); expect(log[0], contains('Example label')); expect(log[1], contains('debugPrintStack')); }); test('should show message of ErrorDescription', () { const String descriptionMessage = 'This is the message'; final ErrorDescription errorDescription = ErrorDescription(descriptionMessage); expect(errorDescription.toString(), descriptionMessage); }); test('debugPrintStack', () { final List<String> log = captureOutput(() { final FlutterErrorDetails details = FlutterErrorDetails( exception: 'Example exception', stack: StackTrace.current, library: 'Example library', context: ErrorDescription('Example context'), informationCollector: () sync* { yield ErrorDescription('Example information'); }, ); FlutterError.dumpErrorToConsole(details); }); expect(log[0], contains('EXAMPLE LIBRARY')); expect(log[1], contains('Example context')); expect(log[2], contains('Example exception')); final String joined = log.join('\n'); expect(joined, contains('captureOutput')); expect(joined, contains('\nExample information\n')); }); test('FlutterErrorDetails.toString', () { expect( FlutterErrorDetails( exception: 'MESSAGE', library: 'LIBRARY', context: ErrorDescription('CONTEXTING'), informationCollector: () sync* { yield ErrorDescription('INFO'); }, ).toString(), '══╡ EXCEPTION CAUGHT BY LIBRARY ╞════════════════════════════════\n' 'The following message was thrown CONTEXTING:\n' 'MESSAGE\n' '\n' 'INFO\n' '═════════════════════════════════════════════════════════════════\n', ); expect( FlutterErrorDetails( exception: 'MESSAGE', context: ErrorDescription('CONTEXTING'), informationCollector: () sync* { yield ErrorDescription('INFO'); }, ).toString(), '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' 'The following message was thrown CONTEXTING:\n' 'MESSAGE\n' '\n' 'INFO\n' '═════════════════════════════════════════════════════════════════\n', ); expect( FlutterErrorDetails( exception: 'MESSAGE', context: ErrorDescription('CONTEXTING ${'SomeContext(BlaBla)'}'), informationCollector: () sync* { yield ErrorDescription('INFO'); }, ).toString(), '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' 'The following message was thrown CONTEXTING SomeContext(BlaBla):\n' 'MESSAGE\n' '\n' 'INFO\n' '═════════════════════════════════════════════════════════════════\n', ); expect( const FlutterErrorDetails( exception: 'MESSAGE', ).toString(), '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' 'The following message was thrown:\n' 'MESSAGE\n' '═════════════════════════════════════════════════════════════════\n', ); }); test('FlutterErrorDetails.toStringShort', () { expect( FlutterErrorDetails( exception: 'MESSAGE', library: 'library', context: ErrorDescription('CONTEXTING'), informationCollector: () sync* { yield ErrorDescription('INFO'); }, ).toStringShort(), 'Exception caught by library', ); }); test('FlutterError default constructor', () { FlutterError error = FlutterError( 'My Error Summary.\n' 'My first description.\n' 'My second description.', ); expect(error.diagnostics.length, equals(3)); expect(error.diagnostics[0].level, DiagnosticLevel.summary); expect(error.diagnostics[1].level, DiagnosticLevel.info); expect(error.diagnostics[2].level, DiagnosticLevel.info); expect(error.diagnostics[0].toString(), 'My Error Summary.'); expect(error.diagnostics[1].toString(), 'My first description.'); expect(error.diagnostics[2].toString(), 'My second description.'); expect( error.toStringDeep(), 'FlutterError\n' ' My Error Summary.\n' ' My first description.\n' ' My second description.\n', ); error = FlutterError( 'My Error Summary.\n' 'My first description.\n' 'My second description.\n' '\n', ); expect(error.diagnostics.length, equals(5)); expect(error.diagnostics[0].level, DiagnosticLevel.summary); expect(error.diagnostics[1].level, DiagnosticLevel.info); expect(error.diagnostics[2].level, DiagnosticLevel.info); expect(error.diagnostics[0].toString(), 'My Error Summary.'); expect(error.diagnostics[1].toString(), 'My first description.'); expect(error.diagnostics[2].toString(), 'My second description.'); expect(error.diagnostics[3].toString(), ''); expect(error.diagnostics[4].toString(), ''); expect( error.toStringDeep(), 'FlutterError\n' ' My Error Summary.\n' ' My first description.\n' ' My second description.\n' '\n' '\n', ); error = FlutterError( 'My Error Summary.\n' 'My first description.\n' '\n' 'My second description.', ); expect(error.diagnostics.length, equals(4)); expect(error.diagnostics[0].level, DiagnosticLevel.summary); expect(error.diagnostics[1].level, DiagnosticLevel.info); expect(error.diagnostics[2].level, DiagnosticLevel.info); expect(error.diagnostics[3].level, DiagnosticLevel.info); expect(error.diagnostics[0].toString(), 'My Error Summary.'); expect(error.diagnostics[1].toString(), 'My first description.'); expect(error.diagnostics[2].toString(), ''); expect(error.diagnostics[3].toString(), 'My second description.'); expect( error.toStringDeep(), 'FlutterError\n' ' My Error Summary.\n' ' My first description.\n' '\n' ' My second description.\n', ); error = FlutterError('My Error Summary.'); expect(error.diagnostics.length, 1); expect(error.diagnostics.first.level, DiagnosticLevel.summary); expect(error.diagnostics.first.toString(), 'My Error Summary.'); expect( error.toStringDeep(), 'FlutterError\n' ' My Error Summary.\n', ); }); test('Malformed FlutterError objects', () { { final AssertionError error; try { throw FlutterError.fromParts(<DiagnosticsNode>[]); } on AssertionError catch (e) { error = e; } expect( FlutterErrorDetails(exception: error).toString(), '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' 'The following assertion was thrown:\n' 'Empty FlutterError\n' '═════════════════════════════════════════════════════════════════\n', ); } { final AssertionError error; try { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorDescription('Error description without a summary'), ]); } on AssertionError catch (e) { error = e; } expect( FlutterErrorDetails(exception: error).toString(), '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' 'The following assertion was thrown:\n' 'FlutterError is missing a summary.\n' 'All FlutterError objects should start with a short (one line)\n' 'summary description of the problem that was detected.\n' 'Malformed FlutterError:\n' ' Error description without a summary\n' '\n' 'This error should still help you solve your problem, however\n' 'please also report this malformed error in the framework by\n' 'filing a bug on GitHub:\n' ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml\n' '═════════════════════════════════════════════════════════════════\n', ); } { final AssertionError error; try { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('Error Summary A'), ErrorDescription('Some descriptionA'), ErrorSummary('Error Summary B'), ErrorDescription('Some descriptionB'), ]); } on AssertionError catch (e) { error = e; } expect( FlutterErrorDetails(exception: error).toString(), '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' 'The following assertion was thrown:\n' 'FlutterError contained multiple error summaries.\n' 'All FlutterError objects should have only a single short (one\n' 'line) summary description of the problem that was detected.\n' 'Malformed FlutterError:\n' ' Error Summary A\n' ' Some descriptionA\n' ' Error Summary B\n' ' Some descriptionB\n' '\n' 'The malformed error has 2 summaries.\n' 'Summary 1: Error Summary A\n' 'Summary 2: Error Summary B\n' '\n' 'This error should still help you solve your problem, however\n' 'please also report this malformed error in the framework by\n' 'filing a bug on GitHub:\n' ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml\n' '═════════════════════════════════════════════════════════════════\n', ); } { final AssertionError error; try { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorDescription('Some description'), ErrorSummary('Error summary'), ]); } on AssertionError catch (e) { error = e; } expect( FlutterErrorDetails(exception: error).toString(), '══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞══════════════════════\n' 'The following assertion was thrown:\n' 'FlutterError is missing a summary.\n' 'All FlutterError objects should start with a short (one line)\n' 'summary description of the problem that was detected.\n' 'Malformed FlutterError:\n' ' Some description\n' ' Error summary\n' '\n' 'This error should still help you solve your problem, however\n' 'please also report this malformed error in the framework by\n' 'filing a bug on GitHub:\n' ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml\n' '═════════════════════════════════════════════════════════════════\n', ); } }); test('User-thrown exceptions have ErrorSummary properties', () { { final DiagnosticsNode node; try { throw 'User thrown string'; } catch (e) { node = FlutterErrorDetails(exception: e).toDiagnosticsNode(); } final ErrorSummary summary = node.getProperties().whereType<ErrorSummary>().single; expect(summary.value, equals(<String>['User thrown string'])); } { final DiagnosticsNode node; try { throw ArgumentError.notNull('myArgument'); } catch (e) { node = FlutterErrorDetails(exception: e).toDiagnosticsNode(); } final ErrorSummary summary = node.getProperties().whereType<ErrorSummary>().single; expect(summary.value, equals(<String>['Invalid argument(s) (myArgument): Must not be null'])); } }); test('Identifies user fault', () { // User fault because they called `new Text(null)` from their own code. final StackTrace stack = StackTrace.fromString(''' #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39) #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5) #2 new Text (package:flutter/src/widgets/text.dart:287:10) #3 _MyHomePageState.build (package:hello_flutter/main.dart:72:16) #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4414:27) #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4303:15) #6 Element.rebuild (package:flutter/src/widgets/framework.dart:4027:5) #7 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4286:5) #8 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4461:11) #9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4281:5) #10 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3276:14) #11 Element.updateChild (package:flutter/src/widgets/framework.dart:3070:12) #12 SingleChildRenderObjectElement.mount (package:flutter/blah.dart:999:9)'''); final FlutterErrorDetails details = FlutterErrorDetails( exception: AssertionError('Test assertion'), stack: stack, ); final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); details.debugFillProperties(builder); expect(builder.properties.length, 4); expect(builder.properties[0].toString(), 'The following assertion was thrown:'); expect(builder.properties[1].toString(), contains('Assertion failed')); expect(builder.properties[2] is ErrorSpacer, true); final DiagnosticsStackTrace trace = builder.properties[3] as DiagnosticsStackTrace; expect(trace, isNotNull); expect(trace.value, stack); }); test('Identifies our fault', () { // Our fault because we should either have an assertion in `text_helper.dart` // or we should make sure not to pass bad values into new Text. final StackTrace stack = StackTrace.fromString(''' #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39) #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5) #2 new Text (package:flutter/src/widgets/text.dart:287:10) #3 new SomeWidgetUsingText (package:flutter/src/widgets/text_helper.dart:287:10) #4 _MyHomePageState.build (package:hello_flutter/main.dart:72:16) #5 StatefulElement.build (package:flutter/src/widgets/framework.dart:4414:27) #6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4303:15) #7 Element.rebuild (package:flutter/src/widgets/framework.dart:4027:5) #8 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4286:5) #9 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4461:11) #10 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4281:5) #11 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3276:14) #12 Element.updateChild (package:flutter/src/widgets/framework.dart:3070:12) #13 SingleChildRenderObjectElement.mount (package:flutter/blah.dart:999:9)'''); final FlutterErrorDetails details = FlutterErrorDetails( exception: AssertionError('Test assertion'), stack: stack, ); final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); details.debugFillProperties(builder); expect(builder.properties.length, 6); expect(builder.properties[0].toString(), 'The following assertion was thrown:'); expect(builder.properties[1].toString(), contains('Assertion failed')); expect(builder.properties[2] is ErrorSpacer, true); expect( builder.properties[3].toString(), 'Either the assertion indicates an error in the framework itself, or we should ' 'provide substantially more information in this error message to help you determine ' 'and fix the underlying cause.\n' 'In either case, please report this assertion by filing a bug on GitHub:\n' ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml', ); expect(builder.properties[4] is ErrorSpacer, true); final DiagnosticsStackTrace trace = builder.properties[5] as DiagnosticsStackTrace; expect(trace, isNotNull); expect(trace.value, stack); }); test('RepetitiveStackFrameFilter does not go out of range', () { const RepetitiveStackFrameFilter filter = RepetitiveStackFrameFilter( frames: <PartialStackFrame>[ PartialStackFrame(className: 'TestClass', method: 'test1', package: 'package:test/blah.dart'), PartialStackFrame(className: 'TestClass', method: 'test2', package: 'package:test/blah.dart'), PartialStackFrame(className: 'TestClass', method: 'test3', package: 'package:test/blah.dart'), ], replacement: 'test', ); final List<String?> reasons = List<String?>.filled(2, null); filter.filter( const <StackFrame>[ StackFrame(className: 'TestClass', method: 'test1', packageScheme: 'package', package: 'test', packagePath: 'blah.dart', line: 1, column: 1, number: 0, source: ''), StackFrame(className: 'TestClass', method: 'test2', packageScheme: 'package', package: 'test', packagePath: 'blah.dart', line: 1, column: 1, number: 0, source: ''), ], reasons, ); expect(reasons, List<String?>.filled(2, null)); }); }
flutter/packages/flutter/test/foundation/assertions_test.dart/0
{ "file_path": "flutter/packages/flutter/test/foundation/assertions_test.dart", "repo_id": "flutter", "token_count": 6977 }
705
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @TestOn('!chrome') library; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; Object getAssertionErrorWithMessage() { try { assert(false, 'Message goes here.'); } catch (e) { return e; } throw 'assert failed'; } Object getAssertionErrorWithoutMessage() { try { assert(false); } catch (e) { return e; } throw 'assert failed'; } Object getAssertionErrorWithLongMessage() { try { assert(false, 'word ' * 100); } catch (e) { return e; } throw 'assert failed'; } Future<StackTrace> getSampleStack() async { return Future<StackTrace>.sync(() => StackTrace.current); } Future<void> main() async { final List<String?> console = <String?>[]; final StackTrace sampleStack = await getSampleStack(); setUp(() async { expect(debugPrint, equals(debugPrintThrottled)); debugPrint = (String? message, { int? wrapWidth }) { console.add(message); }; }); tearDown(() async { expect(console, isEmpty); debugPrint = debugPrintThrottled; }); test('Error reporting - assert with message', () async { expect(console, isEmpty); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: getAssertionErrorWithMessage(), stack: sampleStack, library: 'error handling test', context: ErrorDescription('testing the error handling logic'), informationCollector: () sync* { yield ErrorDescription('line 1 of extra information'); yield ErrorHint('line 2 of extra information\n'); }, )); expect(console.join('\n'), matches( r'^══╡ EXCEPTION CAUGHT BY ERROR HANDLING TEST ╞═══════════════════════════════════════════════════════\n' r'The following assertion was thrown testing the error handling logic:\n' r'Message goes here\.\n' r"'[^']+flutter/test/foundation/error_reporting_test\.dart':\n" r"Failed assertion: line [0-9]+ pos [0-9]+: 'false'\n" r'\n' r'When the exception was thrown, this was the stack:\n' r'#0 getSampleStack\.<anonymous closure> \([^)]+flutter/test/foundation/error_reporting_test\.dart:[0-9]+:[0-9]+\)\n' r'#2 getSampleStack \([^)]+flutter/test/foundation/error_reporting_test\.dart:[0-9]+:[0-9]+\)\n' r'#3 main \([^)]+flutter/test/foundation/error_reporting_test\.dart:[0-9]+:[0-9]+\)\n' r'(.+\n)+', // TODO(ianh): when fixing #4021, also filter out frames from the test infrastructure below the first call to our main() )); console.clear(); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: getAssertionErrorWithMessage(), )); expect(console.join('\n'), 'Another exception was thrown: Message goes here.'); console.clear(); FlutterError.resetErrorCount(); }); test('Error reporting - assert with long message', () async { expect(console, isEmpty); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: getAssertionErrorWithLongMessage(), )); expect(console.join('\n'), matches( r'^══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞═════════════════════════════════════════════════════════\n' r'The following assertion was thrown:\n' r'word word word word word word word word word word word word word word word word word word word word\n' r'word word word word word word word word word word word word word word word word word word word word\n' r'word word word word word word word word word word word word word word word word word word word word\n' r'word word word word word word word word word word word word word word word word word word word word\n' r'word word word word word word word word word word word word word word word word word word word word\n' r"'[^']+flutter/test/foundation/error_reporting_test\.dart':\n" r"Failed assertion: line [0-9]+ pos [0-9]+: 'false'\n" r'════════════════════════════════════════════════════════════════════════════════════════════════════$', )); console.clear(); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: getAssertionErrorWithLongMessage(), )); expect( console.join('\n'), 'Another exception was thrown: ' 'word word word word word word word word word word word word word word word word word word word word ' 'word word word word word word word word word word word word word word word word word word word word ' 'word word word word word word word word word word word word word word word word word word word word ' 'word word word word word word word word word word word word word word word word word word word word ' 'word word word word word word word word word word word word word word word word word word word word', ); console.clear(); FlutterError.resetErrorCount(); }); test('Error reporting - assert with no message', () async { expect(console, isEmpty); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: getAssertionErrorWithoutMessage(), stack: sampleStack, library: 'error handling test', context: ErrorDescription('testing the error handling logic'), informationCollector: () sync* { yield ErrorDescription('line 1 of extra information'); yield ErrorDescription('line 2 of extra information\n'); // the trailing newlines here are intentional }, )); expect(console.join('\n'), matches( r'^══╡ EXCEPTION CAUGHT BY ERROR HANDLING TEST ╞═══════════════════════════════════════════════════════\n' r'The following assertion was thrown testing the error handling logic:\n' r"'[^']+flutter/test/foundation/error_reporting_test\.dart':[\n ]" r"Failed[\n ]assertion:[\n ]line[\n ][0-9]+[\n ]pos[\n ][0-9]+:[\n ]'false':[\n ]is[\n ]not[\n ]true\.\n" r'\n' r'When the exception was thrown, this was the stack:\n' r'#0 getSampleStack\.<anonymous closure> \([^)]+flutter/test/foundation/error_reporting_test\.dart:[0-9]+:[0-9]+\)\n' r'#2 getSampleStack \([^)]+flutter/test/foundation/error_reporting_test\.dart:[0-9]+:[0-9]+\)\n' r'#3 main \([^)]+flutter/test/foundation/error_reporting_test\.dart:[0-9]+:[0-9]+\)\n' r'(.+\n)+', // TODO(ianh): when fixing #4021, also filter out frames from the test infrastructure below the first call to our main() )); console.clear(); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: getAssertionErrorWithoutMessage(), )); expect(console.join('\n'), matches(r"Another exception was thrown: '[^']+flutter/test/foundation/error_reporting_test\.dart': Failed assertion: line [0-9]+ pos [0-9]+: 'false': is not true\.")); console.clear(); FlutterError.resetErrorCount(); }); test('Error reporting - NoSuchMethodError', () async { expect(console, isEmpty); final Object exception = NoSuchMethodError.withInvocation(5, Invocation.method(#foo, <dynamic>[2, 4])); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: exception, )); expect(console.join('\n'), matches( r'^══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞═════════════════════════════════════════════════════════\n' r'The following NoSuchMethodError was thrown:\n' r'int has no foo method accepting arguments \(_, _\)\n' r'════════════════════════════════════════════════════════════════════════════════════════════════════$', )); console.clear(); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: exception, )); expect( console.join('\n'), 'Another exception was thrown: NoSuchMethodError: int has no foo method accepting arguments (_, _)', ); console.clear(); FlutterError.resetErrorCount(); }); test('Error reporting - NoSuchMethodError', () async { expect(console, isEmpty); FlutterError.dumpErrorToConsole(const FlutterErrorDetails( exception: 'hello', )); expect(console.join('\n'), matches( r'^══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞═════════════════════════════════════════════════════════\n' r'The following message was thrown:\n' r'hello\n' r'════════════════════════════════════════════════════════════════════════════════════════════════════$', )); console.clear(); FlutterError.dumpErrorToConsole(const FlutterErrorDetails( exception: 'hello again', )); expect(console.join('\n'), 'Another exception was thrown: hello again'); console.clear(); FlutterError.resetErrorCount(); }); // Regression test for https://github.com/flutter/flutter/issues/62223 test('Error reporting - empty stack', () async { expect(console, isEmpty); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: 'exception - empty stack', stack: StackTrace.fromString(''), )); expect(console.join('\n'), matches( r'^══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞═════════════════════════════════════════════════════════\n' r'The following message was thrown:\n' r'exception - empty stack\n' r'\n' r'When the exception was thrown, this was the stack\n' r'════════════════════════════════════════════════════════════════════════════════════════════════════$', )); console.clear(); FlutterError.resetErrorCount(); }); test('Stack traces are not truncated', () async { const String stackString = ''' #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39) #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5) #2 new Text (package:flutter/src/widgets/text.dart:287:10) #3 _MyHomePageState.build (package:hello_flutter/main.dart:72:16) #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4414:27) #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4303:15) #6 Element.rebuild (package:flutter/src/widgets/framework.dart:4027:5) #7 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4286:5) #8 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4461:11) #9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4281:5) #10 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3276:14)'''; expect(console, isEmpty); FlutterError.dumpErrorToConsole(FlutterErrorDetails( exception: AssertionError('Test assertion'), stack: StackTrace.fromString(stackString), )); final String x = console.join('\n'); expect(x, startsWith(''' ══╡ EXCEPTION CAUGHT BY FLUTTER FRAMEWORK ╞═════════════════════════════════════════════════════════ The following assertion was thrown: Assertion failed: "Test assertion" When the exception was thrown, this was the stack: #2 new Text (package:flutter/src/widgets/text.dart:287:10) #3 _MyHomePageState.build (package:hello_flutter/main.dart:72:16) #4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4414:27) #5 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4303:15) #6 Element.rebuild (package:flutter/src/widgets/framework.dart:4027:5) #7 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4286:5) #8 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4461:11) #9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4281:5)''', )); console.clear(); FlutterError.resetErrorCount(); }); }
flutter/packages/flutter/test/foundation/error_reporting_test.dart/0
{ "file_path": "flutter/packages/flutter/test/foundation/error_reporting_test.dart", "repo_id": "flutter", "token_count": 4453 }
706
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('debugPrintGestureArenaDiagnostics', (WidgetTester tester) async { PointerEvent event; debugPrintGestureArenaDiagnostics = true; final DebugPrintCallback oldCallback = debugPrint; final List<String> log = <String>[]; debugPrint = (String? s, { int? wrapWidth }) { log.add(s ?? ''); }; final TapGestureRecognizer tap = TapGestureRecognizer() ..onTapDown = (TapDownDetails details) { } ..onTapUp = (TapUpDetails details) { } ..onTap = () { } ..onTapCancel = () { }; expect(log, isEmpty); event = const PointerDownEvent(pointer: 1, position: Offset(10.0, 10.0)); tap.addPointer(event as PointerDownEvent); expect(log, hasLength(2)); expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 ❙ ★ Opening new gesture arena.')); expect(log[1], equalsIgnoringHashCodes('Gesture arena 1 ❙ Adding: TapGestureRecognizer#00000(state: ready, button: 1)')); log.clear(); GestureBinding.instance.gestureArena.close(1); expect(log, hasLength(1)); expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 ❙ Closing with 1 member.')); log.clear(); GestureBinding.instance.pointerRouter.route(event); expect(log, isEmpty); event = const PointerUpEvent(pointer: 1, position: Offset(12.0, 8.0)); GestureBinding.instance.pointerRouter.route(event); expect(log, isEmpty); GestureBinding.instance.gestureArena.sweep(1); expect(log, hasLength(2)); expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 ❙ Sweeping with 1 member.')); expect(log[1], equalsIgnoringHashCodes('Gesture arena 1 ❙ Winner: TapGestureRecognizer#00000(state: ready, finalPosition: Offset(12.0, 8.0), button: 1)')); log.clear(); tap.dispose(); expect(log, isEmpty); debugPrintGestureArenaDiagnostics = false; debugPrint = oldCallback; }); testWidgets('debugPrintRecognizerCallbacksTrace', (WidgetTester tester) async { PointerEvent event; debugPrintRecognizerCallbacksTrace = true; final DebugPrintCallback oldCallback = debugPrint; final List<String> log = <String>[]; debugPrint = (String? s, { int? wrapWidth }) { log.add(s ?? ''); }; final TapGestureRecognizer tap = TapGestureRecognizer() ..onTapDown = (TapDownDetails details) { } ..onTapUp = (TapUpDetails details) { } ..onTap = () { } ..onTapCancel = () { }; expect(log, isEmpty); event = const PointerDownEvent(pointer: 1, position: Offset(10.0, 10.0)); tap.addPointer(event as PointerDownEvent); expect(log, isEmpty); GestureBinding.instance.gestureArena.close(1); expect(log, isEmpty); GestureBinding.instance.pointerRouter.route(event); expect(log, isEmpty); event = const PointerUpEvent(pointer: 1, position: Offset(12.0, 8.0)); GestureBinding.instance.pointerRouter.route(event); expect(log, isEmpty); GestureBinding.instance.gestureArena.sweep(1); expect(log, hasLength(3)); expect(log[0], equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: ready, finalPosition: Offset(12.0, 8.0), button: 1) calling onTapDown callback.')); expect(log[1], equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: ready, won arena, finalPosition: Offset(12.0, 8.0), button: 1, sent tap down) calling onTapUp callback.')); expect(log[2], equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: ready, won arena, finalPosition: Offset(12.0, 8.0), button: 1, sent tap down) calling onTap callback.')); log.clear(); tap.dispose(); expect(log, isEmpty); debugPrintRecognizerCallbacksTrace = false; debugPrint = oldCallback; }); testWidgets('debugPrintGestureArenaDiagnostics and debugPrintRecognizerCallbacksTrace', (WidgetTester tester) async { PointerEvent event; debugPrintGestureArenaDiagnostics = true; debugPrintRecognizerCallbacksTrace = true; final DebugPrintCallback oldCallback = debugPrint; final List<String> log = <String>[]; debugPrint = (String? s, { int? wrapWidth }) { log.add(s ?? ''); }; final TapGestureRecognizer tap = TapGestureRecognizer() ..onTapDown = (TapDownDetails details) { } ..onTapUp = (TapUpDetails details) { } ..onTap = () { } ..onTapCancel = () { }; expect(log, isEmpty); event = const PointerDownEvent(pointer: 1, position: Offset(10.0, 10.0)); tap.addPointer(event as PointerDownEvent); expect(log, hasLength(2)); expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 ❙ ★ Opening new gesture arena.')); expect(log[1], equalsIgnoringHashCodes('Gesture arena 1 ❙ Adding: TapGestureRecognizer#00000(state: ready, button: 1)')); log.clear(); GestureBinding.instance.gestureArena.close(1); expect(log, hasLength(1)); expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 ❙ Closing with 1 member.')); log.clear(); GestureBinding.instance.pointerRouter.route(event); expect(log, isEmpty); event = const PointerUpEvent(pointer: 1, position: Offset(12.0, 8.0)); GestureBinding.instance.pointerRouter.route(event); expect(log, isEmpty); GestureBinding.instance.gestureArena.sweep(1); expect(log, hasLength(5)); expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 ❙ Sweeping with 1 member.')); expect(log[1], equalsIgnoringHashCodes('Gesture arena 1 ❙ Winner: TapGestureRecognizer#00000(state: ready, finalPosition: Offset(12.0, 8.0), button: 1)')); expect(log[2], equalsIgnoringHashCodes(' ❙ TapGestureRecognizer#00000(state: ready, finalPosition: Offset(12.0, 8.0), button: 1) calling onTapDown callback.')); expect(log[3], equalsIgnoringHashCodes(' ❙ TapGestureRecognizer#00000(state: ready, won arena, finalPosition: Offset(12.0, 8.0), button: 1, sent tap down) calling onTapUp callback.')); expect(log[4], equalsIgnoringHashCodes(' ❙ TapGestureRecognizer#00000(state: ready, won arena, finalPosition: Offset(12.0, 8.0), button: 1, sent tap down) calling onTap callback.')); log.clear(); tap.dispose(); expect(log, isEmpty); debugPrintGestureArenaDiagnostics = false; debugPrintRecognizerCallbacksTrace = false; debugPrint = oldCallback; }); test('TapGestureRecognizer _sentTapDown toString', () { final TapGestureRecognizer tap = TapGestureRecognizer() ..onTap = () {}; // Add a callback so that event can be added expect(tap.toString(), equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: ready)')); const PointerDownEvent event = PointerDownEvent(pointer: 1, position: Offset(10.0, 10.0)); tap.addPointer(event); tap.didExceedDeadline(); expect(tap.toString(), equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: possible, button: 1, sent tap down)')); GestureBinding.instance.gestureArena.close(1); tap.dispose(); }); }
flutter/packages/flutter/test/gestures/debug_test.dart/0
{ "file_path": "flutter/packages/flutter/test/gestures/debug_test.dart", "repo_id": "flutter", "token_count": 2686 }
707
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/gestures.dart'; import 'package:flutter_test/flutter_test.dart'; import 'gesture_tester.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); testGesture('Should recognize pan', (GestureTester tester) { final MultiTapGestureRecognizer tap = MultiTapGestureRecognizer(longTapDelay: kLongPressTimeout); final List<String> log = <String>[]; tap.onTapDown = (int pointer, TapDownDetails details) { log.add('tap-down $pointer'); }; tap.onTapUp = (int pointer, TapUpDetails details) { log.add('tap-up $pointer'); }; tap.onTap = (int pointer) { log.add('tap $pointer'); }; tap.onLongTapDown = (int pointer, TapDownDetails details) { log.add('long-tap-down $pointer'); }; tap.onTapCancel = (int pointer) { log.add('tap-cancel $pointer'); }; final TestPointer pointer5 = TestPointer(5); final PointerDownEvent down5 = pointer5.down(const Offset(10.0, 10.0)); tap.addPointer(down5); tester.closeArena(5); expect(log, <String>['tap-down 5']); log.clear(); tester.route(down5); expect(log, isEmpty); final TestPointer pointer6 = TestPointer(6); final PointerDownEvent down6 = pointer6.down(const Offset(15.0, 15.0)); tap.addPointer(down6); tester.closeArena(6); expect(log, <String>['tap-down 6']); log.clear(); tester.route(down6); expect(log, isEmpty); tester.route(pointer5.move(const Offset(11.0, 12.0))); expect(log, isEmpty); tester.route(pointer6.move(const Offset(14.0, 13.0))); expect(log, isEmpty); tester.route(pointer5.up()); expect(log, <String>[ 'tap-up 5', 'tap 5', ]); log.clear(); tester.async.elapse(kLongPressTimeout + kPressTimeout); expect(log, <String>['long-tap-down 6']); log.clear(); tester.route(pointer6.move(const Offset(40.0, 30.0))); // move more than kTouchSlop from 15.0,15.0 expect(log, <String>['tap-cancel 6']); log.clear(); tester.route(pointer6.up()); expect(log, isEmpty); tap.dispose(); }); testGesture('Can filter based on device kind', (GestureTester tester) { final MultiTapGestureRecognizer tap = MultiTapGestureRecognizer( longTapDelay: kLongPressTimeout, supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.touch }, ); final List<String> log = <String>[]; tap.onTapDown = (int pointer, TapDownDetails details) { log.add('tap-down $pointer'); }; tap.onTapUp = (int pointer, TapUpDetails details) { log.add('tap-up $pointer'); }; tap.onTap = (int pointer) { log.add('tap $pointer'); }; tap.onLongTapDown = (int pointer, TapDownDetails details) { log.add('long-tap-down $pointer'); }; tap.onTapCancel = (int pointer) { log.add('tap-cancel $pointer'); }; final TestPointer touchPointer5 = TestPointer(5); final PointerDownEvent down5 = touchPointer5.down(const Offset(10.0, 10.0)); tap.addPointer(down5); tester.closeArena(5); expect(log, <String>['tap-down 5']); log.clear(); tester.route(down5); expect(log, isEmpty); final TestPointer mousePointer6 = TestPointer(6, PointerDeviceKind.mouse); final PointerDownEvent down6 = mousePointer6.down(const Offset(20.0, 20.0)); tap.addPointer(down6); tester.closeArena(6); // Mouse down should be ignored by the recognizer. expect(log, isEmpty); final TestPointer touchPointer7 = TestPointer(7); final PointerDownEvent down7 = touchPointer7.down(const Offset(15.0, 15.0)); tap.addPointer(down7); tester.closeArena(7); expect(log, <String>['tap-down 7']); log.clear(); tester.route(down7); expect(log, isEmpty); tester.route(touchPointer5.move(const Offset(11.0, 12.0))); expect(log, isEmpty); // Move within the [kTouchSlop] range. tester.route(mousePointer6.move(const Offset(21.0, 18.0))); // Move beyond the slop range. tester.route(mousePointer6.move(const Offset(50.0, 40.0))); // Neither triggers any event because they originate from a mouse. expect(log, isEmpty); tester.route(touchPointer7.move(const Offset(14.0, 13.0))); expect(log, isEmpty); tester.route(touchPointer5.up()); expect(log, <String>[ 'tap-up 5', 'tap 5', ]); log.clear(); // Mouse up should be ignored. tester.route(mousePointer6.up()); expect(log, isEmpty); tester.async.elapse(kLongPressTimeout + kPressTimeout); // Only the touch pointer (7) triggers a long-tap, not the mouse pointer (6). expect(log, <String>['long-tap-down 7']); log.clear(); tester.route(touchPointer7.move(const Offset(40.0, 30.0))); // move more than kTouchSlop from 15.0,15.0 expect(log, <String>['tap-cancel 7']); log.clear(); tap.dispose(); }); }
flutter/packages/flutter/test/gestures/multitap_test.dart/0
{ "file_path": "flutter/packages/flutter/test/gestures/multitap_test.dart", "repo_id": "flutter", "token_count": 1932 }
708
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/gestures.dart'; import 'package:flutter_test/flutter_test.dart'; import 'velocity_tracker_data.dart'; bool _withinTolerance(double actual, double expected) { const double kTolerance = 0.001; // Within .1% of expected value final double diff = (actual - expected)/expected; return diff.abs() < kTolerance; } bool _checkVelocity(Velocity actual, Offset expected) { return _withinTolerance(actual.pixelsPerSecond.dx, expected.dx) && _withinTolerance(actual.pixelsPerSecond.dy, expected.dy); } void main() { const List<Offset> expected = <Offset>[ Offset(219.59280094228163, 1304.701682306001), Offset(355.71046950050845, 967.2112857054104), Offset(12.657970884022308, -36.90447839251946), Offset(714.1399654786744, -2561.534447931869), Offset(-19.668121066218564, -2910.105747052462), Offset(646.8690114934209, 2976.977762577527), Offset(396.6988447819592, 2106.225572911095), Offset(298.31594440044495, -3660.8315955215294), Offset(-1.7334232785165882, -3288.13174127454), Offset(384.6361280392334, -2645.6612524779835), Offset(176.37900397918557, 2711.2542876273264), Offset(396.9328560260098, 4280.651578291764), Offset(-71.51939428321249, 3716.7385187526947), ]; testWidgets('Velocity tracker gives expected results', (WidgetTester tester) async { final VelocityTracker tracker = VelocityTracker.withKind(PointerDeviceKind.touch); int i = 0; for (final PointerEvent event in velocityEventData) { if (event is PointerDownEvent || event is PointerMoveEvent) { tracker.addPosition(event.timeStamp, event.position); } if (event is PointerUpEvent) { expect(_checkVelocity(tracker.getVelocity(), expected[i]), isTrue); i += 1; } } }); testWidgets('Velocity control test', (WidgetTester tester) async { const Velocity velocity1 = Velocity(pixelsPerSecond: Offset(7.0, 0.0)); const Velocity velocity2 = Velocity(pixelsPerSecond: Offset(12.0, 0.0)); expect(velocity1, equals(const Velocity(pixelsPerSecond: Offset(7.0, 0.0)))); expect(velocity1, isNot(equals(velocity2))); expect(velocity2 - velocity1, equals(const Velocity(pixelsPerSecond: Offset(5.0, 0.0)))); expect((-velocity1).pixelsPerSecond, const Offset(-7.0, 0.0)); expect(velocity1 + velocity2, equals(const Velocity(pixelsPerSecond: Offset(19.0, 0.0)))); expect(velocity1.hashCode, isNot(equals(velocity2.hashCode))); expect(velocity1, hasOneLineDescription); }); testWidgets('Interrupted velocity estimation', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/7510 final VelocityTracker tracker = VelocityTracker.withKind(PointerDeviceKind.touch); for (final PointerEvent event in interruptedVelocityEventData) { if (event is PointerDownEvent || event is PointerMoveEvent) { tracker.addPosition(event.timeStamp, event.position); } if (event is PointerUpEvent) { expect(_checkVelocity(tracker.getVelocity(), const Offset(649.5, 3890.3)), isTrue); } } }); testWidgets('No data velocity estimation', (WidgetTester tester) async { final VelocityTracker tracker = VelocityTracker.withKind(PointerDeviceKind.touch); expect(tracker.getVelocity(), Velocity.zero); }); testWidgets('FreeScrollStartVelocityTracker.getVelocity throws when no points', (WidgetTester tester) async { final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch); AssertionError? exception; try { tracker.getVelocity(); } on AssertionError catch (e) { exception = e; } expect(exception?.toString(), contains('at least 1 point')); }); testWidgets('FreeScrollStartVelocityTracker.getVelocity throws when the new point precedes the previous point', (WidgetTester tester) async { final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch); AssertionError? exception; tracker.addPosition(const Duration(hours: 1), Offset.zero); try { tracker.getVelocity(); tracker.addPosition(const Duration(seconds: 1), Offset.zero); } on AssertionError catch (e) { exception = e; } expect(exception?.toString(), contains('has a smaller timestamp')); }); testWidgets('Estimate does not throw when there are more than 1 point', (WidgetTester tester) async { final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch); Offset position = Offset.zero; Duration time = Duration.zero; const Offset positionDelta = Offset(0, -1); const Duration durationDelta = Duration(seconds: 1); AssertionError? exception; for (int i = 0; i < 5; i+=1) { position += positionDelta; time += durationDelta; tracker.addPosition(time, position); try { tracker.getVelocity(); } on AssertionError catch (e) { exception = e; } expect(exception, isNull); } }); testWidgets('Makes consistent velocity estimates with consistent velocity', (WidgetTester tester) async { final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch); Offset position = Offset.zero; Duration time = Duration.zero; const Offset positionDelta = Offset(0, -1); const Duration durationDelta = Duration(seconds: 1); for (int i = 0; i < 10; i+=1) { position += positionDelta; time += durationDelta; tracker.addPosition(time, position); if (i >= 3) { expect(tracker.getVelocity().pixelsPerSecond, positionDelta); } } }); testWidgets('Assume zero velocity when there are no recent samples - base VelocityTracker', (WidgetTester tester) async { final VelocityTracker tracker = VelocityTracker.withKind(PointerDeviceKind.touch); Offset position = Offset.zero; Duration time = Duration.zero; const Offset positionDelta = Offset(0, -1); const Duration durationDelta = Duration(seconds: 1); for (int i = 0; i < 10; i+=1) { position += positionDelta; time += durationDelta; tracker.addPosition(time, position); } await tester.pumpAndSettle(); expect(tracker.getVelocity().pixelsPerSecond, Offset.zero); }); testWidgets('Assume zero velocity when there are no recent samples - IOS', (WidgetTester tester) async { final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch); Offset position = Offset.zero; Duration time = Duration.zero; const Offset positionDelta = Offset(0, -1); const Duration durationDelta = Duration(seconds: 1); for (int i = 0; i < 10; i+=1) { position += positionDelta; time += durationDelta; tracker.addPosition(time, position); } await tester.pumpAndSettle(); expect(tracker.getVelocity().pixelsPerSecond, Offset.zero); }); testWidgets('Assume zero velocity when there are no recent samples - MacOS', (WidgetTester tester) async { final MacOSScrollViewFlingVelocityTracker tracker = MacOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch); Offset position = Offset.zero; Duration time = Duration.zero; const Offset positionDelta = Offset(0, -1); const Duration durationDelta = Duration(seconds: 1); for (int i = 0; i < 10; i+=1) { position += positionDelta; time += durationDelta; tracker.addPosition(time, position); } await tester.pumpAndSettle(); expect(tracker.getVelocity().pixelsPerSecond, Offset.zero); }); }
flutter/packages/flutter/test/gestures/velocity_tracker_test.dart/0
{ "file_path": "flutter/packages/flutter/test/gestures/velocity_tracker_test.dart", "repo_id": "flutter", "token_count": 2808 }
709
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class User { const User({ required this.email, required this.name, }); final String email; final String name; @override String toString() { return '$name, $email'; } } void main() { const List<String> kOptions = <String>[ 'aardvark', 'bobcat', 'chameleon', 'dingo', 'elephant', 'flamingo', 'goose', 'hippopotamus', 'iguana', 'jaguar', 'koala', 'lemur', 'mouse', 'northern white rhinoceros', ]; const List<User> kOptionsUsers = <User>[ User(name: 'Alice', email: '[email protected]'), User(name: 'Bob', email: '[email protected]'), User(name: 'Charlie', email: '[email protected]'), ]; testWidgets('can filter and select a list of string options', (WidgetTester tester) async { late String lastSelection; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Autocomplete<String>( onSelected: (String selection) { lastSelection = selection; }, optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, ), ), ), ); // The field is always rendered, but the options are not unless needed. expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsNothing); // Focus the empty field. All the options are displayed. await tester.tap(find.byType(TextFormField)); await tester.pump(); expect(find.byType(ListView), findsOneWidget); ListView list = find.byType(ListView).evaluate().first.widget as ListView; expect(list.semanticChildCount, kOptions.length); // Enter text. The options are filtered by the text. await tester.enterText(find.byType(TextFormField), 'ele'); await tester.pump(); expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsOneWidget); list = find.byType(ListView).evaluate().first.widget as ListView; // 'chameleon' and 'elephant' are displayed. expect(list.semanticChildCount, 2); // Select a option. The options hide and the field updates to show the // selection. await tester.tap(find.byType(InkWell).first); await tester.pump(); expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsNothing); final TextFormField field = find.byType(TextFormField).evaluate().first.widget as TextFormField; expect(field.controller!.text, 'chameleon'); expect(lastSelection, 'chameleon'); // Modify the field text. The options appear again and are filtered. await tester.enterText(find.byType(TextFormField), 'e'); await tester.pump(); expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsOneWidget); list = find.byType(ListView).evaluate().first.widget as ListView; // 'chameleon', 'elephant', 'goose', 'lemur', 'mouse', and // 'northern white rhinoceros' are displayed. expect(list.semanticChildCount, 6); }); testWidgets('can filter and select a list of custom User options', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Autocomplete<User>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptionsUsers.where((User option) { return option.toString().contains(textEditingValue.text.toLowerCase()); }); }, ), ), ), ); // The field is always rendered, but the options are not unless needed. expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsNothing); // Focus the empty field. All the options are displayed. await tester.tap(find.byType(TextFormField)); await tester.pump(); expect(find.byType(ListView), findsOneWidget); ListView list = find.byType(ListView).evaluate().first.widget as ListView; expect(list.semanticChildCount, kOptionsUsers.length); // Enter text. The options are filtered by the text. await tester.enterText(find.byType(TextFormField), 'example'); await tester.pump(); expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsOneWidget); list = find.byType(ListView).evaluate().first.widget as ListView; // 'Alice' and 'Bob' are displayed because they have "example.com" emails. expect(list.semanticChildCount, 2); // Select a option. The options hide and the field updates to show the // selection. await tester.tap(find.byType(InkWell).first); await tester.pump(); expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsNothing); final TextFormField field = find.byType(TextFormField).evaluate().first.widget as TextFormField; expect(field.controller!.text, 'Alice, [email protected]'); // Modify the field text. The options appear again and are filtered. await tester.enterText(find.byType(TextFormField), 'B'); await tester.pump(); expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsOneWidget); list = find.byType(ListView).evaluate().first.widget as ListView; // 'Bob' is displayed. expect(list.semanticChildCount, 1); }); testWidgets('displayStringForOption is displayed in the options', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Autocomplete<User>( displayStringForOption: (User option) { return option.name; }, optionsBuilder: (TextEditingValue textEditingValue) { return kOptionsUsers.where((User option) { return option.toString().contains(textEditingValue.text.toLowerCase()); }); }, ), ), ), ); // The field is always rendered, but the options are not unless needed. expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsNothing); // Focus the empty field. All the options are displayed, and the string that // is used comes from displayStringForOption. await tester.tap(find.byType(TextFormField)); await tester.pump(); expect(find.byType(ListView), findsOneWidget); final ListView list = find.byType(ListView).evaluate().first.widget as ListView; expect(list.semanticChildCount, kOptionsUsers.length); for (int i = 0; i < kOptionsUsers.length; i++) { expect(find.text(kOptionsUsers[i].name), findsOneWidget); } // Select a option. The options hide and the field updates to show the // selection. The text in the field is given by displayStringForOption. await tester.tap(find.byType(InkWell).first); await tester.pump(); expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsNothing); final TextFormField field = find.byType(TextFormField).evaluate().first.widget as TextFormField; expect(field.controller!.text, kOptionsUsers.first.name); }); testWidgets('can build a custom field', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Autocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController textEditingController, FocusNode focusNode, VoidCallback onFieldSubmitted) { return Container(key: fieldKey); }, ), ), ), ); // The custom field is rendered and not the default TextFormField. expect(find.byKey(fieldKey), findsOneWidget); expect(find.byType(TextFormField), findsNothing); }); testWidgets('can build custom options', (WidgetTester tester) async { final GlobalKey optionsKey = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Autocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return Container(key: optionsKey); }, ), ), ), ); // The default field is rendered but not the options, yet. expect(find.byKey(optionsKey), findsNothing); expect(find.byType(TextFormField), findsOneWidget); // Focus the empty field. The custom options is displayed. await tester.tap(find.byType(TextFormField)); await tester.pump(); expect(find.byKey(optionsKey), findsOneWidget); }); testWidgets('the default Autocomplete options widget has a maximum height of 200', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp(home: Scaffold( body: Autocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, ), ))); final Finder listFinder = find.byType(ListView); final Finder inputFinder = find.byType(TextFormField); await tester.tap(inputFinder); await tester.enterText(inputFinder, ''); await tester.pump(); final Size baseSize = tester.getSize(listFinder); final double resultingHeight = baseSize.height; expect(resultingHeight, equals(200)); }); testWidgets('the options height restricts to max desired height', (WidgetTester tester) async { const double desiredHeight = 150.0; await tester.pumpWidget(MaterialApp( home: Scaffold( body: Autocomplete<String>( optionsMaxHeight: desiredHeight, optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, ), ))); /// entering "a" returns 9 items from kOptions so basically the /// height of 9 options would be beyond `desiredHeight=150`, /// so height gets restricted to desiredHeight. final Finder listFinder = find.byType(ListView); final Finder inputFinder = find.byType(TextFormField); await tester.tap(inputFinder); await tester.enterText(inputFinder, 'a'); await tester.pump(); final Size baseSize = tester.getSize(listFinder); final double resultingHeight = baseSize.height; /// expected desired Height =150.0 expect(resultingHeight, equals(desiredHeight)); }); testWidgets('The height of options shrinks to height of resulting items, if less than maxHeight', (WidgetTester tester) async { // Returns a Future with the height of the default [Autocomplete] options widget // after the provided text had been entered into the [Autocomplete] field. Future<double> getDefaultOptionsHeight( WidgetTester tester, String enteredText) async { final Finder listFinder = find.byType(ListView); final Finder inputFinder = find.byType(TextFormField); final TextFormField field = inputFinder.evaluate().first.widget as TextFormField; field.controller!.clear(); await tester.tap(inputFinder); await tester.enterText(inputFinder, enteredText); await tester.pump(); final Size baseSize = tester.getSize(listFinder); return baseSize.height; } const double maxOptionsHeight = 250.0; await tester.pumpWidget(MaterialApp( home: Scaffold( body: Autocomplete<String>( optionsMaxHeight: maxOptionsHeight, optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, ), ))); final Finder listFinder = find.byType(ListView); expect(listFinder, findsNothing); // Entering `a` returns 9 items(height > `maxOptionsHeight`) from the kOptions // so height gets restricted to `maxOptionsHeight =250`. final double nineItemsHeight = await getDefaultOptionsHeight(tester, 'a'); expect(nineItemsHeight, equals(maxOptionsHeight)); // Returns 2 Items (height < `maxOptionsHeight`) // so options height shrinks to 2 Items combined height. final double twoItemsHeight = await getDefaultOptionsHeight(tester, 'el'); expect(twoItemsHeight, lessThan(maxOptionsHeight)); // Returns 1 item (height < `maxOptionsHeight`) from `kOptions` // so options height shrinks to 1 items height. final double oneItemsHeight = await getDefaultOptionsHeight(tester, 'elep'); expect(oneItemsHeight, lessThan(twoItemsHeight)); }); testWidgets('initialValue sets initial text field value', (WidgetTester tester) async { late String lastSelection; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Autocomplete<String>( initialValue: const TextEditingValue(text: 'lem'), onSelected: (String selection) { lastSelection = selection; }, optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, ), ), ), ); // The field is always rendered, but the options are not unless needed. expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsNothing); expect( tester.widget<TextFormField>(find.byType(TextFormField)).controller!.text, 'lem', ); // Focus the empty field. All the options are displayed. await tester.tap(find.byType(TextFormField)); await tester.pump(); expect(find.byType(ListView), findsOneWidget); final ListView list = find.byType(ListView).evaluate().first.widget as ListView; // Displays just one option ('lemur'). expect(list.semanticChildCount, 1); // Select a option. The options hide and the field updates to show the // selection. await tester.tap(find.byType(InkWell).first); await tester.pump(); expect(find.byType(TextFormField), findsOneWidget); expect(find.byType(ListView), findsNothing); final TextFormField field = find.byType(TextFormField).evaluate().first.widget as TextFormField; expect(field.controller!.text, 'lemur'); expect(lastSelection, 'lemur'); }); // Ensures that the option with the given label has a given background color // if given, or no background if color is null. void checkOptionHighlight(WidgetTester tester, String label, Color? color) { final RenderBox renderBox = tester.renderObject<RenderBox>(find.ancestor(matching: find.byType(Container), of: find.text(label))); if (color != null) { // Check to see that the container is painted with the highlighted background color. expect(renderBox, paints..rect(color: color)); } else { // There should only be a paragraph painted. expect(renderBox, paintsExactlyCountTimes(const Symbol('drawRect'), 0)); expect(renderBox, paints..paragraph()); } } testWidgets('keyboard navigation of the options properly highlights the option', (WidgetTester tester) async { const Color highlightColor = Color(0xFF112233); await tester.pumpWidget( MaterialApp( theme: ThemeData.light().copyWith( focusColor: highlightColor, ), home: Scaffold( body: Autocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, ), ), ), ); await tester.tap(find.byType(TextFormField)); await tester.enterText(find.byType(TextFormField), 'el'); await tester.pump(); expect(find.byType(ListView), findsOneWidget); final ListView list = find.byType(ListView).evaluate().first.widget as ListView; expect(list.semanticChildCount, 2); // Initially the first option should be highlighted checkOptionHighlight(tester, 'chameleon', highlightColor); checkOptionHighlight(tester, 'elephant', null); // Move the selection down await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); // Highlight should be moved to the second item checkOptionHighlight(tester, 'chameleon', null); checkOptionHighlight(tester, 'elephant', highlightColor); }); testWidgets('keyboard navigation keeps the highlighted option scrolled into view', (WidgetTester tester) async { const Color highlightColor = Color(0xFF112233); await tester.pumpWidget( MaterialApp( theme: ThemeData.light().copyWith(focusColor: highlightColor), home: Scaffold( body: Autocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, ), ), ), ); await tester.tap(find.byType(TextFormField)); await tester.enterText(find.byType(TextFormField), 'e'); await tester.pump(); expect(find.byType(ListView), findsOneWidget); final ListView list = find.byType(ListView).evaluate().first.widget as ListView; expect(list.semanticChildCount, 6); final Rect optionsGroupRect = tester.getRect(find.byType(ListView)); const double optionsGroupPadding = 16.0; // Highlighted item should be at the top. checkOptionHighlight(tester, 'chameleon', highlightColor); expect( tester.getTopLeft(find.text('chameleon')).dy, equals(optionsGroupRect.top + optionsGroupPadding), ); // Move down the list of options. await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Select 'elephant'. await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Select 'goose'. await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Select 'lemur'. await tester.pumpAndSettle(); // Highlighted item 'lemur' should be centered in the options popup. checkOptionHighlight(tester, 'lemur', highlightColor); expect( tester.getCenter(find.text('lemur')).dy, equals(optionsGroupRect.center.dy), ); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Select 'mouse'. await tester.pumpAndSettle(); checkOptionHighlight(tester, 'mouse', highlightColor); // First item should have scrolled off the top, and not be selected. expect(find.text('chameleon'), findsNothing); // The other items on screen should not be selected. checkOptionHighlight(tester, 'goose', null); checkOptionHighlight(tester, 'lemur', null); checkOptionHighlight(tester, 'northern white rhinoceros', null); }); group('optionsViewOpenDirection', () { testWidgets('default (down)', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Autocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], ), ), ), ); final OptionsViewOpenDirection actual = tester.widget<RawAutocomplete<String>>(find.byType(RawAutocomplete<String>)) .optionsViewOpenDirection; expect(actual, equals(OptionsViewOpenDirection.down)); }); testWidgets('down', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Autocomplete<String>( optionsViewOpenDirection: OptionsViewOpenDirection.down, // ignore: avoid_redundant_argument_values optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], ), ), ), ); final OptionsViewOpenDirection actual = tester.widget<RawAutocomplete<String>>(find.byType(RawAutocomplete<String>)) .optionsViewOpenDirection; expect(actual, equals(OptionsViewOpenDirection.down)); }); testWidgets('up', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: Autocomplete<String>( optionsViewOpenDirection: OptionsViewOpenDirection.up, optionsBuilder: (TextEditingValue textEditingValue) => <String>['aa'], ), ), ), ), ); final OptionsViewOpenDirection actual = tester.widget<RawAutocomplete<String>>(find.byType(RawAutocomplete<String>)) .optionsViewOpenDirection; expect(actual, equals(OptionsViewOpenDirection.up)); await tester.tap(find.byType(RawAutocomplete<String>)); await tester.enterText(find.byType(RawAutocomplete<String>), 'a'); expect(find.text('aa').hitTestable(), findsOneWidget); }); }); }
flutter/packages/flutter/test/material/autocomplete_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/autocomplete_test.dart", "repo_id": "flutter", "token_count": 8260 }
710
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'feedback_tester.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final Finder nextMonthIcon = find.byWidgetPredicate((Widget w) => w is IconButton && (w.tooltip?.startsWith('Next month') ?? false)); final Finder previousMonthIcon = find.byWidgetPredicate((Widget w) => w is IconButton && (w.tooltip?.startsWith('Previous month') ?? false)); Widget calendarDatePicker({ Key? key, DateTime? initialDate, DateTime? firstDate, DateTime? lastDate, DateTime? currentDate, ValueChanged<DateTime>? onDateChanged, ValueChanged<DateTime>? onDisplayedMonthChanged, DatePickerMode initialCalendarMode = DatePickerMode.day, SelectableDayPredicate? selectableDayPredicate, TextDirection textDirection = TextDirection.ltr, ThemeData? theme, bool? useMaterial3, }) { return MaterialApp( theme: theme ?? ThemeData(useMaterial3: useMaterial3), home: Material( child: Directionality( textDirection: textDirection, child: CalendarDatePicker( key: key, initialDate: initialDate, firstDate: firstDate ?? DateTime(2001), lastDate: lastDate ?? DateTime(2031, DateTime.december, 31), currentDate: currentDate ?? DateTime(2016, DateTime.january, 3), onDateChanged: onDateChanged ?? (DateTime date) {}, onDisplayedMonthChanged: onDisplayedMonthChanged, initialCalendarMode: initialCalendarMode, selectableDayPredicate: selectableDayPredicate, ), ), ), ); } Widget yearPicker({ Key? key, DateTime? selectedDate, DateTime? initialDate, DateTime? firstDate, DateTime? lastDate, DateTime? currentDate, ValueChanged<DateTime>? onChanged, TextDirection textDirection = TextDirection.ltr, }) { return MaterialApp( home: Material( child: Directionality( textDirection: textDirection, child: YearPicker( key: key, selectedDate: selectedDate ?? DateTime(2016, DateTime.january, 15), firstDate: firstDate ?? DateTime(2001), lastDate: lastDate ?? DateTime(2031, DateTime.december, 31), currentDate: currentDate ?? DateTime(2016, DateTime.january, 3), onChanged: onChanged ?? (DateTime date) {}, ), ), ), ); } group('CalendarDatePicker', () { testWidgets('Can select a day', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), onDateChanged: (DateTime date) => selectedDate = date, )); await tester.tap(find.text('12')); expect(selectedDate, equals(DateTime(2016, DateTime.january, 12))); }); testWidgets('Can select a day with nothing first selected', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( onDateChanged: (DateTime date) => selectedDate = date, )); await tester.tap(find.text('12')); expect(selectedDate, equals(DateTime(2016, DateTime.january, 12))); }); testWidgets('Can select a month', (WidgetTester tester) async { DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); expect(find.text('January 2016'), findsOneWidget); // Go back two months await tester.tap(previousMonthIcon); await tester.pumpAndSettle(); expect(find.text('December 2015'), findsOneWidget); expect(displayedMonth, equals(DateTime(2015, DateTime.december))); await tester.tap(previousMonthIcon); await tester.pumpAndSettle(); expect(find.text('November 2015'), findsOneWidget); expect(displayedMonth, equals(DateTime(2015, DateTime.november))); // Go forward a month await tester.tap(nextMonthIcon); await tester.pumpAndSettle(); expect(find.text('December 2015'), findsOneWidget); expect(displayedMonth, equals(DateTime(2015, DateTime.december))); }); testWidgets('Can select a month with nothing first selected', (WidgetTester tester) async { DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); expect(find.text('January 2016'), findsOneWidget); // Go back two months await tester.tap(previousMonthIcon); await tester.pumpAndSettle(); expect(find.text('December 2015'), findsOneWidget); expect(displayedMonth, equals(DateTime(2015, DateTime.december))); await tester.tap(previousMonthIcon); await tester.pumpAndSettle(); expect(find.text('November 2015'), findsOneWidget); expect(displayedMonth, equals(DateTime(2015, DateTime.november))); // Go forward a month await tester.tap(nextMonthIcon); await tester.pumpAndSettle(); expect(find.text('December 2015'), findsOneWidget); expect(displayedMonth, equals(DateTime(2015, DateTime.december))); }); testWidgets('Can select a year', (WidgetTester tester) async { DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); await tester.tap(find.text('January 2016')); // Switch to year mode. await tester.pumpAndSettle(); await tester.tap(find.text('2018')); await tester.pumpAndSettle(); expect(find.text('January 2018'), findsOneWidget); expect(displayedMonth, equals(DateTime(2018))); }); testWidgets('Can select a year with nothing first selected', (WidgetTester tester) async { DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); await tester.tap(find.text('January 2016')); // Switch to year mode. await tester.pumpAndSettle(); await tester.tap(find.text('2018')); await tester.pumpAndSettle(); expect(find.text('January 2018'), findsOneWidget); expect(displayedMonth, equals(DateTime(2018))); }); testWidgets('Selecting date does not change displayed month', (WidgetTester tester) async { DateTime? selectedDate; DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2020, DateTime.march, 15), onDateChanged: (DateTime date) => selectedDate = date, onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); await tester.tap(nextMonthIcon); await tester.pumpAndSettle(); expect(find.text('April 2020'), findsOneWidget); expect(displayedMonth, equals(DateTime(2020, DateTime.april))); await tester.tap(find.text('25')); await tester.pumpAndSettle(); expect(find.text('April 2020'), findsOneWidget); expect(displayedMonth, equals(DateTime(2020, DateTime.april))); expect(selectedDate, equals(DateTime(2020, DateTime.april, 25))); // There isn't a 31 in April so there shouldn't be one if it is showing April. expect(find.text('31'), findsNothing); }); testWidgets('Changing year does change selected date', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), onDateChanged: (DateTime date) => selectedDate = date, )); await tester.tap(find.text('4')); expect(selectedDate, equals(DateTime(2016, DateTime.january, 4))); await tester.tap(find.text('January 2016')); await tester.pumpAndSettle(); await tester.tap(find.text('2018')); await tester.pumpAndSettle(); expect(selectedDate, equals(DateTime(2018, DateTime.january, 4))); }); testWidgets('Changing year for february 29th', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2020, DateTime.february, 29), onDateChanged: (DateTime date) => selectedDate = date, )); await tester.tap(find.text('February 2020')); await tester.pumpAndSettle(); await tester.tap(find.text('2018')); await tester.pumpAndSettle(); expect(selectedDate, equals(DateTime(2018, DateTime.february, 28))); await tester.tap(find.text('February 2018')); await tester.pumpAndSettle(); await tester.tap(find.text('2020')); await tester.pumpAndSettle(); // Changing back to 2020 the 29th is not selected anymore. expect(selectedDate, equals(DateTime(2020, DateTime.february, 28))); }); testWidgets('Changing year does not change the month', (WidgetTester tester) async { DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); await tester.tap(nextMonthIcon); await tester.pumpAndSettle(); await tester.tap(nextMonthIcon); await tester.pumpAndSettle(); await tester.tap(find.text('March 2016')); await tester.pumpAndSettle(); await tester.tap(find.text('2018')); await tester.pumpAndSettle(); expect(find.text('March 2018'), findsOneWidget); expect(displayedMonth, equals(DateTime(2018, DateTime.march))); }); testWidgets('Can select a year and then a day', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), onDateChanged: (DateTime date) => selectedDate = date, )); await tester.tap(find.text('January 2016')); // Switch to year mode. await tester.pumpAndSettle(); await tester.tap(find.text('2017')); await tester.pumpAndSettle(); await tester.tap(find.text('19')); expect(selectedDate, equals(DateTime(2017, DateTime.january, 19))); }); testWidgets('Cannot select a day outside bounds', (WidgetTester tester) async { final DateTime validDate = DateTime(2017, DateTime.january, 15); DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( initialDate: validDate, firstDate: validDate, lastDate: validDate, onDateChanged: (DateTime date) => selectedDate = date, )); // Earlier than firstDate. Should be ignored. await tester.tap(find.text('10')); expect(selectedDate, isNull); // Later than lastDate. Should be ignored. await tester.tap(find.text('20')); expect(selectedDate, isNull); // This one is just right. await tester.tap(find.text('15')); expect(selectedDate, validDate); }); testWidgets('Cannot navigate to a month outside bounds', (WidgetTester tester) async { DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( firstDate: DateTime(2016, DateTime.december, 15), initialDate: DateTime(2017, DateTime.january, 15), lastDate: DateTime(2017, DateTime.february, 15), onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); await tester.tap(nextMonthIcon); await tester.pumpAndSettle(); expect(displayedMonth, equals(DateTime(2017, DateTime.february))); // Shouldn't be possible to keep going forward into March. expect(nextMonthIcon, findsNothing); await tester.tap(previousMonthIcon); await tester.pumpAndSettle(); await tester.tap(previousMonthIcon); await tester.pumpAndSettle(); expect(displayedMonth, equals(DateTime(2016, DateTime.december))); // Shouldn't be possible to keep going backward into November. expect(previousMonthIcon, findsNothing); }); testWidgets('Cannot select disabled year', (WidgetTester tester) async { DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( firstDate: DateTime(2018, DateTime.june, 9), initialDate: DateTime(2018, DateTime.july, 4), lastDate: DateTime(2018, DateTime.december, 15), onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); await tester.tap(find.text('July 2018')); // Switch to year mode. await tester.pumpAndSettle(); await tester.tap(find.text('2016')); // Disabled, doesn't change the year. await tester.pumpAndSettle(); await tester.tap(find.text('2020')); // Disabled, doesn't change the year. await tester.pumpAndSettle(); await tester.tap(find.text('2018')); await tester.pumpAndSettle(); // Nothing should have changed. expect(displayedMonth, isNull); }); testWidgets('Selecting firstDate year respects firstDate', (WidgetTester tester) async { DateTime? selectedDate; DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( firstDate: DateTime(2016, DateTime.june, 9), initialDate: DateTime(2018, DateTime.may, 4), lastDate: DateTime(2019, DateTime.january, 15), onDateChanged: (DateTime date) => selectedDate = date, onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); await tester.tap(find.text('May 2018')); await tester.pumpAndSettle(); await tester.tap(find.text('2016')); await tester.pumpAndSettle(); // Month should be clamped to June as the range starts at June 2016. expect(find.text('June 2016'), findsOneWidget); expect(displayedMonth, DateTime(2016, DateTime.june)); expect(selectedDate, DateTime(2016, DateTime.june, 9)); }); testWidgets('Selecting lastDate year respects lastDate', (WidgetTester tester) async { DateTime? selectedDate; DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( firstDate: DateTime(2016, DateTime.june, 9), initialDate: DateTime(2018, DateTime.may, 4), lastDate: DateTime(2019, DateTime.january, 15), onDateChanged: (DateTime date) => selectedDate = date, onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); // Selected date is now 2018-05-04 (initialDate). await tester.tap(find.text('May 2018')); // Selected date is still 2018-05-04. await tester.pumpAndSettle(); await tester.tap(find.text('2019')); // Selected date would become 2019-05-04 but gets clamped to the month of lastDate, so 2019-01-04. await tester.pumpAndSettle(); expect(find.text('January 2019'), findsOneWidget); expect(displayedMonth, DateTime(2019)); expect(selectedDate, DateTime(2019, DateTime.january, 4)); }); testWidgets('Selecting lastDate year respects lastDate', (WidgetTester tester) async { DateTime? selectedDate; DateTime? displayedMonth; await tester.pumpWidget(calendarDatePicker( firstDate: DateTime(2016, DateTime.june, 9), initialDate: DateTime(2018, DateTime.may, 15), lastDate: DateTime(2019, DateTime.january, 4), onDateChanged: (DateTime date) => selectedDate = date, onDisplayedMonthChanged: (DateTime date) => displayedMonth = date, )); // Selected date is now 2018-05-15 (initialDate). await tester.tap(find.text('May 2018')); // Selected date is still 2018-05-15. await tester.pumpAndSettle(); await tester.tap(find.text('2019')); // Selected date would become 2019-05-15 but gets clamped to the month of lastDate, so 2019-01-15. // Day is now beyond the lastDate so that also gets clamped, to 2019-01-04. await tester.pumpAndSettle(); expect(find.text('January 2019'), findsOneWidget); expect(displayedMonth, DateTime(2019)); expect(selectedDate, DateTime(2019, DateTime.january, 4)); }); testWidgets('Only predicate days are selectable', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( firstDate: DateTime(2017, DateTime.january, 10), initialDate: DateTime(2017, DateTime.january, 16), lastDate: DateTime(2017, DateTime.january, 20), onDateChanged: (DateTime date) => selectedDate = date, selectableDayPredicate: (DateTime date) => date.day.isEven, )); await tester.tap(find.text('13')); // Odd, doesn't work. expect(selectedDate, isNull); await tester.tap(find.text('10')); // Even, works. expect(selectedDate, DateTime(2017, DateTime.january, 10)); await tester.tap(find.text('17')); // Odd, doesn't work. expect(selectedDate, DateTime(2017, DateTime.january, 10)); }); testWidgets('Can select initial calendar picker mode', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2014, DateTime.january, 15), initialCalendarMode: DatePickerMode.year, )); // 2018 wouldn't be available if the year picker wasn't showing. // The initial current year is 2014. await tester.tap(find.text('2018')); await tester.pumpAndSettle(); expect(find.text('January 2018'), findsOneWidget); }); testWidgets('Material2 - currentDate is highlighted', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( useMaterial3: false, initialDate: DateTime(2016, DateTime.january, 15), currentDate: DateTime(2016, 1, 2), )); const Color todayColor = Color(0xff2196f3); // default primary color expect( Material.of(tester.element(find.text('2'))), // The current day should be painted with a circle outline. paints..circle( color: todayColor, style: PaintingStyle.stroke, strokeWidth: 1.0, ), ); }); testWidgets('Material3 - currentDate is highlighted', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( useMaterial3: true, initialDate: DateTime(2016, DateTime.january, 15), currentDate: DateTime(2016, 1, 2), )); const Color todayColor = Color(0xff6750a4); // default primary color expect( Material.of(tester.element(find.text('2'))), // The current day should be painted with a circle outline. paints..circle( color: todayColor, style: PaintingStyle.stroke, strokeWidth: 1.0, ), ); }); testWidgets('Material2 - currentDate is highlighted even if it is disabled', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( useMaterial3: false, firstDate: DateTime(2016, 1, 3), lastDate: DateTime(2016, 1, 31), currentDate: DateTime(2016, 1, 2), // not between first and last initialDate: DateTime(2016, 1, 5), )); const Color disabledColor = Color(0x61000000); // default disabled color expect( Material.of(tester.element(find.text('2'))), // The current day should be painted with a circle outline. paints ..circle( color: disabledColor, style: PaintingStyle.stroke, strokeWidth: 1.0, ), ); }); testWidgets('Material3 - currentDate is highlighted even if it is disabled', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( useMaterial3: true, firstDate: DateTime(2016, 1, 3), lastDate: DateTime(2016, 1, 31), currentDate: DateTime(2016, 1, 2), // not between first and last initialDate: DateTime(2016, 1, 5), )); const Color disabledColor = Color(0x616750a4); // default disabled color expect( Material.of(tester.element(find.text('2'))), // The current day should be painted with a circle outline. paints ..circle( color: disabledColor, style: PaintingStyle.stroke, strokeWidth: 1.0, ), ); }); testWidgets('Selecting date does not switch picker to year selection', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2020, DateTime.may, 10), initialCalendarMode: DatePickerMode.year, )); await tester.tap(find.text('2017')); await tester.pumpAndSettle(); expect(find.text('May 2017'), findsOneWidget); await tester.tap(find.text('10')); await tester.pumpAndSettle(); expect(find.text('May 2017'), findsOneWidget); expect(find.text('2017'), findsNothing); }); testWidgets('Selecting disabled date does not change current selection', (WidgetTester tester) async { DateTime day(int day) => DateTime(2020, DateTime.may, day); DateTime selection = day(2); await tester.pumpWidget(calendarDatePicker( initialDate: selection, firstDate: day(2), lastDate: day(3), onDateChanged: (DateTime date) { selection = date; }, )); await tester.tap(find.text('3')); await tester.pumpAndSettle(); expect(selection, day(3)); await tester.tap(find.text('4')); await tester.pumpAndSettle(); expect(selection, day(3)); await tester.tap(find.text('5')); await tester.pumpAndSettle(); expect(selection, day(3)); }); for (final bool useMaterial3 in <bool>[false, true]) { testWidgets('Updates to initialDate parameter are not reflected in the state (useMaterial3=$useMaterial3)', (WidgetTester tester) async { final Key pickerKey = UniqueKey(); final DateTime initialDate = DateTime(2020, 1, 21); final DateTime updatedDate = DateTime(1976, 2, 23); final DateTime firstDate = DateTime(1970); final DateTime lastDate = DateTime(2099, 31, 12); final Color selectedColor = useMaterial3 ? const Color(0xff6750a4) : const Color(0xff2196f3); // default primary color await tester.pumpWidget(calendarDatePicker( key: pickerKey, useMaterial3: useMaterial3, initialDate: initialDate, firstDate: firstDate, lastDate: lastDate, onDateChanged: (DateTime value) {}, )); await tester.pumpAndSettle(); // Month should show as January 2020. expect(find.text('January 2020'), findsOneWidget); // Selected date should be painted with a colored circle. expect( Material.of(tester.element(find.text('21'))), paints..circle(color: selectedColor, style: PaintingStyle.fill), ); // Change to the updated initialDate. // This should have no effect, the initialDate is only the _initial_ date. await tester.pumpWidget(calendarDatePicker( key: pickerKey, useMaterial3: useMaterial3, initialDate: updatedDate, firstDate: firstDate, lastDate: lastDate, onDateChanged: (DateTime value) {}, )); // Wait for the page scroll animation to finish. await tester.pumpAndSettle(const Duration(milliseconds: 200)); // Month should show as January 2020 still. expect(find.text('January 2020'), findsOneWidget); expect(find.text('February 1976'), findsNothing); // Selected date should be painted with a colored circle. expect( Material.of(tester.element(find.text('21'))), paints..circle(color: selectedColor, style: PaintingStyle.fill), ); }); } testWidgets('Updates to initialCalendarMode parameter is not reflected in the state', (WidgetTester tester) async { final Key pickerKey = UniqueKey(); await tester.pumpWidget(calendarDatePicker( key: pickerKey, initialDate: DateTime(2016, DateTime.january, 15), initialCalendarMode: DatePickerMode.year, )); await tester.pumpAndSettle(); // Should be in year mode. expect(find.text('January 2016'), findsOneWidget); // Day/year selector expect(find.text('15'), findsNothing); // day 15 in grid expect(find.text('2016'), findsOneWidget); // 2016 in year grid await tester.pumpWidget(calendarDatePicker( key: pickerKey, initialDate: DateTime(2016, DateTime.january, 15), )); await tester.pumpAndSettle(); // Should be in year mode still; updating an _initial_ parameter has no effect. expect(find.text('January 2016'), findsOneWidget); // Day/year selector expect(find.text('15'), findsNothing); // day 15 in grid expect(find.text('2016'), findsOneWidget); // 2016 in year grid }); testWidgets('Dragging more than half the width should not cause a jump', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), )); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(PageView))); // This initial drag is required for the PageView to recognize the gesture, as it uses DragStartBehavior.start. // It does not count towards the drag distance. await gesture.moveBy(const Offset(100, 0)); // Dragging for a bit less than half the width should reveal the previous month. await gesture.moveBy(const Offset(800 / 2 - 1, 0)); await tester.pumpAndSettle(); expect(find.text('January 2016'), findsOneWidget); expect(find.text('1'), findsNWidgets(2)); // Dragging a bit over the half should still show both. await gesture.moveBy(const Offset(2, 0)); await tester.pumpAndSettle(); expect(find.text('December 2015'), findsOneWidget); expect(find.text('1'), findsNWidgets(2)); }); group('Keyboard navigation', () { testWidgets('Can toggle to year mode', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), )); expect(find.text('2016'), findsNothing); expect(find.text('January 2016'), findsOneWidget); // Navigate to the year selector and activate it. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); // The years should be visible. expect(find.text('2016'), findsOneWidget); expect(find.text('January 2016'), findsOneWidget); }); testWidgets('Can navigate next/previous months', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), )); expect(find.text('January 2016'), findsOneWidget); // Navigate to the previous month button and activate it twice. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); // Should be showing Nov 2015 expect(find.text('November 2015'), findsOneWidget); // Navigate to the next month button and activate it four times. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); // Should be on Mar 2016. expect(find.text('March 2016'), findsOneWidget); }); testWidgets('Can navigate date grid with arrow keys', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), onDateChanged: (DateTime date) => selectedDate = date, )); // Navigate to the grid. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); // Navigate from Jan 15 to Jan 18 with arrow keys. await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); // Activate it. await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); // Should have selected Jan 18. expect(selectedDate, DateTime(2016, DateTime.january, 18)); }); testWidgets('Navigating with arrow keys scrolls months', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), onDateChanged: (DateTime date) => selectedDate = date, )); // Navigate to the grid. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); // Navigate from Jan 15 to Dec 31 with arrow keys await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); // Should have scrolled to Dec 2015. expect(find.text('December 2015'), findsOneWidget); // Navigate from Dec 31 to Nov 26 with arrow keys. await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pumpAndSettle(); // Should have scrolled to Nov 2015. expect(find.text('November 2015'), findsOneWidget); // Activate it await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); // Should have selected Jan 18. expect(selectedDate, DateTime(2015, DateTime.november, 26)); }); testWidgets('RTL text direction reverses the horizontal arrow key navigation', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), onDateChanged: (DateTime date) => selectedDate = date, textDirection: TextDirection.rtl, )); // Navigate to the grid. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); // Navigate from Jan 15 to 19 with arrow keys. await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pumpAndSettle(); // Activate it. await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); // Should have selected Jan 19. expect(selectedDate, DateTime(2016, DateTime.january, 19)); }); }); group('Haptic feedback', () { const Duration hapticFeedbackInterval = Duration(milliseconds: 10); late FeedbackTester feedback; setUp(() { feedback = FeedbackTester(); }); tearDown(() { feedback.dispose(); }); testWidgets('Selecting date vibrates', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), )); await tester.tap(find.text('10')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 1); await tester.tap(find.text('12')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 2); await tester.tap(find.text('14')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 3); }); testWidgets('Tapping unselectable date does not vibrate', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 10), selectableDayPredicate: (DateTime date) => date.day.isEven, )); await tester.tap(find.text('11')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 0); await tester.tap(find.text('13')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 0); await tester.tap(find.text('15')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 0); }); testWidgets('Changing modes and year vibrates', (WidgetTester tester) async { await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), )); await tester.tap(find.text('January 2016')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 1); await tester.tap(find.text('2018')); await tester.pump(hapticFeedbackInterval); expect(feedback.hapticCount, 2); }); }); group('Semantics', () { testWidgets('day mode', (WidgetTester tester) async { final SemanticsHandle semantics = tester.ensureSemantics(); await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), )); // Year mode drop down button. expect(tester.getSemantics(find.text('January 2016')), matchesSemantics( label: 'Select year', isButton: true, )); // Prev/Next month buttons. expect(tester.getSemantics(previousMonthIcon), matchesSemantics( tooltip: 'Previous month', isButton: true, hasTapAction: true, isEnabled: true, hasEnabledState: true, isFocusable: true, )); expect(tester.getSemantics(nextMonthIcon), matchesSemantics( tooltip: 'Next month', isButton: true, hasTapAction: true, isEnabled: true, hasEnabledState: true, isFocusable: true, )); // Day grid. expect(tester.getSemantics(find.text('1')), matchesSemantics( label: '1, Friday, January 1, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('2')), matchesSemantics( label: '2, Saturday, January 2, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('3')), matchesSemantics( label: '3, Sunday, January 3, 2016, Today', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('4')), matchesSemantics( label: '4, Monday, January 4, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('5')), matchesSemantics( label: '5, Tuesday, January 5, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('6')), matchesSemantics( label: '6, Wednesday, January 6, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('7')), matchesSemantics( label: '7, Thursday, January 7, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('8')), matchesSemantics( label: '8, Friday, January 8, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('9')), matchesSemantics( label: '9, Saturday, January 9, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('10')), matchesSemantics( label: '10, Sunday, January 10, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('11')), matchesSemantics( label: '11, Monday, January 11, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('12')), matchesSemantics( label: '12, Tuesday, January 12, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('13')), matchesSemantics( label: '13, Wednesday, January 13, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('14')), matchesSemantics( label: '14, Thursday, January 14, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('15')), matchesSemantics( label: '15, Friday, January 15, 2016', isButton: true, hasTapAction: true, isSelected: true, isFocusable: true, )); expect(tester.getSemantics(find.text('16')), matchesSemantics( label: '16, Saturday, January 16, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('17')), matchesSemantics( label: '17, Sunday, January 17, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('18')), matchesSemantics( label: '18, Monday, January 18, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('19')), matchesSemantics( label: '19, Tuesday, January 19, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('20')), matchesSemantics( label: '20, Wednesday, January 20, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('21')), matchesSemantics( label: '21, Thursday, January 21, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('22')), matchesSemantics( label: '22, Friday, January 22, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('23')), matchesSemantics( label: '23, Saturday, January 23, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('24')), matchesSemantics( label: '24, Sunday, January 24, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('25')), matchesSemantics( label: '25, Monday, January 25, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('26')), matchesSemantics( label: '26, Tuesday, January 26, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('27')), matchesSemantics( label: '27, Wednesday, January 27, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('28')), matchesSemantics( label: '28, Thursday, January 28, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('29')), matchesSemantics( label: '29, Friday, January 29, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); expect(tester.getSemantics(find.text('30')), matchesSemantics( label: '30, Saturday, January 30, 2016', isButton: true, hasTapAction: true, isFocusable: true, )); semantics.dispose(); }); testWidgets('calendar year mode', (WidgetTester tester) async { final SemanticsHandle semantics = tester.ensureSemantics(); await tester.pumpWidget(calendarDatePicker( initialDate: DateTime(2016, DateTime.january, 15), initialCalendarMode: DatePickerMode.year, )); // Year mode drop down button. expect(tester.getSemantics(find.text('January 2016')), matchesSemantics( label: 'Select year', isButton: true, )); // Year grid only shows 2010 - 2024. for (int year = 2010; year <= 2024; year++) { expect(tester.getSemantics(find.text('$year')), matchesSemantics( label: '$year', hasTapAction: true, isSelected: year == 2016, isFocusable: true, isButton: true, )); } semantics.dispose(); }); // This is a regression test for https://github.com/flutter/flutter/issues/143439. testWidgets('Selected date Semantics announcement on onDateChanged', (WidgetTester tester) async { final SemanticsHandle semantics = tester.ensureSemantics(); const DefaultMaterialLocalizations localizations = DefaultMaterialLocalizations(); final DateTime initialDate = DateTime(2016, DateTime.january, 15); DateTime? selectedDate; await tester.pumpWidget(calendarDatePicker( initialDate: initialDate, onDateChanged: (DateTime value) { selectedDate = value; }, )); final bool isToday = DateUtils.isSameDay(initialDate, selectedDate); final String semanticLabelSuffix = isToday ? ', ${localizations.currentDateLabel}' : ''; // The initial date should be announced. expect( tester.takeAnnouncements().last.message, '${localizations.formatFullDate(initialDate)}$semanticLabelSuffix', ); // Select a new date. await tester.tap(find.text('20')); await tester.pumpAndSettle(); // The selected date should be announced. expect( tester.takeAnnouncements().last.message, '${localizations.selectedDateLabel} ${localizations.formatFullDate(selectedDate!)}$semanticLabelSuffix', ); // Select the initial date. await tester.tap(find.text('15')); // The initial date should be announced as selected. expect( tester.takeAnnouncements().first.message, '${localizations.selectedDateLabel} ${localizations.formatFullDate(initialDate)}$semanticLabelSuffix', ); semantics.dispose(); }, variant: TargetPlatformVariant.desktop()); }); // This is a regression test for https://github.com/flutter/flutter/issues/141350. testWidgets('Default day selection overlay', (WidgetTester tester) async { final ThemeData theme = ThemeData(); await tester.pumpWidget(calendarDatePicker( firstDate: DateTime(2016, DateTime.december, 15), initialDate: DateTime(2017, DateTime.january, 15), lastDate: DateTime(2017, DateTime.february, 15), onDisplayedMonthChanged: (DateTime date) {}, theme: theme, )); RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, isNot(paints..circle(radius: 35.0, color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08)))); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.text('25'))); await tester.pumpAndSettle(); inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..circle(radius: 35.0, color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08))); expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 1)); final Rect expectedClipRect = Rect.fromCircle(center: const Offset(400.0, 241.0), radius: 35.0); final Path expectedClipPath = Path()..addRect(expectedClipRect); expect( inkFeatures, paints..clipPath(pathMatcher: coversSameAreaAs( expectedClipPath, areaToCompare: expectedClipRect, sampleSize: 100, )), ); }); }); group('YearPicker', () { testWidgets('Current year is visible in year picker', (WidgetTester tester) async { await tester.pumpWidget(yearPicker()); expect(find.text('2016'), findsOneWidget); }); testWidgets('Can select a year', (WidgetTester tester) async { DateTime? selectedDate; await tester.pumpWidget(yearPicker( onChanged: (DateTime date) => selectedDate = date, )); await tester.pumpAndSettle(); await tester.tap(find.text('2018')); await tester.pumpAndSettle(); expect(selectedDate, equals(DateTime(2018))); }); testWidgets('Cannot select disabled year', (WidgetTester tester) async { DateTime? selectedYear; await tester.pumpWidget(yearPicker( firstDate: DateTime(2018, DateTime.june, 9), selectedDate: DateTime(2018, DateTime.july, 4), lastDate: DateTime(2018, DateTime.december, 15), onChanged: (DateTime date) => selectedYear = date, )); await tester.tap(find.text('2016')); // Disabled, doesn't change the year. await tester.pumpAndSettle(); expect(selectedYear, isNull); await tester.tap(find.text('2020')); // Disabled, doesn't change the year. await tester.pumpAndSettle(); expect(selectedYear, isNull); await tester.tap(find.text('2018')); await tester.pumpAndSettle(); expect(selectedYear, equals(DateTime(2018, DateTime.july))); }); testWidgets('Selecting year with no selected month uses earliest month', (WidgetTester tester) async { DateTime? selectedYear; await tester.pumpWidget(yearPicker( firstDate: DateTime(2018, DateTime.june, 9), lastDate: DateTime(2019, DateTime.december, 15), onChanged: (DateTime date) => selectedYear = date, )); await tester.tap(find.text('2018')); expect(selectedYear, equals(DateTime(2018, DateTime.june))); await tester.pumpWidget(yearPicker( firstDate: DateTime(2018, DateTime.june, 9), lastDate: DateTime(2019, DateTime.december, 15), selectedDate: DateTime(2018, DateTime.june), onChanged: (DateTime date) => selectedYear = date, )); await tester.tap(find.text('2019')); expect(selectedYear, equals(DateTime(2019, DateTime.june))); }); testWidgets('Selecting year with no selected month uses January', (WidgetTester tester) async { DateTime? selectedYear; await tester.pumpWidget(yearPicker( firstDate: DateTime(2018, DateTime.june, 9), lastDate: DateTime(2019, DateTime.december, 15), onChanged: (DateTime date) => selectedYear = date, )); await tester.tap(find.text('2019')); expect(selectedYear, equals(DateTime(2019))); // january implied await tester.pumpWidget(yearPicker( firstDate: DateTime(2018, DateTime.june, 9), lastDate: DateTime(2019, DateTime.december, 15), selectedDate: DateTime(2018), onChanged: (DateTime date) => selectedYear = date, )); await tester.tap(find.text('2018')); expect(selectedYear, equals(DateTime(2018, DateTime.june))); }); }); }
flutter/packages/flutter/test/material/calendar_date_picker_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/calendar_date_picker_test.dart", "repo_id": "flutter", "token_count": 20687 }
711