Flutter: Auto focus CupertinoSearchTextField on page load

Here is a simple example of how auto focus a CupertinoSearchTextField after navigating to the page in Flutter

Problem

In Flutter, a Textfield or in my case a CupertinoSearchTextField does not auto focus on page load. I want it to. Here's how.

1) Define a FocusNode in your StatefulWidget

Then in initState(), slap on a delay to wait for the page transition as you wish.

class _MyPageState extends State<MyPage> {
  FocusNode _node = FocusNode();

  // ....

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 350)).then((_) {
      FocusScope.of(context).requestFocus(_node);
    });
  }

2) Attach the FocusNode to the CupertinoSearchTextField:

  Widget _buildSearchBox() {
    return CupertinoSearchTextField(
        focusNode: _node,
        // ...
    );
  }

Conclusion

Now when you push the page with that widget, you'll get it auto-focusing.

Hope this helps!

Comments: