Flutter TextField处理Zebra条码扫描器快速输入丢字符问题求助
Zebra DS2208扫描Code-128条码偶尔丢字符的问题
- 使用Zebra DS2208手持条码扫描器扫描Code-128码制条码,通过监听键盘输入实现功能,多数情况正常,但扫描如
#COUNTING-TEST-TEST这类条码时偶尔丢字符,结果变成#COUN-T - 设备为亚马逊Fire平板,桌面端扫描完全正常
- 尝试过的方案:stream_transform包、队列、缓冲区,以及针对Android平台注册原生EditText(该方式能很好处理快速输入,但存在其他问题)
自定义TextField代码
class CustomTextFieldState extends State<CustomTextField> { String _inputBuffer = ''; // Buffer to accumulate input Timer? _bufferTimer; // Timer for clearing buffer // Method to manually trigger onSubmitted void submit() { if (widget.onSubmitted != null) { widget.onSubmitted!(widget.controller.text); widget.controller.clear(); _inputBuffer = ""; widget.focusNode.requestFocus(); } } KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) { if (event is KeyDownEvent) { final LogicalKeyboardKey logicalKey = event.logicalKey; final String key = event.character ?? ''; // Handle Enter key only when LogicalKeyboardKey.enter is pressed if (logicalKey == LogicalKeyboardKey.enter) { // Call onSubmitted with buffered input widget.onSubmitted?.call(_inputBuffer); // Clear the controller text and input buffer widget.controller.clear(); _inputBuffer = ''; widget.focusNode.requestFocus(); return KeyEventResult.handled; } // Handle Backspace key else if (logicalKey == LogicalKeyboardKey.backspace) { if (_inputBuffer.isNotEmpty) { // Remove the last character from the buffer _inputBuffer = _inputBuffer.substring(0, _inputBuffer.length - 1); widget.controller.text = _inputBuffer; } return KeyEventResult.handled; } // Handle normal characters: add them to the buffer and update the controller else if (key.isNotEmpty && key.length == 1) { // Add the character to the buffer and update the controller text _inputBuffer += key; widget.controller.text = _inputBuffer; // Reflect the key in the text field return KeyEventResult.handled; } } return KeyEventResult.ignored; } void _resetBufferTimer() { _bufferTimer?.cancel(); _bufferTimer = Timer(widget.bufferDuration, () { setState(() { _inputBuffer = ''; // Clear buffer if no input for bufferDuration }); }); } @override void dispose() { _bufferTimer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Focus( focusNode: widget.focusNode, onKeyEvent: _handleKeyEvent, // Handle key events here child: TextField( autocorrect: false, autofocus: true, textInputAction: TextInputAction.done, controller: widget.controller, textCapitalization: TextCapitalization.none, decoration: InputDecoration( labelText: widget.labelText, border: const OutlineInputBorder(), prefixIcon: IconButton( icon: Icon(Icons.clear), onPressed: () { widget.controller.clear(); setState(() { _inputBuffer = ''; // Clear the buffer as well }); }, ) ), ), ); } }
请问有人成功解决过这个问题吗?
内容的提问来源于stack exchange,提问作者Cody
相关产品推荐
相关产品推荐

