Repository navigation
Fix focus violation when canRequestFocus set to false for all siblings in same build - #185280
Istiak-Ahmed78 wants to merge 30 commits into
Conversation
…alues (fixes flutter#184626) (flutter#184643)" (flutter#185203)" This reverts commit 8e8a194.
There was a problem hiding this comment.
Code Review
This pull request modifies focus management by deferring unfocus operations to a microtask when a FocusNode becomes unfocusable and adding checks in FocusTraversalPolicy to prevent non-focusable nodes from being selected as candidates. It also includes comprehensive regression tests for these scenarios. A logic error was identified in the focus traversal fallback implementation where a valid candidate could be incorrectly overwritten by a non-focusable node.
| if (candidate == null && !_canRequestTraversalFocus(currentNode)) { | ||
| return currentNode; | ||
| } | ||
| candidate ??= currentNode; |
There was a problem hiding this comment.
the comment says the current node is used only if it can request focus, but in this line it is used anyway?
There was a problem hiding this comment.
Right. I've mistaken. Removed the '!'
There was a problem hiding this comment.
But what if the current node cannot request focus? Wouldn't it still be returned in this line if candidate is null?
There was a problem hiding this comment.
That was a clear bug. the code was returning current node, even it is not focusable. What ever. I've handled it correct way now.
if (candidate == null) {
if (_canRequestTraversalFocus(currentNode)) {
return currentNode;
} else {
return null;
}
}this time, if it fails to find any candidate to handover the focus even if searching by _sortAllDescendants. We will check if the current node can be used or not for the focus. If it is not focusable, we will return null. Now, question may arise, what happens if, no cadidade is found?
the focus it returned to the scope not to any child node.
As I had to shift from FocusNode _findInitialFocus to FocusNode? _findInitialFocus. I made some changes related to this to handle it. Though I noticed, the functions uses this call, are already null checked. I ran the example code & both unit tests. Everything found okey. Let me know if have more queries or suggestions
| if (nodeToUnfocus.hasFocus && | ||
| !nodeToUnfocus.canRequestFocus && | ||
| nodeToUnfocus._manager != null && | ||
| nodeToUnfocus._parent != null) { |
There was a problem hiding this comment.
Why the _manager and _parent checks?
I see in dispose that _attachment gets detached, so maybe another thing to check would be _attachment.isAttached.
There was a problem hiding this comment.
Let me describe you what the _manager & _parent do.
the _manager checks if the node is still attached to a FocusManager.
The node might have been: detached from the tree (via FocusAttachment.detach()), Removed from the widget tree
If _manager is null, the node is no longer part of the focus system
and shouldn't be unfocused
Similar thing does _parent. Checks if the node still has a parent in the focus tree.
void detach() {
if (isAttached) {
// ...
_node._parent?._removeChild(_node); // This sets _parent to null
_node._attachment = null;
}
}
later
@mustCallSuper
void _removeChild(FocusNode node, {bool removeScopeFocus = true}) {
// ...
node._parent = null; // Sets _parent to null
node._clearEnclosingScopeCache();
_children.remove(node);
// ...
}But to be honest, instead of doing this multiple checks, (nodeToUnfocus._attachment?.isAttached ?? false) may be better approach. As
/// Returns true if the associated node is attached to this attachment.
///
/// It is possible to be attached to the widget tree, but not be placed in
/// the focus tree (i.e. to not have a parent yet in the focus tree).
bool get isAttached => _node._attachment == this;I'm leaving space for your opinion
| // runs, all widget canRequestFocus setters have completed, so we won't | ||
| // accidentally focus a widget that will soon have canRequestFocus=false. | ||
| final nodeToUnfocus = this; | ||
| scheduleMicrotask(() { |
There was a problem hiding this comment.
Would a post frame callback be better? They might end up being pretty similar in practice, but I find it comforting to know specifically that the node will be unfocused in the next frame. I wonder if you have thoughts.
There was a problem hiding this comment.
Hmm. That option can be an alternative. But you caught a issue with that, the extra frame! Both options has competitive pros & cons.
post frame callback, runs after after all frames rendered, costs extra frame for reflecting the unfocus, result visibility glitch.
On the other hand, scheduleMicrotask executes the queues (unfocuse) of all then rendered. Result less glitch, better performance I believe.
I expect your suggestion & help deciding the best for our case
There was a problem hiding this comment.
We're probably splitting hairs here and either way would be nearly identical in practice... But I'm mainly thinking about what happens if yet more changes to focus and/or canRequestFocus happen after the setState (talking about the example in the issue #185076) but before the next frame. Do we want to wait for all potential changes to canRequestFocus for the current frame to be made before we decide what to unfocus (the postFrameCallback approach)? Or do we want to immediately handle the unfocus so that in case subsequent changes to canRequestFocus are made, the focus is up to date?
Actually, maybe I need to understand the issue better. Do you know exactly why the final Focus does not unfocus itself in the example? It seems like even though it is the last one, we should have a code path to handle that case.
There was a problem hiding this comment.
We're probably splitting hairs here and either way would be nearly identical in practice... But I'm mainly thinking about what happens if yet more changes to focus and/or canRequestFocus happen after the setState (talking about the example in the issue #185076) but before the next frame. Do we want to wait for all potential changes to canRequestFocus for the current frame to be made before we decide what to unfocus (the postFrameCallback approach)? Or do we want to immediately handle the unfocus so that in case subsequent changes to canRequestFocus are made, the focus is up to date?
We went with scheduleMicrotask() for a few reasons, and I think
it's worth explaining the trade-off here.
The main concern you raised is valid—what happens if the user makes multiple
canRequestFocus changes in rapid succession before the frame renders? With
scheduleMicrotask(), we're reacting immediately to each change. However, with addPostFrameCallback(), we'd
wait until the frame is done rendering, so we'd see the final state of all changes.
Here's the thing though: the visual glitch is worse than the rare edge case. If
we use addPostFrameCallback(), the frame would render with a disabled node
appearing to have focus. That's immediately noticeable to the user. With
scheduleMicrotask(), focus is updated before the frame renders, so there's no
glitch. The only downside is if someone makes rapid changes (which is uncommon),
focus might bounce between nodes momentarily.
We handle this with safety checks in the microtask:
if (hasFocus && !value) {
final nodeToUnfocus = this;
scheduleMicrotask(() {
if (nodeToUnfocus.hasFocus &&
!nodeToUnfocus.canRequestFocus &&
(nodeToUnfocus._attachment?.isAttached ?? false)) {
nodeToUnfocus.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild);
}
});
}The _attachment?.isAttached check ensures we don't try to unfocus a disposed
or detached node, and the !canRequestFocus check prevents us from unfocusing
a node that's already been re-enabled. These checks catch most of the edge cases.
we prioritize avoiding the visual glitch in the common case
(disabling all siblings at once) over handling rare rapid-change scenarios. The
safety checks give us confidence that edge cases are handled correctly.
Actually, maybe I need to understand the issue better. Do you know exactly why the final Focus does not unfocus itself in the example? It seems like even though it is the last one, we should have a code path to handle that case.
Looking at the actual unfocus() implementation, it turns out
the final Focus case is already handled correctly, just not in an obvious way.
When a node calls unfocus(disposition: UnfocusDisposition.previouslyFocusedChild),
it walks up to find a focusable scope and then calls scope._doRequestFocus(findFirstFocus: true):
case UnfocusDisposition.previouslyFocusedChild:
if (scope.canRequestFocus) {
scope._focusedChildren.remove(this);
}
while (!scope!.canRequestFocus) {
scope.enclosingScope?._focusedChildren.remove(scope);
scope = scope.enclosingScope ?? _manager?.rootScope;
}
scope._doRequestFocus(findFirstFocus: true);The _doRequestFocus(findFirstFocus: true) method handles the "all children
disabled" case by looking for the first focusable child. If it doesn't find one
(because they're all disabled), it falls back to focusing the scope itself. So
the behavior is correct—focus just moves to the scope instead of bouncing to
another child.
That said, this behavior is implicit rather than explicit. We could make it
clearer by adding a comment explaining that _doRequestFocus handles the case
where no focusable child exists:
case UnfocusDisposition.previouslyFocusedChild:
if (scope.canRequestFocus) {
scope._focusedChildren.remove(this);
}
while (!scope!.canRequestFocus) {
scope.enclosingScope?._focusedChildren.remove(scope);
scope = scope.enclosingScope ?? _manager?.rootScope;
}
// Request focus on the scope. If no focusable child is found,
// focus will move to the scope itself. This correctly handles
// the case where all children become unfocusable.
scope._doRequestFocus(findFirstFocus: true);There was a problem hiding this comment.
Hi @Istiak-Ahmed78, this looks like a copy-pasted response from an AI chatbot. While we encourage using AI to brainstorm and contribute to the framework, our contribution guidelines explicitly discourage posting unfiltered AI output, especially in response to a maintainer's question.
Please review our contribution guidelines and make sure you understand the question @justinmc asked enough to draft a human-reviewed/driven response.
There was a problem hiding this comment.
@justinmc . Due to my personal issue. I'm having delay to sit with this PR to continue discussion with you. I may need more a day to be available. I'm sorry about that. I'll return soon.
There was a problem hiding this comment.
@justinmc , you caught correct. you know what? Focus 2.unfocus() is not called actualy.
Let me ellaborate.
talking about buggy behaviour (Focus 0 -> Focus 1 -> Focus 2 -> Focus 1):
when the setters are calling syncronously, when unfocus is called of Focus 1,
flutter/packages/flutter/lib/src/widgets/focus_manager.dart
Lines 916 to 962 in 143c87d
it falls this case
then the operation of finding next focus starts here
Lets see what is written in
void _doRequestFocusflutter/packages/flutter/lib/src/widgets/focus_manager.dart
Lines 1495 to 1516 in 143c87d
while (_focusedChildren.isNotEmpty &&
(!_focusedChildren.last.canRequestFocus || _focusedChildren.last.enclosingScope == null)) {
_focusedChildren.removeLast();
}Here this block of code is skipped. Why? the right side condition (!_focusedChildren.last.canRequestFocus || _focusedChildren.last.enclosingScope == null)) becomes false
The below part is also skipped. Why? findFirstFocus this property is false, cause we here through this: scope._doRequestFocus(findFirstFocus: true) // findFirstFocus is true and focusedChild is non-null
if (!findFirstFocus || focusedChild == null) {
if (canRequestFocus) {
_setAsFocusedChildForScope();
_markNextFocus(this);
}
return;
}this line is called of _doRequestFocus
Now let's see how
void _doRequestFocus looks likeflutter/packages/flutter/lib/src/widgets/focus_manager.dart
Lines 1169 to 1191 in 143c87d
in this code,
_markNextFocus(this); part is calledflutter/packages/flutter/lib/src/widgets/focus_manager.dart
Lines 1901 to 1910 in 143c87d
then
_markNeedsUpdate(); is called and _markedForFocus = node // Focus 2now lets see what is written in
void _markNeedsUpdate()flutter/packages/flutter/lib/src/widgets/focus_manager.dart
Lines 1920 to 1932 in 143c87d
you see that line scheduleMicrotask(applyFocusChangesIfNeeded);? this method schedule a queue to execute applyFocusChangesIfNeeded, this applyFocusChangesIfNeeded is called after current synchronous works (like current widget updates). in that call
if (_markedForFocus != null && _markedForFocus != _primaryFocus) {
final Set<FocusNode> previousPath = previousFocus?.ancestors.toSet() ?? <FocusNode>{};
final Set<FocusNode> nextPath = _markedForFocus!.ancestors.toSet();
// ...
_primaryFocus = _markedForFocus; // Was Focus 2, Can you remeber that? I mentioned eariler
_markedForFocus = null;
}That means after all setters run completes _primaryFocus is given to Focus 2.
Now the question is, why unfocus() is not executed when setter of Focus 2 is ran?
the answers hides in the condition of unfocus() to run
flutter/packages/flutter/lib/src/widgets/focus_manager.dart
Lines 546 to 548 in 143c87d
hasFocus this parameter fails here (false).flutter/packages/flutter/lib/src/widgets/focus_manager.dart
Lines 766 to 767 in 143c87d
for
hasPrimaryFocus , Manager’s primary is still Focus 1, not Focus 2.and about
primaryFocus.ancestors.contains(this), Focus 2 is a sibling of the primary leaf, not an ancestor of it.
There was a problem hiding this comment.
I think the faulty behaviour is now crystal clear to you.
There was a problem hiding this comment.
@justinmc , you may be confused. But I just expended the story of the Senario B, when Focus 1's unfocus is called to Focus 2's setters why not unfocus is not called. But this time, I walked you through each line of codes execution. I'm waiting for your thought
There was a problem hiding this comment.
That microtask that you pointed out is the key here (scheduleMicrotask(applyFocusChangesIfNeeded)). So here is my understanding:
- The canRequestFocus setter is called sequentially with false for each FocusNode in the list.
- For a node that currently has focus, it will try to find a previously focused node to pass the focus to.
- In the repro case, it will find a previously focused node that has canRequestFocus set to true, because its canRequestFocus setter has not been called yet.
- It tries to focus that node, but it does so asynchronously (
scheduleMicrotask(applyFocusChangesIfNeeded)). - Before the microtask runs, the canRequestFocus setter is called for the node that is scheduled to receive focus.
- applyFocusChangesIfNeeded runs as a microtask and focuses the node that just had canRequestFocus set to false. It does not seem to consider that canRequestFocus is false, so it gives the node focus anyway.
If I'm understanding correctly, isn't it a bug that applyFocusChangesIfNeeded does not consider canRequestFocus? Since it's called in a microtask, I think we should handle the possibility that canRequestFocus has changed since the microtask was scheduled.
| if (candidate != null && !_canRequestTraversalFocus(candidate)) { | ||
| candidate = null; | ||
| } |
There was a problem hiding this comment.
Can you explain this change?
There was a problem hiding this comment.
Okey, let me explain it.
If candidate exists AND cannot receive traversal focus:
Discard it (set to null)Basically we are checking if focused child can receive traversal focus or not. For example when TextField(enabled: false) or Focus(skipTraversal: true)
static bool _canRequestTraversalFocus(FocusNode node) {
return node.canRequestFocus && !node.skipTraversal;
}If candidate exists AND cannot receive focus, Set candidate = null (Discard it), mark it that it should not be selected as possible candidate for next focus searching
| debugPrint = oldDebugPrint; | ||
| } | ||
| }); | ||
| group('FocusNode.canRequestFocus regression tests', () { |
There was a problem hiding this comment.
Is the indentation off here? Hard to tell on GitHub...
| 10, | ||
| (i) => Focus( | ||
| focusNode: focusNodes[i], | ||
| canRequestFocus: false, |
There was a problem hiding this comment.
Instead of pumping the whole widget tree again with this small change, you should use a StatefulWidget and call setState to change it.
Here's a test that does something similar as an example:
There was a problem hiding this comment.
I've handled this issue, Please check the changes
|
@victorsanni , @justinmc can you please go though the changes again? |
|
I've marked this PR as not ready to port to flutter/packages yet. The changes not in the material or cupertino libraries will remain here. |
|
Advice for PR splitting: Since this touches material/cupertino along with other parts of flutter/flutter, it will need to be split up. If the material/cupertino changes are dependent on the other non-material/cupertino changes in this PR, then the material/cupertino changes will need to wait for them to roll to stable before they can be ported over to material_ui/cupertino_ui in flutter/packages (which uses the stable branch).
|
|
Hi @justinmc , @victorsanni! Any more work needed here? Let me know. I'm waiting.. |
Hi @Istiak-Ahmed78 as we shared above, this will need to be moved over to flutter/packages, but it is not quite time to do that yet. We will let you know when it is ready and provide instructions then. |
Ok. Got that |
victorsanni
left a comment
There was a problem hiding this comment.
Hi @Istiak-Ahmed78, thanks for your work here so far. I think we can move this PR along by splitting it into framework-only and non-framework-only fixes. From my understanding, the focus manager validation (i.e _findValidFocusOrFallback) will not require API breaks or Material/Cupertino changes? So is it possible to split the PR so we can land the validation changes while waiting for the design packages to be ready for the findLastFocus API changes?
@victorsanni, We have two kinds of changes. One: Framework related. this involves |
|
@Istiak-Ahmed78 We have started porting PRs to the packages! :) Please see #188444 for the guide. Yes, please split the PR into a framework one and a package one. Thank you very much! |
Okey. Unfortunatly, recently my PC got damaged. Soon I'll repair it. And return to this PR. Please allow me a bit of time |
|
I'm so sorry to hear that. Best wishes to you, and take your time! |
|
After reading #188444 . I came to understand that I need to create 2 additional PRs: One will land on |
|
Yes, there is a PR limit in place. To work around this, any open PRs you are not actively working on can be made drafts, these do not contribute to the limit. |
|
Our framework related changes go in this PR |
|
Let me convert this PR to a draft so the new PR can be ready for review. :) |
|
This pull request has been changed to a draft. The currently pending flutter-gold status will not be able to resolve until a new commit is pushed or the change is marked ready for review again. For more guidance, visit Writing a golden file test for Reviewers: Read the Tree Hygiene page and make sure this patch meets those guidelines before LGTMing. |
…s in same build (flutter#191536) This PR is a split of flutter#185280. Holds only framework related changes. Fixes flutter#185076, fixes an issue where a widget unexpectedly receives primary focus when `canRequestFocus` is set to `false` for all sibling widgets in the same build cycle. This is reviewable in draft state. ## Pre-launch Checklist - [x] I read the [Contributor Guide](https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview) and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines](https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines) and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene](https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md) wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide](https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md), including [Features we expect every widget to implement]. - [x] I signed the [CLA](https://cla.developers.google.com/). - [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](https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes) and added [Data Driven Fixes](https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md ) where supported. - [ ] All existing and new tests are passing. Co-authored-by: Victor Sanni <[email protected]>

Fixes issue where a widget with
canRequestFocus=falsecould unexpectedly receive primary focus whencanRequestFocusis set tofalsefor all sibling widgets in the same build cycle.To address the issue added validation in
applyFocusChangesIfNeeded()and improved focus traversal logic:Now it checks
canRequestFocusinapplyFocusChangesIfNeeded(), to be sure that the requested focus is anymore focusable or not.Breaking Change⚠️
API Change
The return type of
FocusTraversalPolicy.findLastFocus()has changed:FocusNode findLastFocus(FocusNode currentNode)FocusNode? findLastFocus(FocusNode currentNode)Why This Change is Necessary
Previously
findLastFocuswould returncurrentNodewhen there are no descendants. But it wouldn't check whether is focusable or not. So there can be cases when theres no really focusable node available.By making the return type nullable we can explicitly return
nullwhen no focusable node is foundMigration Required
All callers of
findLastFocus()must be updated to handle null:Related Issues
Checklist
///).