diff --git a/packages/flutter/lib/src/cupertino/text_field.dart b/packages/flutter/lib/src/cupertino/text_field.dart index 4602082bf7..0dc8027713 100644 --- a/packages/flutter/lib/src/cupertino/text_field.dart +++ b/packages/flutter/lib/src/cupertino/text_field.dart @@ -653,6 +653,7 @@ class _CupertinoTextFieldState extends State with Restoratio if (widget.controller == null) { _createLocalController(); } + _effectiveFocusNode.canRequestFocus = widget.enabled ?? true; } @override @@ -665,11 +666,7 @@ class _CupertinoTextFieldState extends State with Restoratio _controller!.dispose(); _controller = null; } - final bool isEnabled = widget.enabled ?? true; - final bool wasEnabled = oldWidget.enabled ?? true; - if (wasEnabled && !isEnabled) { - _effectiveFocusNode.unfocus(); - } + _effectiveFocusNode.canRequestFocus = widget.enabled ?? true; } @override diff --git a/packages/flutter/test/cupertino/text_field_test.dart b/packages/flutter/test/cupertino/text_field_test.dart index 836d386237..a5c3a5d845 100644 --- a/packages/flutter/test/cupertino/text_field_test.dart +++ b/packages/flutter/test/cupertino/text_field_test.dart @@ -2707,6 +2707,43 @@ void main() { expect(tapCount, 1); }); + testWidgets('Focus test when the text field is disabled', (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + await tester.pumpWidget( + CupertinoApp( + home: Center( + child: CupertinoTextField( + focusNode: focusNode, + ), + ), + ), + ); + + expect(focusNode.hasFocus, false); // initial status + + // Should accept requestFocus. + focusNode.requestFocus(); + await tester.pump(); + expect(focusNode.hasFocus, true); + + // Disable the text field, now it should not accept requestFocus. + await tester.pumpWidget( + CupertinoApp( + home: Center( + child: CupertinoTextField( + enabled: false, + focusNode: focusNode, + ), + ), + ), + ); + + // Should not accept requestFocus. + focusNode.requestFocus(); + await tester.pump(); + expect(focusNode.hasFocus, false); + }); + testWidgets( 'text field respects theme', (WidgetTester tester) async {