initstate初始化时如何聚焦文本字段

Rut*_*ana 2 textfield dart flutter flutter-layout

我想在初始化 initstate 时聚焦我的文本字段。例如。当我打开任何页面时,如果有任何文本字段,则文本字段需要自动聚焦。

TextFormField(

                          focusNode: focusNode,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: orientation == Orientation.portrait
                                ? MediaQuery.of(context).size.width * 0.025
                                : MediaQuery.of(context).size.width * 0.015,
                          ),
                          validator: (val) => Validators.validateRequired(
                              val, " Product Baarcode"),
                          controller: _addproduct,
                          // focusNode: _addproductFocusNode,
                          decoration: InputDecoration(
                            errorStyle: TextStyle(color: Colors.yellow),
                            enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(color: Colors.white),
                            ),
                            fillColor: Colors.white,
                            focusedBorder: UnderlineInputBorder(
                              borderSide: BorderSide(color: Colors.white),
                            ),
                            hintStyle: TextStyle(color: Colors.white),
                            labelStyle: TextStyle(color: Colors.white),
                            filled: false,
                            prefixIcon: Icon(
                              FontAwesomeIcons.barcode,
                              color: Colors.white,
                            ),
                            labelText: "Enter Product Barcode",
                            hintText: "Enter Product Barcode",
                          ),
                          onFieldSubmitted: (val) {
                            _addProduct();
                          },
                        ),
Run Code Online (Sandbox Code Playgroud)

Pet*_*dad 7

如果您希望TextField在打开页面时获得焦点,则可以使用以下属性autofocus

TextField(
  autofocus: true,
);
Run Code Online (Sandbox Code Playgroud)

如果您希望它在稍后的时间点集中,那么您可以使用该类FocusNode。您可以在此处查看示例:

https://flutter.dev/docs/cookbook/forms/focus#focus-a-text-field-when-a-button-is-tapped