Flutter 快速输入 TextField

问题描述 投票:0回答:1

我正在使用手持式条码扫描仪来扫描条码。如果不跟踪键盘输入,我就无法让它工作。它现在大部分时间都可以工作,但有时如果我扫描#COUNTING-TEST-TEST,它会丢失字母并导致类似#COUN-T 的结果。

条码类型为 Code-128,扫描仪为 Zebra DS2208

我正在使用 Amazon Fire 平板电脑,如果我在桌面上扫描,它会完美运行。

有人成功过吗?

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
              });
            },
          )
        ),
        
      ),
    );
  }
}

我尝试过使用stream_transform包、队列、缓冲区。如果平台是 android,我什至尝试注册本机 android 编辑文本,但这有其自身的复杂性,尽管它能够很好地读取快速输入。

flutter buffer textfield barcode barcode-scanner
1个回答
0
投票

所以我终于能够得到它了。我使用了 flutter_barcode_listener 包并进行了一些定制。

void _handleBarcodeScan(String scannedCode) async {
if (!widget.focusNode.hasFocus) {
  return;
}
setState(() {
  // scannedcode came in with extra whitespace
  _scannedText = scannedCode.trim();
  
  // Scanner configured with enter after scan came in with `a` at the end
  if (_scannedText.endsWith("`a`")) {
    // # was transformed to 3 I needed to only remove the first 3 since 
       that is the only spot # will be
    _scannedText = _scannedText.replaceFirst("3", "#");
  }
  
  // If user manually entered text then often times _scannedText would be 
  // empty so instead I got the text from the widget
  if (_scannedText == "" && widget.controller.text != ""){
    _scannedText = widget.controller.text.toUpperCase();
  }

  // Replace all specific characters as needed
  _scannedText = _scannedText
      .replaceAll("½", "-")
      .replaceAll("``a`", "")
      .replaceAll(RegExp(r"\s+"), "") // Remove all spaces, including multiple spaces
      .replaceAll("¡3", "#"); // # would sometimes come in as that weird 
                              // character as well
});


widget.controller.clear();
widget.onBarcodeComplete(_scannedText);

}

@override

小部件构建(BuildContext上下文){ 返回条码键盘监听器( bufferDuration: widget.bufferDuration, onBarcodeScanned: _handleBarcodeScan, 孩子:文本字段( 控制器:widget.controller, focusNode: widget.focusNode, 文本大写: TextCapitalization.none, 装饰:输入装饰( labelText: widget.labelText, 边框:const OutlineInputBorder(), 前缀图标:图标按钮( 图标:图标(Icons.clear), 按下时:() { widget.controller.clear(); 设置状态((){ _scannedText = ''; }); }, ), ), onChanged:_onTextChanged, 提交时:(值){ }, ), ); } }

© www.soinside.com 2019 - 2024. All rights reserved.