From 5881b13b9707b510bfa9d0ef0881ac98d24a8774 Mon Sep 17 00:00:00 2001 From: Bruno Leroux Date: Fri, 6 Dec 2024 11:11:26 +0100 Subject: [PATCH] Fix DropdownButtonFormField overlay colors management (#159472) ## Description This PR fixes some `DropdownButtonFormField` issues where the overlay color overflows. Before this PR, `DropdownButtonFormField` was relying on an `InkWell` to display overlay colors. This resulted in several issues related to the `InkWell` overflowing because it is not aware of the inner container inside `InputDecorator`, for instance see https://github.com/flutter/flutter/issues/106659. With this PR, `DropdownButtonFormField` does not use an `InkWell` but rely on `InputDecorator` to paint overlay colors. `InputDecorator` paints overlay colors only on its internal container, this fixes the color overflowing when using `InkWell`. With this change users can opt-in for overlay colors to be painted by setting InputDecorator.filled to true (similarly to TextField and accordingly to [the Material specification](https://m2.material.io/components/menus#dropdown-menu)). Code sample from https://github.com/flutter/flutter/issues/106659 with InputDecoration.filled set to true:
Code sample with InputDecoration.filled set to true ```dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { MyApp({Key? key}) : super(key: key); static const String _title = 'Flutter Code Sample'; final _formKey = GlobalKey(); @override Widget build(BuildContext context) { var items = [ 'Ayo', 'This', 'Don', 'Look', 'Right', ].map((String val) { return DropdownMenuItem( value: val, child: Text( val, ), ); }).toList(); return MaterialApp( title: _title, theme: ThemeData( inputDecorationTheme: const InputDecorationTheme( border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(32)), borderSide: BorderSide(color: Colors.blue, width: 2), ), ), ), home: Scaffold( body: Center( child: SizedBox( width: 500, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Form( key: _formKey, child: DropdownButtonFormField( onTap: () { _formKey.currentState!.validate(); }, validator: (String? v) => 'Required', onChanged: (String? value) {}, items: items, // Set InputDecoration.filled to true if overlays should be visible. // See Material specification for filled vs outlined dropdown button: // https://m2.material.io/components/menus#dropdown-menu. decoration: const InputDecoration(filled: true), ), ), ], ), ), ), ), ); } } ```
Before: ![image](https://github.com/user-attachments/assets/3c22975f-9b8c-4184-8ffe-67f2191bf563) After: ![image](https://github.com/user-attachments/assets/47ac35c3-b516-454f-bd47-2d35d85f172f) After (when filled is not set to true): ![image](https://github.com/user-attachments/assets/faf46e40-5817-4d64-9158-7a57d94a9776) ## Related Issue Fixes [DropdownButtonFormField InkWell spreads to error message](https://github.com/flutter/flutter/issues/106659). Fixes [DropdownButtonFormField input decorator focus/hover is not clipped and appears behind fill color.](https://github.com/flutter/flutter/issues/147069) First step for [DropDownButtonFormField hoverColor has no effect in web and desktop platforms](https://github.com/flutter/flutter/issues/151460) ## Tests Adds 4 tests. Updates 2 tests (remove checks specific to InkWell usage and use filled: true when checking for hover/focus colors). Removes 1 test (test specific to InkWell usage, because this PR removes the InkWell the test is obsolete). --- .../flutter/lib/src/material/dropdown.dart | 124 ++++++++------ .../lib/src/material/input_decorator.dart | 1 - .../material/dropdown_form_field_test.dart | 135 +++++----------- .../flutter/test/material/dropdown_test.dart | 153 ++++++++++++++++-- 4 files changed, 253 insertions(+), 160 deletions(-) diff --git a/packages/flutter/lib/src/material/dropdown.dart b/packages/flutter/lib/src/material/dropdown.dart index 0cbbf6bec8..d0eda380ee 100644 --- a/packages/flutter/lib/src/material/dropdown.dart +++ b/packages/flutter/lib/src/material/dropdown.dart @@ -23,7 +23,6 @@ import 'constants.dart'; import 'debug.dart'; import 'icons.dart'; import 'ink_well.dart'; -import 'input_border.dart'; import 'input_decorator.dart'; import 'material.dart'; import 'material_localizations.dart'; @@ -1010,8 +1009,7 @@ class DropdownButton extends StatefulWidget { ), assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), _inputDecoration = null, - _isEmpty = false, - _isFocused = false; + _isEmpty = false; DropdownButton._formField({ super.key, @@ -1044,7 +1042,6 @@ class DropdownButton extends StatefulWidget { this.padding, required InputDecoration inputDecoration, required bool isEmpty, - required bool isFocused, }) : assert(items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) { return item.value == value; @@ -1056,8 +1053,7 @@ class DropdownButton extends StatefulWidget { ), assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), _inputDecoration = inputDecoration, - _isEmpty = isEmpty, - _isFocused = isFocused; + _isEmpty = isEmpty; /// The list of items the user can select. /// @@ -1287,8 +1283,6 @@ class DropdownButton extends StatefulWidget { final bool _isEmpty; - final bool _isFocused; - @override State> createState() => _DropdownButtonState(); } @@ -1300,6 +1294,8 @@ class _DropdownButtonState extends State> with WidgetsBindi FocusNode? _internalNode; FocusNode? get focusNode => widget.focusNode ?? _internalNode; late Map> _actionMap; + bool _isHovering = false; + bool _hasPrimaryFocus = false; // Only used if needed to create _internalNode. FocusNode _createFocusNode() { @@ -1321,16 +1317,26 @@ class _DropdownButtonState extends State> with WidgetsBindi onInvoke: (ButtonActivateIntent intent) => _handleTap(), ), }; + focusNode?.addListener(_handleFocusChanged); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _removeDropdownRoute(); + focusNode?.removeListener(_handleFocusChanged); _internalNode?.dispose(); super.dispose(); } + void _handleFocusChanged() { + if (_hasPrimaryFocus != focusNode!.hasPrimaryFocus) { + setState(() { + _hasPrimaryFocus = focusNode!.hasPrimaryFocus; + }); + } + } + void _removeDropdownRoute() { _dropdownRoute?._dismiss(); _dropdownRoute = null; @@ -1586,30 +1592,76 @@ class _DropdownButtonState extends State> with WidgetsBindi }, ); + // When an InputDecoration is provided, use it instead of using an InkWell + // that overflows in some cases (such as showing an errorText) and requires + // additional logic to manage clipping properly. + // A filled InputDecoration is able to fill the InputDecorator container + // without overflowing. It also supports blending the hovered color. + // According to the Material specification, the overlay colors should be + // visible only for filled dropdown button, see: + // https://m2.material.io/components/menus#dropdown-menu if (widget._inputDecoration != null) { - result = InputDecorator( - decoration: widget._inputDecoration!, - isEmpty: widget._isEmpty, - isFocused: widget._isFocused, - child: result, + InputDecoration effectiveDecoration = widget._inputDecoration!; + if (_hasPrimaryFocus) { + final Color? focusColor = widget.focusColor ?? effectiveDecoration.focusColor; + // For compatibility, override the fill color when focusColor is set. + if (focusColor != null) { + effectiveDecoration = effectiveDecoration.copyWith(fillColor: focusColor); + } + } + result = Focus( + canRequestFocus: _enabled, + focusNode: focusNode, + autofocus: widget.autofocus, + child: MouseRegion( + onEnter: (PointerEnterEvent event) { + if (!_isHovering) { + setState(() { + _isHovering = true; + }); + } + }, + onExit: (PointerExitEvent event) { + if (_isHovering) { + setState(() { + _isHovering = false; + }); + } + }, + cursor: effectiveMouseCursor, + child: GestureDetector( + onTap: _enabled ? _handleTap : null, + behavior: HitTestBehavior.opaque, + child: InputDecorator( + decoration: effectiveDecoration, + isEmpty: widget._isEmpty, + isFocused: _hasPrimaryFocus, + isHovering: _isHovering, + child: widget.padding == null ? result : Padding(padding: widget.padding!, child: result), + ), + ), + ), + ); + } else { + result = InkWell( + mouseCursor: effectiveMouseCursor, + onTap: _enabled ? _handleTap : null, + canRequestFocus: _enabled, + borderRadius: widget.borderRadius, + focusNode: focusNode, + autofocus: widget.autofocus, + focusColor: widget.focusColor ?? Theme.of(context).focusColor, + enableFeedback: false, + child: widget.padding == null ? result : Padding(padding: widget.padding!, child: result), ); } + final bool childHasButtonSemantic = hintIndex != null || (_selectedIndex != null && widget.selectedItemBuilder == null); return Semantics( button: !childHasButtonSemantic, child: Actions( actions: _actionMap, - child: InkWell( - mouseCursor: effectiveMouseCursor, - onTap: _enabled ? _handleTap : null, - canRequestFocus: _enabled, - borderRadius: widget.borderRadius, - focusNode: focusNode, - autofocus: widget.autofocus, - focusColor: widget.focusColor ?? Theme.of(context).focusColor, - enableFeedback: false, - child: widget.padding == null ? result : Padding(padding: widget.padding!, child: result), - ), + child: result, ), ); } @@ -1679,13 +1731,13 @@ class DropdownButtonFormField extends FormField { 'with the same value', ), assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), - decoration = decoration ?? InputDecoration(focusColor: focusColor), + decoration = decoration ?? const InputDecoration(), super( initialValue: value, autovalidateMode: autovalidateMode ?? AutovalidateMode.disabled, builder: (FormFieldState field) { final _DropdownButtonFormFieldState state = field as _DropdownButtonFormFieldState; - final InputDecoration decorationArg = decoration ?? InputDecoration(focusColor: focusColor); + final InputDecoration decorationArg = decoration ?? const InputDecoration(); final InputDecoration effectiveDecoration = decorationArg.applyDefaults( Theme.of(field.context).inputDecorationTheme, ); @@ -1707,19 +1759,6 @@ class DropdownButtonFormField extends FormField { canRequestFocus: false, skipTraversal: true, child: Builder(builder: (BuildContext context) { - final bool isFocused = Focus.of(context).hasFocus; - late final InputBorder? resolvedBorder = switch (( - enabled: effectiveDecoration.enabled, - focused: isFocused, - error: effectiveDecoration.errorText != null, - )) { - (enabled: _, focused: true, error: true) => effectiveDecoration.focusedErrorBorder, - (enabled: _, focused: _, error: true) => effectiveDecoration.errorBorder, - (enabled: _, focused: true, error: _) => effectiveDecoration.focusedBorder, - (enabled: true, focused: _, error: _) => effectiveDecoration.enabledBorder, - (enabled: false, focused: _, error: _) => effectiveDecoration.border, - }; - return DropdownButtonHideUnderline( child: DropdownButton._formField( items: items, @@ -1745,18 +1784,13 @@ class DropdownButtonFormField extends FormField { menuMaxHeight: menuMaxHeight, enableFeedback: enableFeedback, alignment: alignment, - borderRadius: borderRadius ?? switch (resolvedBorder) { - final OutlineInputBorder border => border.borderRadius, - final UnderlineInputBorder border => border.borderRadius, - _ => null, - }, + borderRadius: borderRadius, // Clear the decoration hintText because DropdownButton has its own hint logic. inputDecoration: effectiveDecoration.copyWith( errorText: field.errorText, hintText: effectiveDecoration.hintText != null ? '' : null, ), isEmpty: isEmpty, - isFocused: isFocused, padding: padding, ), ); diff --git a/packages/flutter/lib/src/material/input_decorator.dart b/packages/flutter/lib/src/material/input_decorator.dart index 3309b5c2be..78cfa0c216 100644 --- a/packages/flutter/lib/src/material/input_decorator.dart +++ b/packages/flutter/lib/src/material/input_decorator.dart @@ -2079,7 +2079,6 @@ class _InputDecoratorState extends State with TickerProviderStat if (_hasError) MaterialState.error, }; - InputBorder _getDefaultBorder(ThemeData themeData, InputDecorationTheme defaults) { final InputBorder border = MaterialStateProperty.resolveAs(decoration.border, materialState) ?? const UnderlineInputBorder(); diff --git a/packages/flutter/test/material/dropdown_form_field_test.dart b/packages/flutter/test/material/dropdown_form_field_test.dart index f769e068ac..d47d96e664 100644 --- a/packages/flutter/test/material/dropdown_form_field_test.dart +++ b/packages/flutter/test/material/dropdown_form_field_test.dart @@ -4,7 +4,6 @@ import 'dart:math' as math; -import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -1130,103 +1129,6 @@ void main() { ); }); - testWidgets('InputDecoration borders are used for clipping', (WidgetTester tester) async { - const BorderRadius errorBorderRadius = BorderRadius.all(Radius.circular(5.0)); - const BorderRadius focusedErrorBorderRadius = BorderRadius.all(Radius.circular(6.0)); - const BorderRadius focusedBorder = BorderRadius.all(Radius.circular(7.0)); - const BorderRadius enabledBorder = BorderRadius.all(Radius.circular(9.0)); - - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - - const String errorText = 'This is an error'; - bool showError = false; - - await tester.pumpWidget( - MaterialApp( - theme: ThemeData( - inputDecorationTheme: const InputDecorationTheme( - errorBorder: OutlineInputBorder( - borderRadius: errorBorderRadius, - ), - focusedErrorBorder: OutlineInputBorder( - borderRadius: focusedErrorBorderRadius, - ), - focusedBorder: OutlineInputBorder( - borderRadius: focusedBorder, - ), - enabledBorder: OutlineInputBorder( - borderRadius: enabledBorder, - ), - ), - ), - home: Material( - child: Center( - child: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return DropdownButtonFormField( - value: 'two', - onChanged:(String? value) { - setState(() { - if (value == 'three') { - showError = true; - } else { - showError = false; - } - }); - }, - decoration: InputDecoration( - errorText: showError ? errorText : null, - ), - focusNode: focusNode, - items: menuItems.map>((String item) { - return DropdownMenuItem( - key: ValueKey(item), - value: item, - child: Text(item, key: ValueKey('${item}Text')), - ); - }).toList(), - ); - } - ), - ), - ), - ), - ); - - // Test enabled border. - InkWell inkWell = tester.widget(find.byType(InkWell)); - expect(inkWell.borderRadius, enabledBorder); - - // Test focused border. - focusNode.requestFocus(); - await tester.pump(); - - inkWell = tester.widget(find.byType(InkWell)); - expect(inkWell.borderRadius, focusedBorder); - - // Test focused error border. - await tester.tap(find.text('two'), warnIfMissed: false); - await tester.pumpAndSettle(); - await tester.tap(find.text('three').last); - await tester.pumpAndSettle(); - - inkWell = tester.widget(find.byType(InkWell)); - expect(inkWell.borderRadius, focusedErrorBorderRadius); - - // Test error border with no focus. - focusNode.unfocus(); - await tester.pump(); - - // Hovering over the widget should show the error border. - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); - await gesture.moveTo(tester.getCenter(find.text('three').last)); - await tester.pumpAndSettle(); - - inkWell = tester.widget(find.byType(InkWell)); - expect(inkWell.borderRadius, errorBorderRadius); - }); - testWidgets('DropdownButtonFormField onChanged is called when the form is reset', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/123009. final GlobalKey> stateKey = GlobalKey>(); @@ -1307,4 +1209,41 @@ void main() { expect(tester.takeException(), isNull); }); + + // Regression test for https://github.com/flutter/flutter/issues/106659. + testWidgets('Error visual logic is delegated to InputDecorator', (WidgetTester tester) async { + final GlobalKey formKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Form( + key: formKey, + child: DropdownButtonFormField( + items: menuItems.map((String value) { + return DropdownMenuItem( + value: value, + child: Text(value), + ); + }).toList(), + onChanged: onChanged, + validator: (String? v) => 'Required', + onTap: () { + formKey.currentState!.validate(); + }, + ), + ), + ), + ), + ); + + await tester.tap(find.byType(InputDecorator)); + await tester.pump(); + + // Check InputDecorator state because DropdownButtonFormField delegates + // visual logic to the InputDecorator. + final InputDecorator inputDecorator = tester.widget(find.byType(InputDecorator)); + expect(inputDecorator.isFocused, true); + expect(inputDecorator.decoration.errorText, 'Required'); + }); } diff --git a/packages/flutter/test/material/dropdown_test.dart b/packages/flutter/test/material/dropdown_test.dart index 97f60069ca..09bf16e6b1 100644 --- a/packages/flutter/test/material/dropdown_test.dart +++ b/packages/flutter/test/material/dropdown_test.dart @@ -2429,6 +2429,13 @@ void main() { expect(tester.getTopLeft(find.text('-item0-')).dx, 8); }); + Finder findInputDecoratorBorderPainter() { + return find.descendant( + of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_BorderContainer'), + matching: find.byWidgetPredicate((Widget w) => w is CustomPaint), + ); + } + testWidgets('DropdownButton can be focused, and has focusColor', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final UniqueKey buttonKey = UniqueKey(); @@ -2451,14 +2458,136 @@ void main() { final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButtonFormField'); addTearDown(focusNode.dispose); - await tester.pumpWidget(buildFrame(isFormField: true, buttonKey: buttonKey, onChanged: onChanged, focusNode: focusNode, autofocus: true)); - await tester.pumpAndSettle(); // Pump a frame for autofocus to take effect. - expect(focusNode.hasPrimaryFocus, isTrue); - expect(find.byType(Material), paints ..rect(rect: const Rect.fromLTRB(0.0, 268.0, 800.0, 332.0), color: const Color(0x1f000000))); + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + focusNode: focusNode, + autofocus: true, + decoration: const InputDecoration(filled: true), + )); - await tester.pumpWidget(buildFrame(isFormField: true, buttonKey: buttonKey, onChanged: onChanged, focusNode: focusNode, focusColor: const Color(0xff00ff00))); - await tester.pumpAndSettle(); // Pump a frame for autofocus to take effect. - expect(find.byType(Material), paints ..rect(rect: const Rect.fromLTRB(0.0, 268.0, 800.0, 332.0), color: const Color(0x1f00ff00))); + await tester.pump(); // Pump a frame for autofocus to take effect. + expect(focusNode.hasPrimaryFocus, isTrue); + + // Default focus Color from InputDecorator defaults. + final ThemeData theme = Theme.of(tester.element(find.byType(InputDecorator))); + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: theme.colorScheme.surfaceContainerHighest, + ), + ); + + // Focus color from Decoration. + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + focusNode: focusNode, + decoration: const InputDecoration( + filled: true, + focusColor: Color(0xff00ffff), + ), + )); + + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: const Color(0xff00ffff), + ), + ); + + // Focus color from focusColor property. + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + focusNode: focusNode, + decoration: const InputDecoration( + filled: true, + focusColor: Color(0xff00ffff), + ), + focusColor: const Color(0xff00ff00), + )); + + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: const Color(0xff00ff00), + ), + ); + }); + + // Regression test for https://github.com/flutter/flutter/issues/147069. + testWidgets('DropdownButtonFormField can be hovered', (WidgetTester tester) async { + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final UniqueKey buttonKey = UniqueKey(); + + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + )); + await tester.pump(); + + // Check inputDecorator.isHovering value because DropdownButtonFormField + // delegates to the InputDecorator which manages hover overlay. + InputDecorator inputDecorator = tester.widget(find.byType(InputDecorator)); + expect(inputDecorator.isHovering, false); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.moveTo(tester.getCenter(find.byKey(buttonKey))); + await tester.pump(); + + inputDecorator = tester.widget(find.byType(InputDecorator)); + expect(inputDecorator.isHovering, true); + }); + + // Regression test for https://github.com/flutter/flutter/issues/151460. + testWidgets('DropdownButtonFormField has hover color', (WidgetTester tester) async { + tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final UniqueKey buttonKey = UniqueKey(); + + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + // Setting InputDecoration.filled to true is required to get overlay showing. + decoration: const InputDecoration(filled: true), + )); + await tester.pump(); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.moveTo(tester.getCenter(find.byKey(buttonKey))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 15)); // Hover animation. + + // Default hover color. + final ThemeData theme = Theme.of(tester.element(find.byType(InputDecorator))); + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: Color.alphaBlend(theme.hoverColor, theme.colorScheme.surfaceContainerHighest), + ), + ); + + // Custom hover color. + const Color hoverColor = Color(0xaa00ff00); + await tester.pumpWidget(buildFrame( + isFormField: true, + buttonKey: buttonKey, + onChanged: onChanged, + decoration: const InputDecoration( + filled: true, + hoverColor: hoverColor), + )); + expect(findInputDecoratorBorderPainter(), paints + ..path( + style: PaintingStyle.fill, + color: Color.alphaBlend(hoverColor, theme.colorScheme.surfaceContainerHighest), + ), + ); }); testWidgets("DropdownButton won't be focused if not enabled", (WidgetTester tester) async { @@ -4023,7 +4152,7 @@ void main() { }); }); - testWidgets('BorderRadius property clips dropdown button and dropdown menu', (WidgetTester tester) async { + testWidgets('BorderRadius property clips dropdown menu', (WidgetTester tester) async { const double radius = 20.0; await tester.pumpWidget( @@ -4047,14 +4176,6 @@ void main() { ), ); - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); - await gesture.addPointer(); - await gesture.moveTo(tester.getCenter(find.byType(DropdownButtonFormField))); - await tester.pumpAndSettle(); - - final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); - expect(inkFeatures, paints..rrect(rrect: RRect.fromLTRBR(0.0, 276.0, 800.0, 324.0, const Radius.circular(radius)))); - await tester.tap(find.text('One')); await tester.pumpAndSettle();