Flutter Web HID设备访问插件web_hid的使用
Flutter Web HID设备访问插件web_hid的使用
Dart 对 dart:js
的封装,用于访问 Web HID API。
功能特性
canUseHid
getDevices/requestDevice
subscribeConnect/unsubscribeConnect
subscribeDisconnect/unsubscribeDisconnect
open/close
sendReport
subscribeInputReport/unsubscribeInputReport
sendFeatureReport
使用方法
canUseHid
检查当前浏览器是否支持 Web HID API。
bool canUse = canUseHid();
print('canUse $canUse');
getDevices/requestDevice
获取已连接的 HID 设备
List<HidDevice> getDevices = await hid.getDevices();
_device = getDevices[0];
请求用户选择 HID 设备
List<HidDevice> requestDevice = await hid.requestDevice(RequestOptions(
filters: [keyboardBacklightIds],
));
_device = requestDevice[0];
subscribeConnect/unsubscribeConnect
订阅 HID 设备连接事件。
final EventListener _handleConnect = allowInterop((Event event) {});
...
hid.subscribeConnect(_handleConnect);
...
hid.unsubscribeConnect(_handleConnect);
subscribeDisconnect/unsubscribeDisconnect
订阅 HID 设备断开事件。
final EventListener _handleDisconnect = allowInterop((Event event) {});
...
hid.subscribeDisconnect(_handleDisconnect);
...
hid.unsubscribeDisconnect(_handleDisconnect);
open/close
打开 HID 设备
_device?.open().then((value) {
print('device.open success');
}).catchError((error) {
print('device.open $error');
});
关闭 HID 设备
_device?.close().then((value) {
print('device.close success');
}).catchError((error) {
print('device.close $error');
});
sendReport
发送 HID 报告。
_device?.sendReport(0, blockBytes).then((value) {
print('device.sendReport success');
}).catchError((error) {
print('device.sendReport $error');
});
subscribeInputReport/unsubscribeInputReport
订阅 HID 输入报告事件。
final EventListener _handleInputReport = allowInterop((event) {});
...
_device?.subscribeInputReport(_handleInputReport);
...
_device?.unsubscribeInputReport(_handleInputReport);
sendFeatureReport
发送 HID 特性报告。
_device?.sendFeatureReport(1, Uint32List.fromList([1, 0])).then((value) {
print('device.sendFeatureReport 0 success');
}).catchError((error) {
print('device.sendFeatureReport $error');
});
完整示例代码
以下是一个完整的示例代码,展示了如何使用 web_hid
插件与 HID 设备进行交互。
// ignore_for_file: avoid_print, avoid_web_libraries_in_flutter
import 'dart:html' show Event, EventListener;
import 'dart:js' show allowInterop;
import 'package:flutter/material.dart';
import 'package:web_hid/web_hid.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('web_hid 示例'),
),
body: Center(
child: Column(
children: [
ElevatedButton(
child: const Text('检测是否支持 HID'),
onPressed: () {
bool canUse = canUseHid();
print('是否支持 HID: $canUse');
},
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: const Text('订阅连接事件'),
onPressed: () {
hid.subscribeConnect(_handleConnect);
print('订阅连接事件成功');
},
),
ElevatedButton(
child: const Text('取消订阅连接事件'),
onPressed: () {
hid.unsubscribeConnect(_handleConnect);
print('取消订阅连接事件成功');
},
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: const Text('订阅断开事件'),
onPressed: () {
hid.subscribeDisconnect(_handleDisconnect);
print('订阅断开事件成功');
},
),
ElevatedButton(
child: const Text('取消订阅断开事件'),
onPressed: () {
hid.unsubscribeDisconnect(_handleDisconnect);
print('取消订阅断开事件成功');
},
),
],
),
ElevatedButton(
child: const Text('打开设备'),
onPressed: () {
_device?.open().then((value) {
print('设备打开成功');
}).catchError((error) {
print('设备打开失败: $error');
});
},
),
ElevatedButton(
child: const Text('关闭设备'),
onPressed: () {
_device?.close().then((value) {
print('设备关闭成功');
}).catchError((error) {
print('设备关闭失败: $error');
});
},
),
ElevatedButton(
child: const Text('发送报告'),
onPressed: () {
_device?.sendReport(0, Uint8List.fromList([0x01, 0x02]))
.then((value) {
print('发送报告成功');
}).catchError((error) {
print('发送报告失败: $error');
});
},
),
],
),
),
);
}
}
final EventListener _handleConnect = allowInterop((Event event) {
print('_handleConnect $event');
});
final EventListener _handleDisconnect = allowInterop((Event event) {
print('_handleDisconnect $event');
});
更多关于Flutter Web HID设备访问插件web_hid的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
Flutter Web HID(Human Interface Device)插件 web_hid
允许你在 Flutter Web 应用中访问和与 HID 设备进行交互。HID 设备通常包括键盘、鼠标、游戏手柄等,但也可以是其他符合 HID 标准的设备。
以下是如何在 Flutter Web 项目中使用 web_hid
插件的基本步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 web_hid
插件的依赖:
dependencies:
flutter:
sdk: flutter
web_hid: ^0.1.0 # 请检查最新版本
然后运行 flutter pub get
来获取依赖。
2. 导入插件
在你的 Dart 文件中导入 web_hid
插件:
import 'package:web_hid/web_hid.dart';
3. 请求设备访问权限
在访问 HID 设备之前,你需要请求用户授权。你可以使用 requestDevice
方法来请求访问设备:
Future<void> requestHidDevice() async {
try {
// 请求访问 HID 设备
HidDevice? device = await WebHid.requestDevice();
if (device != null) {
print('Device connected: ${device.productName}');
// 你可以在这里与设备进行交互
} else {
print('No device selected');
}
} catch (e) {
print('Error requesting HID device: $e');
}
}
4. 与设备交互
一旦你获得了设备的访问权限,你可以使用 HidDevice
对象与设备进行交互。例如,你可以发送和接收数据:
Future<void> interactWithDevice(HidDevice device) async {
// 发送数据到设备
List<int> data = [0x01, 0x02, 0x03];
await device.sendReport(data);
// 监听设备发送的数据
device.onInputReport.listen((report) {
print('Received report: ${report.data}');
});
}
5. 断开设备连接
当你不再需要与设备交互时,可以断开连接:
Future<void> disconnectDevice(HidDevice device) async {
await device.close();
print('Device disconnected');
}
6. 处理设备连接和断开事件
你可以监听设备的连接和断开事件:
void listenToDeviceEvents() {
WebHid.onConnect.listen((device) {
print('Device connected: ${device.productName}');
});
WebHid.onDisconnect.listen((device) {
print('Device disconnected: ${device.productName}');
});
}
7. 完整示例
以下是一个完整的示例,展示了如何请求设备、与设备交互以及处理设备事件:
import 'package:flutter/material.dart';
import 'package:web_hid/web_hid.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HidExample(),
);
}
}
class HidExample extends StatefulWidget {
@override
_HidExampleState createState() => _HidExampleState();
}
class _HidExampleState extends State<HidExample> {
HidDevice? _device;
@override
void initState() {
super.initState();
listenToDeviceEvents();
}
Future<void> requestHidDevice() async {
try {
HidDevice? device = await WebHid.requestDevice();
if (device != null) {
setState(() {
_device = device;
});
print('Device connected: ${device.productName}');
interactWithDevice(device);
} else {
print('No device selected');
}
} catch (e) {
print('Error requesting HID device: $e');
}
}
Future<void> interactWithDevice(HidDevice device) async {
List<int> data = [0x01, 0x02, 0x03];
await device.sendReport(data);
device.onInputReport.listen((report) {
print('Received report: ${report.data}');
});
}
Future<void> disconnectDevice() async {
if (_device != null) {
await _device!.close();
setState(() {
_device = null;
});
print('Device disconnected');
}
}
void listenToDeviceEvents() {
WebHid.onConnect.listen((device) {
print('Device connected: ${device.productName}');
});
WebHid.onDisconnect.listen((device) {
print('Device disconnected: ${device.productName}');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Web HID Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: requestHidDevice,
child: Text('Request HID Device'),
),
if (_device != null)
ElevatedButton(
onPressed: disconnectDevice,
child: Text('Disconnect Device'),
),
],
),
),
);
}
}
8. 运行应用
确保你的 Flutter 环境支持 Web 开发,然后运行应用:
flutter run -d chrome