diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index f9a13076c8..7b19f46423 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -1154,8 +1154,12 @@ class EditableTextState extends State with AutomaticKeepAliveClien void didChangeDependencies() { super.didChangeDependencies(); if (!_didAutoFocus && widget.autofocus) { - FocusScope.of(context).autofocus(widget.focusNode); _didAutoFocus = true; + SchedulerBinding.instance.addPostFrameCallback((_) { + if (mounted) { + FocusScope.of(context).autofocus(widget.focusNode); + } + }); } } diff --git a/packages/flutter/test/widgets/editable_text_test.dart b/packages/flutter/test/widgets/editable_text_test.dart index 439beb7a45..bf715c3797 100644 --- a/packages/flutter/test/widgets/editable_text_test.dart +++ b/packages/flutter/test/widgets/editable_text_test.dart @@ -4178,6 +4178,37 @@ void main() { } expect(tester.testTextInput.editingState['text'], 'flutter is the best!...'); }); + + testWidgets('autofocus:true on first frame does not throw', (WidgetTester tester) async { + final TextEditingController controller = TextEditingController(text: testText); + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + + await tester.pumpWidget(MaterialApp( + home: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: FocusNode(), + style: Typography.material2018(platform: TargetPlatform.android).black.subtitle1, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + )); + + + await tester.pumpAndSettle(); // Wait for autofocus to take effect. + + final dynamic exception = tester.takeException(); + expect(exception, isNull); + }); } class MockTextSelectionControls extends Mock implements TextSelectionControls {