File tree Expand file tree Collapse file tree 2 files changed +53
-2
lines changed Expand file tree Collapse file tree 2 files changed +53
-2
lines changed Original file line number Diff line number Diff line change @@ -354,9 +354,11 @@ class FormState extends State<Form> {
354
354
final bool validateOnFocusChange = widget.autovalidateMode == AutovalidateMode .onUnfocus;
355
355
356
356
for (final FormFieldState <dynamic > field in _fields) {
357
- if (! validateOnFocusChange || ! field._focusNode.hasFocus) {
357
+ final bool hasFocus = field._focusNode.hasFocus;
358
+
359
+ if (! validateOnFocusChange || ! hasFocus || (validateOnFocusChange && hasFocus)) {
358
360
final bool isFieldValid = field.validate ();
359
- hasError = ! isFieldValid || hasError ;
361
+ hasError | = ! isFieldValid;
360
362
// Ensure that only the first error message gets announced to the user.
361
363
if (errorMessage.isEmpty) {
362
364
errorMessage = field.errorText ?? '' ;
Original file line number Diff line number Diff line change @@ -1505,4 +1505,53 @@ void main() {
1505
1505
expect (find.text (errorText ('foo' )), findsOneWidget);
1506
1506
expect (find.text (errorText ('bar' )), findsOneWidget);
1507
1507
});
1508
+
1509
+ testWidgets ('AutovalidateMode.onUnfocus should validate all fields manually with FormState' , (WidgetTester tester) async {
1510
+ final GlobalKey <FormState > formKey = GlobalKey <FormState >();
1511
+ const Key fieldKey = Key ('form field' );
1512
+ String errorText (String ? value) => '$value /error' ;
1513
+
1514
+ await tester.pumpWidget (
1515
+ MaterialApp (
1516
+ home: Center (
1517
+ child: Form (
1518
+ key: formKey,
1519
+ autovalidateMode: AutovalidateMode .onUnfocus,
1520
+ child: Material (
1521
+ child: Column (
1522
+ children: < Widget > [
1523
+ TextFormField (
1524
+ key: fieldKey,
1525
+ initialValue: 'foo' ,
1526
+ validator: errorText,
1527
+ ),
1528
+ TextFormField (
1529
+ initialValue: 'bar' ,
1530
+ validator: errorText,
1531
+ ),
1532
+ ],
1533
+ ),
1534
+ ),
1535
+ ),
1536
+ ),
1537
+ ),
1538
+ );
1539
+
1540
+
1541
+ // Focus on the first field.
1542
+ await tester.tap (find.byKey (fieldKey));
1543
+ await tester.pump ();
1544
+
1545
+ // Check no error messages are displayed initially.
1546
+ expect (find.text ('foo/error' ), findsNothing);
1547
+ expect (find.text ('bar/error' ), findsNothing);
1548
+
1549
+ // Validate all fields manually using FormState.
1550
+ expect (formKey.currentState! .validate (), isFalse);
1551
+ await tester.pump ();
1552
+
1553
+ // Check error messages are displayed.
1554
+ expect (find.text ('foo/error' ), findsOneWidget);
1555
+ expect (find.text ('bar/error' ), findsOneWidget);
1556
+ });
1508
1557
}
You can’t perform that action at this time.
0 commit comments