Skip to content

Commit 90a9670

Browse files
hoyahozzLongCatIsLooong
authored andcommitted
[iOS] Restore Flutter text focus after native responder recovery (flutter#191781)
Fixes flutter#189051 On iOS 26, UIKit resigns the native text responder during a quick app switch and restores it on return. The engine reports the resignation to the framework as `onConnectionClosed` but never reports the restoration, so the keyboard comes back while every `FocusNode` stays unfocused and typing goes nowhere. I filed that issue, [together with a sample app that uses nothing but plain `TextField` widgets.](https://github.com/hoyahozz/ios-keyboard-stuck-after-app-switch) ### Root cause Instrumented unpatched engine, iPhone 17 / iOS 26.6 : ```text 18:54:13.415 resignFirstResponder client=1 18:54:13.420 framework focus cleared (onConnectionClosed) 18:54:13.488 AppLifecycleState.paused 18:54:13.783 becomeFirstResponder client=1 <-- UIKit restores the same view 18:54:14.042 AppLifecycleState.resumed 18:54:14.043 all Flutter text fields focus=false 18:54:14.272 viewInsets.bottom=physical=924.0, logical=308.0 ``` The `becomeFirstResponder` never reaches Dart. There is no reverse message for "UIKit restored the same view", so only the framework half stays down. I cannot see UIKit's internals, so I compared behaviour instead. A standalone UIKit app with a single `UITextField` and no Flutter, built once and installed on both devices, produced this sequence only on iOS 26 : - iPhone 15 Pro / iOS 18.1.1 : the field stays first responder across the switch, with no resignation. - iPhone 17 / iOS 26.6 : `willResignActive → resignFirstResponder → didEndEditing`, then `willEnterForeground → becomeFirstResponder → didBeginEditing`. Plain UIKit recovers on its own, because `didBeginEditing` puts the field back into editing. Flutter has no equivalent signal. I cannot say why UIKit does this and Apple does not document it, so I treated it as a behaviour difference observed from **iOS 26** onward and fixed the Flutter side of the boundary, which does not depend on the reason. ### The fix `FlutterTextInputView` now tracks *why* its responder state changed, and sends the existing `TextInputClient.onFocusReceived` when UIKit restores it. - A non-framework `resignFirstResponder` on a valid client arms a one-shot restore flag. - A real `false → true` restoration of the same view consumes the flag and sends one notification, so it fires at most once per cycle. - `TextInput.show`, `TextInput.hide`, `TextInput.finishAutofillContext` and `TextInput.setClient` cancel it. `showTextInput`, `hideTextInput` and `triggerAutofillSave` now call `becomeFirstResponderFromFramework` / `resignFirstResponderFromFramework`, which is how framework-driven changes are kept out of the classification. - Interactive keyboard dismissal never arms it. - `onConnectionClosed` still fires unchanged, so real handoffs to native inputs and system menus are unaffected. - No framework changes. `TextInput` still matches the client id, and `EditableTextState.onFocusReceived` still checks `mounted`, `_hasFocus` and `canRequestFocus`, so a stale client cannot steal focus. The guarantee is narrow : *if UIKit restores the same responder before the framework declares a new input state, the existing Dart guards get exactly one chance to accept it.* ### Tests New Objective-C tests cover : - one notification per platform `resign → become` cycle - no notification when either side of the transition came from the framework - interactive keyboard dismissal never arming - `setClient` cancelling a pending restoration, for both a new and a repeated id - `show` / `hide` / `finishAutofillContext` going through the wrappers - the delegate serialising to `TextInputClient.onFocusReceived` ### Validation on device iPhone 17 / iOS 26.6, using the sample app from the issue. Same app source and same Flutter revision in both runs. Before, the keyboard returns but no field is focused and typing goes nowhere; after, the same field keeps focus across the switch. #### Before https://github.com/user-attachments/assets/b70e4875-7737-46cb-a3db-738817f5b04c #### After https://github.com/user-attachments/assets/045efe24-0cfd-458b-a567-7fe8fd9def73 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: LongCatIsLooong <[email protected]>
1 parent 71ff9b6 commit 90a9670

5 files changed

Lines changed: 333 additions & 7 deletions

File tree

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1339,6 +1339,14 @@ - (void)flutterTextInputView:(FlutterTextInputView*)textInputView
13391339
});
13401340
}
13411341

