检测颤动中的“输入键”按下

Ben*_*eri 20 flutter

就我而言,我需要扫描条形码并获取产品详细信息。通常条码扫描仪设备会enter key(keycode=13) event在扫描结束时发出信号,但在颤动中输入键与Done如何编写代码来检测在我的 TextFormField 小部件中按下的输入键?

Al *_*hik 28

如果您正在使用,TextField则必须onSubmitted在文本字段中添加以检测用户何时按下Enter键。就我而言,我将Done键盘更改为TextInputAction.Search. 它也适用TextInputAction.Done。这是一个示例代码

   TextField(
    onSubmitted: (value){
      //value is entered text after ENTER press
      //you can also call any function here or make setState() to assign value to other variable
    },
    textInputAction: TextInputAction.search,
  )
Run Code Online (Sandbox Code Playgroud)


loo*_*nix 12

如果有人正在寻找相同的解决方案(如 Al Walid Ashik),但对于TextFormField,只需使用以下内容:

TextFormField(
  /// ...
  onFieldSubmitted: (value) {
     /// do some stuff here
  },
),
Run Code Online (Sandbox Code Playgroud)


Ser*_*kov 8

上面的解决方案有效,但我相信这RawKeyboardListener是一个更可靠和灵活的解决方案。你只需要用它覆盖文本字段并开始监听键盘事件:

var focusNode = FocusNode();
RawKeyboardListener(
        focusNode: focusNode,
        onKey: (event) {
          if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
            // Do something
          }
        },
        child: TextField(controller: TextEditingController())
    )
Run Code Online (Sandbox Code Playgroud)

作为第二个选项,您可以使用 的onKey方法FocusNoded并将节点传递给您的文本字段:

var focusNode = FocusNode(onKey: (node, event) {
    if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
        // Do something
        // Next 2 line needed If you don't want to update the text field with new line.
        // node.unfocus(); 
        // return true;
    }
    return false;

});
TextField(focusNode: focusNode, controller: TextEditingController())
Run Code Online (Sandbox Code Playgroud)

  • ...但仅适用于物理键盘。 (2认同)
  • 由于“onKey”很快就会被弃用,是否有与“onKeyEvent”等效的方法?它似乎无法识别“enter”。 (2认同)

Ben*_*eri 5

TextFormField(
maxLines: null,
autovalidate: true,
   validator: (value){
             if(value.contains('\n')){
              doFun(value);
              }   
            }

)
Run Code Online (Sandbox Code Playgroud)

当用户enter key在文本框中按新行创建时。我们检查一下。

maxLine:null - 隐藏多行

autovalidate:true - 自动运行验证器乐趣

'\n' - 新行('\s'-空格、'\t'-tab.. 等)