sjmcdowall
sjmcdowall

Reputation: 1631

AutoFocus isn't working in multiple Stateful widgets within a PageView

So I have 5 pages in a series of "steps" to complete an action. This is all fine and dandy. I am using a PageView with the various children pages.

The issue -- is that only the first page (that has an autofocus on a TextField widget) is actually getting the focus. As the user traverses the other form type pages -- even though there is an autofocus: true on each page .. they aren't being fired and no focus is being set at all.

This is confusing behavior to me. Each page is being rendered "on the fly" (and destroyed) when going from page to page .. so not sure why the focus isn't being set.

The general widget tree is

Scaffold
   PageView
     [children pages]

So maybe it has something to do with the focus being at the Scaffold context level and thus .. ah.. well I have no idea actually.. I would think when children page 2 that has an autofocus -- would -- set the overall context autofocus again when it's built?

Rather confused -- help appreciated!

Cheers!

Upvotes: 2

Views: 1874

Answers (1)

vinayak bhanushali
vinayak bhanushali

Reputation: 243

I have had the same issue and solved it using focus node. In my case all the children of pageView were Stateful widget each

Solution:

final FocusNode _focusNode = FocusNode();

@override
void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) =>FocusScope.of(context).requestFocus(_focusNode));
}

Than in Your Widget

child: TextFormField(
    focusNode: _focusNode,
)

Upvotes: 8

Related Questions