Flutter : How to add autofocus to dynamically created TextFormFields in flutter?

Viewed 724

I am getting a dynamic number of TextFormFields from the backend. Some fields are required and others are not. As it's dynamic I can't use FocusScope. What I want to achieve is When the user clicks on the next button, the focus should be redirected to the required fields which are empty. How can I achieve this? I can't provide code.

2 Answers

You can use this onEditingComplete, which will show you this example :

Note: If you made the static method just pass context to it.

It worked for me right.

TextField(
        
        controller: controller,
        keyboardType: type,
        autofocus: false,
        enableInteractiveSelection:  false,
        maxLength: maxLength,
        
        ///Using this :
        onEditingComplete: () => FocusScope.of(context).nextFocus(),

        decoration: InputDecoration(
            hintText: 'Enter text',
            border: InputBorder.none,
            counterText: "",
            contentPadding:
                EdgeInsets.symmetric(vertical: 18.0, horizontal: 24.0)),
      )

You should post some code always, here you go,I didn't try it


class MyTextFieldHolder {
  final controller = TextEditingController();
  final focusNode = FocusNode();

  Widget builder(context) {
    return TextField(
      focusNode: focusNode,
      controller: controller,
    );
  }
  
  dispose(){
    controller.dispose();
    focusNode.dispose();
  }
}

class MyForm extends StatefulWidget {
  final List<dynamic> fields;

  const MyForm({Key key, this.fields}) : super(key: key);
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {
  List<MyTextFieldHolder> _holders = [];

  @override
  void initState() {
    widget.fields.forEach((element) {
      _holders.add(MyTextFieldHolder());
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      child: ListView.builder(
        itemCount: _holders.length,
        itemBuilder: (context, i) {
          return _holders[i].builder(context);
        },
      ),
    );
  }
  
  bool _goToNextEmptyField(){
    for(final holder in _holders){
      if(holder.controller.text.isEmpty){
        holder.focusNode.requestFocus();
        return true;
      }
    }
    return false;
  }
}
Related