flutter如何枚举USB设备
在Flutter中如何枚举当前连接的USB设备?我需要在跨平台应用中获取USB设备列表,但官方插件库中似乎没有直接支持的方案。是否可以通过Platform Channels调用原生代码实现?或者有推荐的第三方插件可以完成这个功能?最好能提供Android和iOS双端的解决方案示例代码。
2 回复
在Flutter中,使用flutter_usb插件枚举USB设备。首先添加依赖,然后调用FlutterUsb.getDeviceList()获取设备列表,返回设备信息数组。
更多关于flutter如何枚举USB设备的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中枚举USB设备可以通过以下方法实现:
方法一:使用 flutter_usb 插件
- 添加依赖
dependencies:
flutter_usb: ^0.2.0
- 基本使用代码
import 'package:flutter_usb/flutter_usb.dart';
class USBDeviceList extends StatefulWidget {
@override
_USBDeviceListState createState() => _USBDeviceListState();
}
class _USBDeviceListState extends State<USBDeviceList> {
List<USBDevice> devices = [];
@override
void initState() {
super.initState();
enumerateUSBDevices();
}
Future<void> enumerateUSBDevices() async {
try {
List<USBDevice> deviceList = await FlutterUsb.getDeviceList();
setState(() {
devices = deviceList;
});
} catch (e) {
print('枚举USB设备失败: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('USB设备列表')),
body: ListView.builder(
itemCount: devices.length,
itemBuilder: (context, index) {
USBDevice device = devices[index];
return ListTile(
title: Text('设备ID: ${device.deviceId}'),
subtitle: Text('厂商ID: ${device.vendorId}, 产品ID: ${device.productId}'),
);
},
),
);
}
}
方法二:使用 usb_serial 插件(针对串口设备)
import 'package:usb_serial/usb_serial.dart';
void enumerateUSBSerialDevices() async {
List<UsbDevice> devices = await UsbSerial.listDevices();
for (var device in devices) {
print('设备: ${device.deviceName}');
print('厂商ID: ${device.vendorId}');
print('产品ID: ${device.productId}');
}
}
注意事项:
- Android权限:在
AndroidManifest.xml中添加USB权限
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
-
平台限制:iOS对USB设备访问有严格限制,主要支持Android平台
-
设备过滤:可以通过厂商ID和产品ID过滤特定设备
选择适合你需求的插件,并根据具体设备类型进行相应配置。

