flutterautocompletefocus

How to programmatically set focus to TextField built by fieldViewBuilder of an Autocomplete widget?


Tried to give input focus to a TextField by extracting the FocusNode from the AutoComplete's fieldViewBuilder function. For this i need a setState call inside the fieldViewBuilder function, which seems to be not working. What can I do ?

...
FocusNode? myFocusNode;
  @override
  Widget build(BuildContext context) {
    myFocusNode?.requestFocus();
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          _networkEnabled
              ? 'Network is on, toggle to induce network errors.'
              : 'Network is off, toggle to allow requests to go through.',
        ),
        Switch(
          value: _networkEnabled,
          onChanged: (bool? value) {
            setState(() {
              _networkEnabled = !_networkEnabled;
            });
          },
        ),
        const SizedBox(
          height: 32.0,
        ),
        Autocomplete<String>(
          fieldViewBuilder: (BuildContext context,
              TextEditingController controller,
              FocusNode focusNode,
              VoidCallback onFieldSubmitted) 
          {
            setState(() {
              myFocusNode = focusNode;
            });
            return Padding(
              padding: const EdgeInsets.all(12.0),
              child: TextFormField(
                decoration: InputDecoration(
                  border: const OutlineInputBorder(),
                  errorText:
                      _networkError ? 'Network error, please try again.' : null,
                ),
                controller: controller,
                focusNode: focusNode,
                onFieldSubmitted: (String value) {
                  onFieldSubmitted();
                },
              ),
            );
          },
...

Solution

  • Found a solution by using a closure in an 'addPostFrameCallback' avoiding the setState call like so:

    WidgetsBinding.instance.addPostFrameCallback((_) {
      focusNode.requestFocus();
    });