How to shift focus to next textfield in flutter?

前端 未结 7 2137
甜味超标
甜味超标 2020-12-04 23:36

I am new to Flutter.

I am building a form with multiple text inputs using following widgets: Form, TextFormField. The keyboard that appears doesn\'t show \"next\" (w

7条回答
  •  臣服心动
    2020-12-05 00:12

    This is additional steps to CopsOnRoad answer since it doesn't work in more complex UI when there are focusable widgets in between text fields, for example:

    • when password field has a clickable toggle icon
    • when there is a button(or some other focusable widget) between fields...

    The solution here is to keep calling 'nextFocus()' until 'EditableText' is Found

       @override
        Widget build(BuildContext context) {
          return Scaffold(
            body: Column(
              children: [
                TextField(
                  decoration: InputDecoration(hintText: "TextField A"),
                  textInputAction: textInputAction1,
                  onSubmitted: (_) => context.nextEditableTextFocus(), // move focus to next
                ),
                TextField(
                  decoration: InputDecoration(hintText: "TextField B"),
                  textInputAction: textInputAction2,
                  onSubmitted: (_) => context.nextEditableTextFocus(), // move focus to next
                ),
                MaterialButton(
                 onPressed: () {},
                 color: Colors.amber,
                ),
                TextField(
                  decoration: InputDecoration(hintText: "TextField C"),
                  textInputAction: textInputAction3,
                  onSubmitted: (_) => FocusScope.of(context).unfocus(), // submit and hide keyboard
                ),
              ],
            ),
          );
        }
    

    where the extension method is:

    extension Utility on BuildContext {
      void nextEditableTextFocus() {
        do {
          FocusScope.of(this).nextFocus();
        } while (FocusScope.of(this).focusedChild.context.widget is! EditableText);
      }
    }
    

提交回复
热议问题