Search code examples
flutterfocusflutter-layoutflutter-text

Change focus to next textfield in flutter


I have a code for making Text Fields as shown below

 ...Column(
   children: <Widget>[
                      textField(text: 'User Name'),
                      SizedBox(height: 20),
                      textField(text: 'Password'), ])...

textField is a class that I made that has the following code to make a textfield. I did this to avoid code duplication,since I use textfields a lot in my applicatin.

...TextField(
    textInputAction: TextInputAction.next,
    obscureText: text == 'Password' ? true : false,
    textCapitalization: TextCapitalization.words,
    cursorColor: primaryColor,
    textAlign: TextAlign.center,
    decoration: InputDecoration(
      labelText: text,
      labelStyle: TextStyle(color: primaryColor, fontFamily: 'Bellotta'),
      filled: true,
      fillColor: Colors.white,
      border: OutlineInputBorder(...

Since I use this function to create the text field I cant use focusNode to change focus. How can I solve this issue??


Solution

  • u can specify two more parameter one for focusNode of current textfield & another one for focus u want to change e.g.

    textField(
        text: 'User Name', 
        focusNode: // your focus node, 
        nextFocusNode: // your next field focus node
    ),
    

    now u can use :

    FocusScope.of(context).requestFocus(nextFocus);
    

    tip: if u want to decrease code duplication then instead of creating textfield method u should store ur InputDecoration in var/ method.