【问题标题】:How to focus text field when initstate is initialized初始化initstate时如何聚焦文本字段
【发布时间】:2020-05-01 21:47:41
【问题描述】:

我想在初始化 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();
                          },
                        ),

【问题讨论】:

    标签: flutter dart textfield flutter-layout


    【解决方案1】:

    如果您希望在打开页面时关注TextField,则可以使用属性autofocus

    TextField(
      autofocus: true,
    );
    

    如果你想让它在稍后的时间点得到关注,那么你可以使用 FocusNode 类。您可以在此处查看示例:

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

    【讨论】:

    【解决方案2】:

    您可以使用TextFormField 的autofocus: 参数并将其设置为true。但是,这也会使键盘立即出现。

    【讨论】:

    • 你有键盘的解决方案吗?当文本字段处于焦点时,我不想打开键盘
    • 您为什么想要一个没有可用键盘的焦点文本字段?我想我在问为什么你需要立即让文本字段成为焦点,而不是仅仅显示并可供选择?
    • 不,我的文本字段附带一台扫描仪,因此扫描仪会自动将产品条形码输入文本字段。所以我不需要键盘。
    • 好的,所以我建议您不要使用专为用户输入而设计的文本字段,而是使用文本框来显示条形码(我猜这就是您想要做?)。此链接似乎显示了您要实现的目标的示例:c-sharpcorner.com/article/barcode-and-qrcode-scan-in-flutter
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2012-06-08
    • 2015-09-04
    • 1970-01-01
    • 2020-12-07
    相关资源
    最近更新 更多