The scanning results of flutter's access to the code scanner are actually monitoring the keyboard input and displaying them on the page from testing to

Check whether the equipment is normal

First of all, you must test whether your hardware device is normal. Although some devices have all the indicators on after plugging in the USB, it does not necessarily mean that there is no problem with the device. This needs to be verified first, such as opening Notepad or Doc. document, and then scan the barcode to see if it can be entered normally: Because the initial mode of this type of device is usually the USB Keyboard mode, which simulates keyboard fast input, so when a barcode or QR code is scanned, the keyboard will be simulated. Quickly enter barcode content

If you can input content normally after scanning the code, it means the device is connected properly, and then choose to connect to Flutter or other languages.

If it is not normal, either the interface of the device is not plugged in tightly or the device is broken. Unplug the interface at the back of the device and plug it in again or try changing the interface. It might work. I encountered this cheating problem.

The device I use is a code scanning device similar to Newtologic. Their official website seems to be: Newtologic Optoelectronics Technology Co., Ltd.

Equipment appearance:

Note: There are two interfaces at the back. The first time I could not read the results was because the interface was unstable. I suspected it was a computer problem, but then I switched to another interface and it was fine. 

 

Its operating documentation is: https://16984462.s21i.faiusr.com/61/ABUIABA9GAAgh7Xc3AUohtnFVg.pdf

This device has three modes by default: scan the barcode of the corresponding mode to activate the corresponding mode.

USB Keyboard、USB COM、USB HID

 

I am using the default  USB Keyboard mode here.

Use flutter to monitor keyboard input

I use a demo code from the Internet here, and there is no need to install dependencies. I copy it directly to the main.dart file of flutter, and then you can run it and try it:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(const FocusNodeExampleApp());

class FocusNodeExampleApp extends StatelessWidget {
  const FocusNodeExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('FocusNode Sample')),
        body: const FocusNodeExample(),
      ),
    );
  }
}

class ColorfulButton extends StatefulWidget {
  const ColorfulButton({super.key});

  @override
  State<ColorfulButton> createState() => _ColorfulButtonState();
}

class _ColorfulButtonState extends State<ColorfulButton> {
  late FocusNode _node;
  bool _focused = false;
  late FocusAttachment _nodeAttachment;
  Color _color = Colors.white;

  @override
  void initState() {
    super.initState();
    _node = FocusNode(debugLabel: 'Button');
    _node.addListener(_handleFocusChange);
    _nodeAttachment = _node.attach(context, onKey: _handleKeyPress);
  }

  void _handleFocusChange() {
    if (_node.hasFocus != _focused) {
      setState(() {
        _focused = _node.hasFocus;
      });
    }
  }

  KeyEventResult _handleKeyPress(FocusNode node, RawKeyEvent event) {
    if (event is RawKeyDownEvent) {
      debugPrint(
          'Focus node ${node.debugLabel} got key event: ${event.logicalKey}');
      if (event.logicalKey == LogicalKeyboardKey.keyR) {
        debugPrint('Changing color to red.');
        setState(() {
          _color = Colors.red;
        });
        return KeyEventResult.handled;
      } else if (event.logicalKey == LogicalKeyboardKey.keyG) {
        debugPrint('Changing color to green.');
        setState(() {
          _color = Colors.green;
        });
        return KeyEventResult.handled;
      } else if (event.logicalKey == LogicalKeyboardKey.keyB) {
        debugPrint('Changing color to blue.');
        setState(() {
          _color = Colors.blue;
        });
        return KeyEventResult.handled;
      }
    }
    return KeyEventResult.ignored;
  }

  @override
  void dispose() {
    _node.removeListener(_handleFocusChange);
    // The attachment will automatically be detached in dispose().
    _node.dispose();
    super.dispose();
  }

  void callKeyboard() {
    SystemChannels.textInput.invokeMethod<void>('TextInput.show');
  }

  @override
  Widget build(BuildContext context) {
    _nodeAttachment.reparent();
    return GestureDetector(
      onTap: () {
        if (_focused) {
          _node.unfocus();
        } else {
          _node.requestFocus();
        }
      },
      child: Column(
        children: [
          Container(
            width: 400,
            color: _focused ? _color : Colors.white,
            alignment: Alignment.center,
            child: Text(
                _focused ? "I'm in color! Press R,G,B!" : 'Press to focus'),
          ),
          Container(
              width: 160,
              color: Colors.orange,
              child: OutlinedButton(
                child: Text("Call Keyboard"),
                onPressed: callKeyboard,
              )),
        ],
      ),
    );
  }
}

class FocusNodeExample extends StatelessWidget {
  const FocusNodeExample({super.key});

  @override
  Widget build(BuildContext context) {
    final TextTheme textTheme = Theme.of(context).textTheme;
    return DefaultTextStyle(
      style: textTheme.headlineMedium!,
      child: const ColorfulButton(),
    );
  }
}

           Then the result after running is: Then click Press to focus and start monitoring.

After one click, start monitoring: 

At this time, just press any key on the keyboard, and the monitoring content will be output on the flutter console: after pressing r, g, or b, the background color in the window will also change:

Supports the scan_gun library

The scan_gun library is a packaged library and depends on the library address: scan_gun | Flutter Package

Github warehouse address: GitHub - liyufengrex/flutter_scan_gun: flutter: a universal solution for USB plug-in code scanning guns. (It will not trigger keyboard awakening and will not trigger Chinese garbled characters)

Implement a code scanner to obtain data sources and prohibit system keyboard pop-ups. Rely on  EditableText the principle to realize flutter terminal code scanning capability support. (It will not trigger keyboard awakening and will not trigger Chinese garbled characters) 

Installation instructions, referenced in the pubspec.yaml file:

dependencies:
  scan_gun: ^2.0.0

Then create two files in the lib directory following the official demo:

The file content is directly copied from the official demo:

Then when importing each other, remember to modify the import path and use the local path of your project, otherwise an error will be reported and the corresponding class component cannot be found.

Finally use in main.dart:

import 'package:flutter/material.dart';
import 'package:flutter_scanner/test_scan_gun_withod_textfield.dart';
import 'package:scan_gun/scan_gun.dart';

void main() {
  TextInputBinding();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'scan_gun_demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('扫码枪测试'),
        ),
        body: const TestScanGun(),
      ),
    );
  }
}

Then run: the scan results will be displayed directly without pop-up windows.

Pop-up scan code results:

At this point, the whole process is over. This is also the result of spending a day researching. 

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/135341597