Fix DropdownButtonFormField throws when onChange is null (#146342)

## Description

This PRs fixes a null pointer exception thrown when reset is called on a `DropdownButtonFormField` whose `onChange` callback is null.

## Related Issue

Fixes https://github.com/flutter/flutter/issues/146335

## Tests

Adds 1 tests.
This commit is contained in:
Bruno Leroux
2024-04-08 22:47:13 +02:00
committed by GitHub
parent 670a8cc9e9
commit f45741bc51
2 changed files with 35 additions and 2 deletions

View File

@@ -1726,7 +1726,7 @@ class _DropdownButtonFormFieldState<T> extends FormFieldState<T> {
@override
void didChange(T? value) {
super.didChange(value);
_dropdownButtonFormField.onChanged!(value);
_dropdownButtonFormField.onChanged?.call(value);
}
@override
@@ -1740,6 +1740,6 @@ class _DropdownButtonFormFieldState<T> extends FormFieldState<T> {
@override
void reset() {
super.reset();
_dropdownButtonFormField.onChanged!(value);
_dropdownButtonFormField.onChanged?.call(value);
}
}

View File

@@ -1274,4 +1274,37 @@ void main() {
expect(value, equals('One'));
expect(stateKey.currentState!.value, equals('One'));
});
testWidgets('DropdownButtonFormField with onChanged set to null does not throw on form reset', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/146335.
final GlobalKey<FormFieldState<String>> stateKey = GlobalKey<FormFieldState<String>>();
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Form(
key: formKey,
child: DropdownButtonFormField<String>(
key: stateKey,
value: 'One',
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: null,
),
),
),
),
);
// Reset the form.
formKey.currentState!.reset();
expect(tester.takeException(), isNull);
});
}