From 790ce64f0bde93e3eba4f6b8af876de0821bd4f9 Mon Sep 17 00:00:00 2001 From: Mairramer <50643541+Mairramer@users.noreply.github.com> Date: Tue, 23 Apr 2024 19:09:05 -0300 Subject: [PATCH] Adds AutovalidateMode.onFocusChange to Form and FormField (#140962) This will add a new autovalidateMode to Form and FormField, based on issue #40675. --- packages/flutter/lib/src/widgets/form.dart | 60 ++++++- packages/flutter/test/widgets/form_test.dart | 173 +++++++++++++++++++ 2 files changed, 228 insertions(+), 5 deletions(-) diff --git a/packages/flutter/lib/src/widgets/form.dart b/packages/flutter/lib/src/widgets/form.dart index 2211523a4a..5277e8a603 100644 --- a/packages/flutter/lib/src/widgets/form.dart +++ b/packages/flutter/lib/src/widgets/form.dart @@ -8,6 +8,8 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'basic.dart'; +import 'focus_manager.dart'; +import 'focus_scope.dart'; import 'framework.dart'; import 'navigator.dart'; import 'pop_scope.dart'; @@ -224,10 +226,22 @@ class FormState extends State
{ void _register(FormFieldState field) { _fields.add(field); + if (widget.autovalidateMode == AutovalidateMode.onUnfocus) { + field._focusNode.addListener(() => _updateField(field)); + } } void _unregister(FormFieldState field) { _fields.remove(field); + if (widget.autovalidateMode == AutovalidateMode.onUnfocus) { + field._focusNode.removeListener(()=> _updateField(field)); + } + } + + void _updateField(FormFieldState field) { + if (!field._focusNode.hasFocus) { + _validate(); + } } @override @@ -239,6 +253,7 @@ class FormState extends State { if (_hasInteractedByUser) { _validate(); } + case AutovalidateMode.onUnfocus: case AutovalidateMode.disabled: break; } @@ -323,12 +338,16 @@ class FormState extends State { bool _validate([Set>? invalidFields]) { bool hasError = false; String errorMessage = ''; + final bool validateOnFocusChange = widget.autovalidateMode == AutovalidateMode.onUnfocus; + for (final FormFieldState field in _fields) { - final bool isFieldValid = field.validate(); - hasError = !isFieldValid || hasError; - errorMessage += field.errorText ?? ''; - if (invalidFields != null && !isFieldValid) { - invalidFields.add(field); + if (!validateOnFocusChange || !field._focusNode.hasFocus) { + final bool isFieldValid = field.validate(); + hasError = !isFieldValid || hasError; + errorMessage += field.errorText ?? ''; + if (invalidFields != null && !isFieldValid) { + invalidFields.add(field); + } } } @@ -343,6 +362,7 @@ class FormState extends State { SemanticsService.announce(errorMessage, directionality, assertiveness: Assertiveness.assertive); } } + return !hasError; } } @@ -494,6 +514,7 @@ class FormFieldState extends State> with RestorationMixin { late T? _value = widget.initialValue; final RestorableStringN _errorText = RestorableStringN(null); final RestorableBool _hasInteractedByUser = RestorableBool(false); + final FocusNode _focusNode = FocusNode(); /// The current value of the form field. T? get value => _value; @@ -604,6 +625,7 @@ class FormFieldState extends State> with RestorationMixin { @override void dispose() { _errorText.dispose(); + _focusNode.dispose(); _hasInteractedByUser.dispose(); super.dispose(); } @@ -618,13 +640,34 @@ class FormFieldState extends State> with RestorationMixin { if (_hasInteractedByUser.value) { _validate(); } + case AutovalidateMode.onUnfocus: case AutovalidateMode.disabled: break; } } + Form.maybeOf(context)?._register(this); + + if (Form.maybeOf(context)?.widget.autovalidateMode == AutovalidateMode.onUnfocus && widget.autovalidateMode != AutovalidateMode.always || + widget.autovalidateMode == AutovalidateMode.onUnfocus) { + return Focus( + canRequestFocus: false, + skipTraversal: true, + onFocusChange: (bool value) { + if (!value) { + setState(() { + _validate(); + }); + } + }, + focusNode: _focusNode, + child: widget.builder(this), + ); + } + return widget.builder(this); } + } /// Used to configure the auto validation of [FormField] and [Form] widgets. @@ -638,4 +681,11 @@ enum AutovalidateMode { /// Used to auto-validate [Form] and [FormField] only after each user /// interaction. onUserInteraction, + + /// Used to auto-validate [Form] and [FormField] only after the field has + /// lost focus. + /// + /// In order to validate all fields of a [Form] after the first time the user interacts + /// with one, use [always] instead. + onUnfocus, } diff --git a/packages/flutter/test/widgets/form_test.dart b/packages/flutter/test/widgets/form_test.dart index fa31bbadd7..31a5e1227f 100644 --- a/packages/flutter/test/widgets/form_test.dart +++ b/packages/flutter/test/widgets/form_test.dart @@ -1126,4 +1126,177 @@ void main() { await tester.pump(); expect(find.text('test_error'), findsNothing); }); + + testWidgets('AutovalidateMode.onUnfocus', (WidgetTester tester) async { + final GlobalKey formKey = GlobalKey(); + String? errorText(String? value) => '$value/error'; + + Widget builder() { + return MaterialApp( + theme: ThemeData(), + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Form( + key: formKey, + autovalidateMode: AutovalidateMode.onUnfocus, + child: Material( + child: Column( + children: [ + TextFormField( + initialValue: 'bar', + validator: errorText, + ), + TextFormField( + initialValue: 'bar', + validator: errorText, + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(builder()); + + // No error text is visible yet. + expect(find.text(errorText('foo')!), findsNothing); + + // Enter text in the first TextFormField. + await tester.enterText(find.byType(TextFormField).first, 'foo'); + await tester.pumpAndSettle(); + + // No error text is visible yet. + expect(find.text(errorText('foo')!), findsNothing); + + // Tap on the second TextFormField to trigger validation. + // This should trigger validation for the first TextFormField as well. + await tester.tap(find.byType(TextFormField).last); + await tester.pumpAndSettle(); + + // Verify that the error text is displayed for the first TextFormField. + expect(find.text(errorText('foo')!), findsOneWidget); + expect(find.text(errorText('bar')!), findsNothing); + + // Tap on the first TextFormField to trigger validation. + await tester.tap(find.byType(TextFormField).first); + await tester.pumpAndSettle(); + + // Verify that the both error texts are displayed. + expect(find.text(errorText('foo')!), findsOneWidget); + expect(find.text(errorText('bar')!), findsOneWidget); + }); + + testWidgets('Validate conflicting AutovalidateModes', (WidgetTester tester) async { + final GlobalKey formKey = GlobalKey(); + String? errorText(String? value) => '$value/error'; + + Widget builder() { + return MaterialApp( + theme: ThemeData(), + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Form( + key: formKey, + autovalidateMode: AutovalidateMode.onUnfocus, + child: Material( + child: Column( + children: [ + TextFormField( + autovalidateMode: AutovalidateMode.always, + initialValue: 'foo', + validator: errorText, + ), + TextFormField( + autovalidateMode: AutovalidateMode.disabled, + initialValue: 'bar', + validator: errorText, + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(builder()); + + // Verify that the error text is displayed for the first TextFormField. + expect(find.text(errorText('foo')!), findsOneWidget); + + // Enter text in the TextFormField. + await tester.enterText(find.byType(TextFormField).first, 'foo'); + await tester.pumpAndSettle(); + + // Click in the second TextFormField to trigger validation. + await tester.tap(find.byType(TextFormField).last); + await tester.pumpAndSettle(); + + // No error text is visible yet for the second TextFormField. + expect(find.text(errorText('bar')!), findsNothing); + + // Now click in the first TextFormField to trigger validation for the second TextFormField. + await tester.tap(find.byType(TextFormField).first); + await tester.pumpAndSettle(); + + // Verify that the error text is displayed for the second TextFormField. + expect(find.text(errorText('bar')!), findsOneWidget); + }); + + testWidgets('FocusNode should move to next field when TextInputAction.next is received', (WidgetTester tester) async { + final GlobalKey formKey = GlobalKey(); + final FocusNode focusNode1 = FocusNode(); + final FocusNode focusNode2 = FocusNode(); + final TextEditingController controller1 = TextEditingController(); + final TextEditingController controller2 = TextEditingController(); + + final Widget widget = MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + key: formKey, + child: Column( + children: [ + TextFormField( + focusNode: focusNode1, + controller: controller1, + textInputAction: TextInputAction.next, + ), + TextFormField( + focusNode: focusNode2, + controller: controller2, + ), + ], + ), + ), + ), + ), + ), + ), + ); + + await tester.pumpWidget(widget); + + await tester.showKeyboard(find.byType(TextFormField).first); + await tester.testTextInput.receiveAction(TextInputAction.next); + await tester.pumpAndSettle(); + + expect(focusNode2.hasFocus, isTrue); + }); }