1342+
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
1343+
didRestoreFirstResponderWithTextInputClient:(int)client
1344+
result:(FlutterResult)callback {
1345+
[self.textInputChannel invokeMethod:@"TextInputClient.onFocusReceived"
1346+
arguments:@[ @(client) ]
1347+
result:callback];
1348+
}
1349+
13421350
#pragma mark - Undo Manager Delegate
13431351

13441352
- (void)handleUndoWithDirection:(FlutterUndoRedoDirection)direction {

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineTest.mm‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,30 @@ - (void)testFlutterTextInputViewDidResignFirstResponderWillCallTextInputClientCo
489489
OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/textinput" message:encodedMethodCall]);
490490
}
491491

492+
- (void)testFlutterTextInputViewDidRestoreFirstResponderWillCallTextInputClientOnFocusReceived {
493+
id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]);
494+
FlutterEngine* engine = [[FlutterEngine alloc] init];
495+
[engine setBinaryMessenger:mockBinaryMessenger];
496+
[engine runWithEntrypoint:FlutterDefaultDartEntrypoint initialRoute:@"test"];
497+
FlutterMethodCall* methodCall =
498+
[FlutterMethodCall methodCallWithMethodName:@"TextInputClient.onFocusReceived"
499+
arguments:@[ @(123) ]];
500+
NSData* encodedMethodCall = [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:methodCall];
501+
NSData* encodedReply = [[FlutterJSONMethodCodec sharedInstance] encodeSuccessEnvelope:@NO];
502+
id mockBinaryReply = [OCMArg invokeBlockWithArgs:encodedReply, nil];
503+
OCMStub([mockBinaryMessenger sendOnChannel:@"flutter/textinput"
504+
message:encodedMethodCall
505+
binaryReply:mockBinaryReply]);
506+
507+
__block id focusReceivedResult;
508+
[engine flutterTextInputView:nil
509+
didRestoreFirstResponderWithTextInputClient:123
510+
result:^(id result) {
511+
focusReceivedResult = result;
512+
}];
513+
XCTAssertEqualObjects(focusReceivedResult, @NO);
514+
}
515+
492516
- (void)testFlutterEngineUpdatesDisplays {
493517
FlutterEngine* engine = [[FlutterEngine alloc] init];
494518
id mockEngine = OCMPartialMock(engine);

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
#import <Foundation/Foundation.h>
99

10+
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h"
11+
1012
@class FlutterTextInputPlugin;
1113
@class FlutterTextInputView;
1214

@@ -65,6 +67,9 @@ typedef NS_ENUM(NSInteger, FlutterFloatingCursorDragState) {
6567
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView removeTextPlaceholder:(int)client;
6668
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
6769
didResignFirstResponderWithTextInputClient:(int)client;
70+
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
71+
didRestoreFirstResponderWithTextInputClient:(int)client
72+
result:(FlutterResult)callback;
6873
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
6974
willDismissEditMenuWithTextInputClient:(int)client;
7075
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm‎

Lines changed: 63 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,8 @@ @interface FlutterTextInputView ()
808808
@property(nonatomic, strong) NSArray<NSDictionary*>* editMenuItems;
809809

810810
- (void)setEditableTransform:(NSArray*)matrix;
811+
- (BOOL)becomeFirstResponderFromFramework;
812+
- (BOOL)resignFirstResponderFromFramework;
811813
@end
812814

813815
@implementation FlutterTextInputView {
@@ -825,6 +827,12 @@ @implementation FlutterTextInputView {
825827
bool _isFloatingCursorActive;
826828
CGPoint _floatingCursorOffset;
827829
bool _enableInteractiveSelection;
830+
BOOL _isResigningFirstResponderFromFramework;
831+
// A non-framework resign arms a one-shot notification for this exact view. The responder API
832+
// does not reveal which object, if any, takes focus next, so a handoff to a native input can arm
833+
// it too. Framework responder calls and client updates cancel it before UIKit can restore stale
834+
// input state.
835+
BOOL _shouldNotifyFrameworkOnFirstResponderRestore;
828836
UITextInteraction* _textInteraction API_AVAILABLE(ios(13.0));
829837
}
830838

@@ -1180,6 +1188,7 @@ - (BOOL)respondsToSelector:(SEL)selector {
11801188
}
11811189

11821190
- (void)setTextInputClient:(int)client {
1191+
_shouldNotifyFrameworkOnFirstResponderRestore = NO;
11831192
_textInputClient = client;
11841193
_hasPlaceholder = NO;
11851194
}
@@ -1348,17 +1357,64 @@ - (BOOL)canBecomeFirstResponder {
13481357
return _textInputClient != 0;
13491358
}
13501359

1360+
- (BOOL)becomeFirstResponder {
1361+
BOOL wasFirstResponder = self.isFirstResponder;
1362+
BOOL success = [super becomeFirstResponder];
1363+
if (success && !wasFirstResponder && self.isFirstResponder &&
1364+
_shouldNotifyFrameworkOnFirstResponderRestore) {
1365+
_shouldNotifyFrameworkOnFirstResponderRestore = NO;
1366+
int client = _textInputClient;
1367+
__weak FlutterTextInputView* weakSelf = self;
1368+
FlutterResult handleResult = ^(id result) {
1369+
[weakSelf handleFirstResponderRestoreResult:result client:client];
1370+
};
1371+
// Existing framework client and FocusNode guards decide whether to accept the restored focus.
1372+
[self.textInputDelegate flutterTextInputView:self
1373+
didRestoreFirstResponderWithTextInputClient:client
1374+
result:handleResult];
1375+
}
1376+
return success;
1377+
}
1378+
1379+
- (void)handleFirstResponderRestoreResult:(id)result client:(int)client {
1380+
if ([result isKindOfClass:[NSNumber class]] && [result boolValue]) {
1381+
return;
1382+
}
1383+
// The framework declined the restored focus or failed to answer. Don't leave the keyboard up
1384+
// without a framework client behind it, unless the view has been given another client since the
1385+
// restore was reported.
1386+
if (client == _textInputClient && self.isFirstResponder) {
1387+
[self resignFirstResponderFromFramework];
1388+
}
1389+
}
1390+
13511391
- (BOOL)resignFirstResponder {
1392+
BOOL wasFirstResponder = self.isFirstResponder;
13521393
BOOL success = [super resignFirstResponder];
1353-
if (success) {
1354-
if (!_preventCursorDismissWhenResignFirstResponder) {
1355-
[self.textInputDelegate flutterTextInputView:self
1356-
didResignFirstResponderWithTextInputClient:_textInputClient];
1394+
if (success && !_preventCursorDismissWhenResignFirstResponder) {
1395+
if (wasFirstResponder) {
1396+
_shouldNotifyFrameworkOnFirstResponderRestore =
1397+
!_isResigningFirstResponderFromFramework && _textInputClient != 0;
13571398
}
1399+
[self.textInputDelegate flutterTextInputView:self
1400+
didResignFirstResponderWithTextInputClient:_textInputClient];
13581401
}
13591402
return success;
13601403
}
13611404

1405+
- (BOOL)becomeFirstResponderFromFramework {
1406+
_shouldNotifyFrameworkOnFirstResponderRestore = NO;
1407+
return [self becomeFirstResponder];
1408+
}
1409+
1410+
- (BOOL)resignFirstResponderFromFramework {
1411+
_shouldNotifyFrameworkOnFirstResponderRestore = NO;
1412+
_isResigningFirstResponderFromFramework = YES;
1413+
BOOL success = [self resignFirstResponder];
1414+
_isResigningFirstResponderFromFramework = NO;
1415+
return success;
1416+
}
1417+
13621418
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
13631419
if (action == @selector(paste:)) {
13641420
// Forbid pasting images, memojis, or other non-string content.
@@ -2869,7 +2925,7 @@ - (void)startLiveTextInput {
28692925
- (void)showTextInput {
28702926
_activeView.viewResponder = _viewResponder;
28712927
[self addToInputParentViewIfNeeded:_activeView];
2872-
[_activeView becomeFirstResponder];
2928+
[_activeView becomeFirstResponderFromFramework];
28732929
}
28742930

28752931
- (void)enableActiveViewAccessibility {
@@ -2880,7 +2936,7 @@ - (void)enableActiveViewAccessibility {
28802936
}
28812937

28822938
- (void)hideTextInput {
2883-
[_activeView resignFirstResponder];
2939+
[_activeView resignFirstResponderFromFramework];
28842940

28852941
// Remove the input view from the view hierarchy after resigning first responder.
28862942
// This flag is set by clearTextInputClient when autofillContext is empty.
@@ -2894,7 +2950,7 @@ - (void)hideTextInput {
28942950
}
28952951

28962952
- (void)triggerAutofillSave:(BOOL)saveEntries {
2897-
[_activeView resignFirstResponder];
2953+
[_activeView resignFirstResponderFromFramework];
28982954

28992955
if (saveEntries) {
29002956
// Make all the input fields in the autofill context visible,

0 commit comments

Comments
 (0)