skip to Main Content

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();
                },
              ),
            );
          },
...

2

Answers


  1. Chosen as BEST ANSWER

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

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

  2. You can use a postframeCallback to have focus on Autocomplete.

      FocusNode? focusNode;
      @override
      void initState() {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          focusNode?.requestFocus();
        });
        super.initState();
      }
    
    

    And use

    Autocomplete<String>(
      fieldViewBuilder: (BuildContext context,
          TextEditingController controller,
          FocusNode f,
          VoidCallback onFieldSubmitted) {
        focusNode ??= f;
        return Padding(....),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search