From f43a282f1c8e7f9bc18747255b3aeb479922d3d6 Mon Sep 17 00:00:00 2001 From: xubaolin Date: Fri, 11 Jun 2021 07:54:03 +0800 Subject: [PATCH] fix a DropdownButtonFormField label display issue (#83014) --- .../flutter/lib/src/material/dropdown.dart | 2 +- .../material/dropdown_form_field_test.dart | 54 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/packages/flutter/lib/src/material/dropdown.dart b/packages/flutter/lib/src/material/dropdown.dart index 0107501304..862e654374 100644 --- a/packages/flutter/lib/src/material/dropdown.dart +++ b/packages/flutter/lib/src/material/dropdown.dart @@ -1622,7 +1622,7 @@ class DropdownButtonFormField extends FormField { child: Builder(builder: (BuildContext context) { return InputDecorator( decoration: effectiveDecoration.copyWith(errorText: field.errorText), - isEmpty: state.value == null, + isEmpty: items == null || items.where((DropdownMenuItem item) => item.value == state.value).isEmpty, isFocused: Focus.of(context).hasFocus, child: DropdownButtonHideUnderline( child: DropdownButton( diff --git a/packages/flutter/test/material/dropdown_form_field_test.dart b/packages/flutter/test/material/dropdown_form_field_test.dart index f204887bb0..f92cc13f8f 100644 --- a/packages/flutter/test/material/dropdown_form_field_test.dart +++ b/packages/flutter/test/material/dropdown_form_field_test.dart @@ -149,6 +149,60 @@ void verifyPaintedShadow(Finder customPaint, int elevation) { } void main() { + // Regression test for https://github.com/flutter/flutter/issues/82910 + testWidgets('null value test', (WidgetTester tester) async { + int? value = 1; + + await tester.pumpWidget( + TestApp( + textDirection: TextDirection.ltr, + child: Material( + child: DropdownButtonFormField( + decoration: const InputDecoration( + labelText: 'labelText', + ), + value: value, + onChanged: (int? newValue) { + value = newValue; + }, + items: const >[ + DropdownMenuItem( + value: null, + child: Text('None'), + ), + DropdownMenuItem( + value: 1, + child: Text('One'), + ), + DropdownMenuItem( + value: 2, + child: Text('Two'), + ), + DropdownMenuItem( + value: 3, + child: Text('Three'), + ) + ], + ), + ), + ), + ); + + expect(value, 1); + final Offset nonEmptyLabel = tester.getTopLeft(find.text('labelText')); + + // Switch to `null` value item from value 1. + await tester.tap(find.text('One')); + await tester.pumpAndSettle(); + await tester.tap(find.text('None').last); + await tester.pump(); + + expect(value, null); + final Offset nullValueLabel = tester.getTopLeft(find.text('labelText')); + // The position of the label does not change. + expect(nonEmptyLabel, nullValueLabel); + }); + testWidgets('DropdownButtonFormField with autovalidation test', (WidgetTester tester) async { String? value = 'one'; int _validateCalled = 0;