如何在 Flutter 中的 TextFromField 上使用按键事件?

kin*_*sis 5 onkeypress dart flutter

有没有办法在文本字段中捕获按键?就我而言,当用户在文本字段内按下 Enter 键时,值将被存储。为此,我需要像 Kotlin+Android 一样使用 Keypress-event。我这周刚开始尝试 flutter,因为它很有趣,而且是跨平台的。

RawKeyboardListener(
  child: TextFormField(
    keyboardType: TextInputType.text,
    decoration: new InputDecoration(labelText: "Phone"),
    validator: (val) => val.length == 0 ? 'Enter your phone' : null,
    onSaved: (val) => this.phone = val,
  ),
   focusNode: FocusNode(),
   onKey: (RawKeyEvent event) {
     print(event.data.logicalKey.keyId);
     if (event.runtimeType == RawKeyDownEvent ) {
       print("asdadda");

     }
   },
),
Run Code Online (Sandbox Code Playgroud)

但是我不知道为什么它不起作用但是我按下了键。

kin*_*sis 11

按照Alok建议,我研究了onSubmitted方法。我使用 TextfromField,所以onFieldSubmitted在我的情况下我选择方法。我还添加了 RawKeyBoardListener 用于从移动扫描仪设备按下物理 Enter 键。而代码是——

RawKeyboardListener(//for physical keyboard press
              child: TextFormField(
                keyboardType: TextInputType.text,
                decoration: new InputDecoration(labelText: "Phone"),
                validator: (val) => val.length == 0 ? 'Enter your phone' : null,
                onSaved: (val) => this.phone = val,
                onFieldSubmitted: (_) async {
                  print("asdadda");
                  submitContact();
                },
              ),
               focusNode: FocusNode(),
               onKey: (RawKeyEvent event) { 
                 print(event.data.logicalKey.keyId);
                 if (event.runtimeType == RawKeyDownEvent  &&
                     (event.logicalKey.keyId == 4295426088))//Enter Key ID from keyboard
                 {
                   print("asdadda");
                   submitContact();
                 }
               },
            ),
Run Code Online (Sandbox Code Playgroud)

随意编辑^_^


Alo*_*lok 6

我确定您正在寻找的是 TextField 的onSubmitted. 这样做的作用是,按下Enter键盘上的 ,它会给你一个值,它作为一个参数/参数。有关这方面的更多信息,您可以查看:onSubmitted Property TextField

如何做到这一点,它是 TextField 的一个属性,您只需简单地执行此操作即可完成您的任务。

您还可以在此属性中执行任何操作。

TextField(
  onSubmitted: (value){ 
     print(value);
     // or do whatever you want when you are done editing
     // call your method/print values etc
  }
)
Run Code Online (Sandbox Code Playgroud)

另请阅读有关TextField 类的更多信息。这将在很多方面帮助你。希望对您的情况有所帮助。快乐学习:)