flutter focus on a CupertinoTextField after pushing to the route which contains that field

Issue

I have an tab based app with multi navigation stacks for each tab (using CupertinoTabScaffold)

i’m trying to focus on a CupertinoTextField after I push to a route that has the field with:

screen 1:

Navigator.of(context).push(CupertinoPageRoute<void>(
  builder: (BuildContext context) => SearchResultPage(),
));

screen 2:

  @override
  void initState() {
    Timer(Duration(milliseconds: 1000), () {
      FocusScope.of(context).requestFocus(_focus);
    });
    super.initState();
  }

this code works but if I remove the timer I get an error which says:

flutter: When an inherited widget changes, for example if the value of Theme.of() changes, its dependent
flutter: widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor
flutter: or an initState() method, then the rebuilt dependent widget will not reflect the changes in the
flutter: inherited widget.
flutter: Typically references to inherited widgets should occur in widget build() methods. Alternatively,
flutter: initialization based on inherited widgets can be placed in the didChangeDependencies method, which
flutter: is called after initState and whenever the dependencies change thereafter.

Solution

As defined in flutter docs for initState method:

Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).

This means this function is used for initialization and it runs before the build method is even called, so when you remove the timer, you are actually trying to get focus on a widget which is not yet built/rendered according the framework. That’s why the error.

Answered By – Shubham Bhardwaj

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.