### Install hidapi on Linux Source: https://pub.dev/packages/hid4flutter On Linux, you need to manually install the hidapi library before using the hid4flutter plugin. ```bash sudo apt-get install libhidapi-hidraw0 ``` -------------------------------- ### Install Dependencies Source: https://pub.dev/packages/hid4flutter Run this command in your project's root directory after updating pubspec.yaml to fetch the new dependency. ```bash flutter pub get ``` -------------------------------- ### Get all connected devices Source: https://pub.dev/packages/hid4flutter Retrieves a list of all currently connected HID devices. ```APIDOC ## Get all connected devices list ```dart List devices = await Hid.getDevices(); // Do something with the list ``` ``` -------------------------------- ### Get device by vendorId and productId Source: https://pub.dev/packages/hid4flutter Retrieves a list of HID devices matching the specified vendor ID and product ID. ```APIDOC ## Get device by vendorId and productId ```dart List devices = await Hid.getDevices(vendorId: 0x55, productId: 0x13); // Since multiple devices can match the same vendorId // and productId, get the first device or null. HidDevice? device = devices.firstOrNull; // Do something with the device ``` ``` -------------------------------- ### Flutter App for HID Device Interaction Source: https://pub.dev/packages/hid4flutter/example This is the main application widget for the HID4Flutter example. It sets up the MaterialApp with a theme and navigates to the DeviceListScreen. ```dart import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:hid4flutter/hid4flutter.dart'; class _ReportPayload { final int reportId; final Uint8List bytes; const _ReportPayload(this.reportId, this.bytes); } void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), useMaterial3: true), home: const DeviceListScreen(), ); } } class DeviceListScreen extends StatefulWidget { const DeviceListScreen({super.key}); @override DeviceListScreenState createState() => DeviceListScreenState(); } class DeviceListScreenState extends State { List devices = []; @override void initState() { super.initState(); _loadConnectedDevices(); } Future _loadConnectedDevices() async { try { List connectedDevices = await Hid.getDevices(); setState(() { devices = connectedDevices; }); } catch (e) { // ignore: avoid_print print('Error getting connected devices: $e'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('Connected Devices'), ), body: _buildDeviceList(), floatingActionButton: FloatingActionButton( onPressed: () => { _loadConnectedDevices(), }, tooltip: 'Refresh', child: const Icon(Icons.refresh), ), ); } Widget _buildDeviceList() { if (devices.isEmpty) { return const Center( child: Text('No connected devices'), ); } return ListView.builder( itemCount: devices.length, itemBuilder: (context, index) { HidDevice device = devices[index]; return Card( margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: ListTile( title: Text('Device $index'), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Path: ${device.path}'), Text('Vendor ID: 0x${device.vendorId.toRadixString(16)}'), Text('Product ID: 0x${device.productId.toRadixString(16)}'), Text('Serial Number: ${device.serialNumber}'), Text('Release Number: ${device.releaseNumber}'), Text('Manufacturer: ${device.manufacturer}'), Text('Product Name: ${device.productName}'), Text('Usage Page: 0x${device.usagePage.toRadixString(16)}'), Text('Usage: 0x${device.usage.toRadixString(16)}'), Text('Interface Number: ${device.interfaceNumber}'), Text('Bus Type: ${device.busType}'), ], ), trailing: device.isOpen ? const Icon(Icons.usb, color: Colors.green) : const Icon(Icons.usb, color: Colors.grey), onTap: () async { await _handleDeviceTap(device, index); }, onLongPress: () async { await _handleDeviceLongPress(context, device, index); }, ), ); }, ); } Future _handleDeviceTap(HidDevice device, int index) async { try { if (!device.isOpen) { await device.open(); if (mounted) setState(() {}); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( 'Opened ${device.productName.isNotEmpty ? device.productName : 'device $index'}', ), duration: const Duration(seconds: 2), ), ); } else { await device.close(); if (mounted) setState(() {}); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( 'Closed ${device.productName.isNotEmpty ? device.productName : 'device $index'}', ), duration: const Duration(seconds: 2), ), ); } } catch (e) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( '${device.isOpen ? 'Failed to close' : 'Failed to open'} device: $e'), duration: const Duration(seconds: 3), ), ); } } Future _handleDeviceLongPress( BuildContext context, HidDevice device, int index) async { if (!device.isOpen) { ScaffoldMessenger.of(context).showSnackBar( ``` -------------------------------- ### Import hid4flutter in Dart Source: https://pub.dev/packages/hid4flutter/install Import the hid4flutter package into your Dart files to start using its functionalities. This line should be placed at the top of your Dart file. ```dart import 'package:hid4flutter/hid4flutter.dart'; ``` -------------------------------- ### Get All Connected HID Devices Source: https://pub.dev/packages/hid4flutter Retrieve a list of all HID devices currently connected to the system. This is the first step in interacting with any HID device. ```dart List devices = await Hid.getDevices(); // Do something with the list ``` -------------------------------- ### Deprecated 'elementAt' Usage Source: https://pub.dev/packages/hid4flutter/score This example shows the use of the deprecated `elementAt` method. It is recommended to use the `+` operator instead for better performance and to avoid deprecated features. ```dart final char = codeUnits.elementAt(i).value; ``` -------------------------------- ### Get Specific HID Device by Vendor and Product ID Source: https://pub.dev/packages/hid4flutter Filter and retrieve a list of HID devices matching a specific vendor ID and product ID. Useful for targeting a particular device model. ```dart List devices = await Hid.getDevices(vendorId: 0x55, productId: 0x13); // Since multiple devices can match the same vendorId // and productId, get the first device or null. HidDevice? device = devices.firstOrNull; // Do something with the device ``` -------------------------------- ### Missing Type Annotation Example Source: https://pub.dev/packages/hid4flutter/score This snippet highlights a missing type annotation in the `registerWith` method. Ensure all methods have explicit type annotations for better code clarity and maintainability. ```dart static registerWith() { } ``` -------------------------------- ### Send Output Report Source: https://pub.dev/packages/hid4flutter Opens a device, sends an output report, and then closes the device. ```APIDOC ## Send Output Report ```dart final HidDevice device = ... try { await device.open(); // Send an Output report of 32 bytes (all zeroes). // The reportId is optional (default is 0x00). // It will be prefixed to the data as per HID rules. Uint8List data = Uint8List(32); await device.sendReport(reportId: 0x00, reportData); } finally { await device.close(); } ``` ``` -------------------------------- ### Receive Input Report Source: https://pub.dev/packages/hid4flutter Opens a device, receives an input report with a specified timeout, and then closes the device. ```APIDOC ## Receive Input Report ```dart final HidDevice device = ... try { await device.open(); // Receive a report of 32 bytes with timeout of 2 seconds. Uint8List data = await device.receiveReport(32, timeout: const Duration(seconds: 2)); // First byte is always the reportId. int reportId = data[0]; print('Received report with id $reportId: $data.'); } finally { await device.close(); } ``` ``` -------------------------------- ### Send Output Report to HID Device Source: https://pub.dev/packages/hid4flutter Opens a connection to a HID device, sends a custom output report, and then closes the connection. Ensure the device is available and the report format is correct. ```dart final HidDevice device = ... try { await device.open(); // Send an Output report of 32 bytes (all zeroes). // The reportId is optional (default is 0x00). // It will be prefixed to the data as per HID rules. Uint8List data = Uint8List(32); await device.sendReport(reportId: 0x00, reportData); } finally { await device.close(); } ``` -------------------------------- ### Add hid4flutter Dependency Source: https://pub.dev/packages/hid4flutter/install Run this command in your project's root directory to add the hid4flutter package as a dependency. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add hid4flutter ``` -------------------------------- ### Receive Input Report from HID Device Source: https://pub.dev/packages/hid4flutter Opens a connection to a HID device, attempts to receive an input report within a specified timeout, and then closes the connection. The first byte of the received data is the report ID. ```dart final HidDevice device = ... try { await device.open(); // Receive a report of 32 bytes with timeout of 2 seconds. Uint8List data = await device.receiveReport(32, timeout: const Duration(seconds: 2)); // First byte is always the reportId. int reportId = data[0]; print('Received report with id $reportId: $data.'); } finally { await device.close(); } ``` -------------------------------- ### Update pubspec.yaml Source: https://pub.dev/packages/hid4flutter/install After running `flutter pub add`, your pubspec.yaml file will include the hid4flutter dependency. Ensure this line is present. ```yaml dependencies: hid4flutter: ^0.2.0 ``` -------------------------------- ### Add hid4flutter Dependency Source: https://pub.dev/packages/hid4flutter Add the hid4flutter package to your pubspec.yaml file to include it in your Flutter project. ```yaml dependencies: hid4flutter: ^0.2.0 ``` -------------------------------- ### Convert Hex String to Bytes Source: https://pub.dev/packages/hid4flutter/example A utility function to convert a hexadecimal string representation of bytes into a Uint8List. It handles optional '0x' prefixes, spaces, and ensures the input string has an even number of characters for proper parsing. ```dart Uint8List _hexToBytes(String hexInput) { String s = hexInput .trim() .replaceAll(RegExp(r'0x', caseSensitive: false), '') .replaceAll(RegExp(r'[^0-9a-fA-F]'), ''); if (s.length % 2 != 0) s = '0$s'; final out = Uint8List(s.length ~/ 2); for (int i = 0, j = 0; i < s.length; i += 2, j++) { out[j] = int.parse(s.substring(i, i + 2), radix: 16); } return out; } ``` -------------------------------- ### Prompt User for Report Payload Source: https://pub.dev/packages/hid4flutter/example This function displays a dialog to collect the report ID and data bytes (in hexadecimal format) from the user. It validates the input and returns a _ReportPayload object or null if the user cancels or provides invalid input. ```dart Future<_ReportPayload?> _promptReportPayload(BuildContext context) async { final hexController = TextEditingController(); final reportIdController = TextEditingController(text: '00'); final confirmed = await showDialog( context: context, builder: (ctx) { return AlertDialog( title: const Text('Send custom HEX bytes'), content: Column( mainAxisSize: MainAxisSize.min, children: [ TextField( controller: reportIdController, decoration: const InputDecoration( labelText: 'Report ID (hex, e.g. 00)', ), ), const SizedBox(height: 8), TextField( controller: hexController, decoration: const InputDecoration( labelText: 'Data bytes (hex, e.g. 01 02 0A FF)', ), ), ], ), actions: [ TextButton( onPressed: () => Navigator.of(ctx).pop(false), child: const Text('Cancel'), ), ElevatedButton( onPressed: () => Navigator.of(ctx).pop(true), child: const Text('Send'), ), ], ); }, ); if (confirmed != true) return null; try { final reportId = int.parse( reportIdController.text.replaceAll('0x', '').replaceAll(' ', ''), radix: 16); final bytes = _hexToBytes(hexController.text); return _ReportPayload(reportId, bytes); } catch (e) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Invalid input: $e')), ); return null; } } ``` -------------------------------- ### Send Custom Data to HID Device Source: https://pub.dev/packages/hid4flutter/example Use this function to send custom hexadecimal byte data to a connected HID device. It prompts the user for a report ID and the data bytes, handling potential errors during parsing and sending. ```dart Future _sendReport(BuildContext context, HidDevice device) async { if (device.isClosed) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Open the device first to send data.')), ); return; } final payload = await _promptReportPayload(context); if (payload == null) return; try { await device.sendReport(payload.bytes, reportId: payload.reportId); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Data sent.')), ); } catch (e) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Failed to send: $e')), ); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.