如何在Flutter中获取无Textfield的文本输入

3
当我扫描条形码时,数字通过设备以 String(我猜)的形式发送。 如果我有一个 textfield,并且它被选中/聚焦,扫描会自动填入数字字符串。 我不想把它放在 textField 上,我想在类上捕获它,对其进行处理,以便我可以更新购物车。 我尝试了 KeyboardListener,但它没有起作用。
@override
  Widget build(BuildContext context) {
    return KeyboardListener(
        focusNode: FocusNode(),
        onKeyEvent: (event) {
          text = event.character.toString();
        },
        child: Scaffold(
            appBar: AppBar(
              title: const Text('Retrieve Text Input'),
            ),
            body: Center(
              child: Text(text),
            )));
  }
}

我还看到了一个名为TextInput的类,它是系统文本输入控件的低级接口。

文档中说:

要开始与系统的文本输入控件交互,请调用attach来建立系统的文本输入控件和TextInputClient之间的TextInputConnection

EditableTextState client = EditableTextState(); 
TextInputConfiguration configuration = TextInputConfiguration();

final TextInputConnection _textInputConnection =
        TextInput.attach(client, configuration);

但是我不知道如何使用这个TextInputConnection来获取用户输入,因为互联网上没有关于如何使用这些低级类的示例。

1个回答

2
这是我想要隐藏TextField并监听用户输入的操作步骤。 使用Stack小部件将其他小部件放在TextField上方,以便它被其他小部件遮挡。 在上层小部件上轻点后,使用TextField的焦点获取TextField的焦点。 使用FocusNode getFocus函数。
您可以尝试禁用用户交互并在TextField中应用一些样式。
 style: TextStyle(color: Colors.transparent),
 autofocus: true,
 cursorColor: Colors.transparent,
 showCursor: false,
 autocorrect: false,
 enableSuggestions: false,
 maxLines: 1,
 enableInteractiveSelection: false,
 decoration: InputDecoration(border: InputBorder.none),
                              

使用TextEditController,您可以获取输入的文本。

你是如何防止键盘弹出的?@ashutosh - Yves Boutellier
@YvesBoutellier 我猜那里需要键盘,因此TextInput的要求出现了!否则普通文本将起作用。 对于TextInput showCursor: true, readOnly: true keyboardType: TextInputType.none 将有助于隐藏键盘。 - ashutosh
@YvesBoutellier 还可以尝试始终禁用焦点 TextField(focusNode: AlwaysDisabledFocusNode(),) class AlwaysDisabledFocusNode extends FocusNode { @override bool get hasFocus => false; } - ashutosh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接