How to shift focus to next textfield in flutter?

前端 未结 7 2148
甜味超标
甜味超标 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-04 23:55

    Found a way to achieve it.

    1. Displaying Next Icon instead of Done - setting textInputAction parameter to TextInputAction.next

    2. Using onFieldSubmitted callback to request focus node of next field.

      class FormWidget extends StatelessWidget{    
         final focus = FocusNode();
         @override
         Widget build(BuildContext context) {
          return Form(
            child: SingleChildScrollView(
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  TextFormField(
                    textInputAction: TextInputAction.next,
                    autofocus: true,
                    decoration: InputDecoration(labelText: "Input 1"),
                    onFieldSubmitted: (v){
                      FocusScope.of(context).requestFocus(focus);
                    },
                  ),
                  TextFormField(
                    focusNode: focus,
                    decoration: InputDecoration(labelText: "Input 2"),
                  ),
                ],
              ),
            ),
          );
        }
      }
      

    Edit: As stated in the documentation (flutter.io/docs/cookbook/forms/focus), - we also need to manage FocusNode lifecycle. So, init FocusNode in the init() method and dispose in dispose() of the parent Widget. - @AntonDerevyanko

    Update: The same can be achieved without FocusNode and FocusScopeNode, by simply calling FocusScope.of(context).nextFocus(), take a look at CopsOnRoad solution on how to do that. For more info check doc.

提交回复
热议问题