我正在开发一个应用程序,我需要在其中显示蓝牙(经典和BLE)设备,并且我能够发现使用(flutter_bluetooth_serial)包并在ListView中显示。我还可以连接经典设备,但无法连接 BLE 设备。据我了解,我发现使用 (flutter_bluetooth_serial) 的设备,当我尝试连接 BLE 设备时,由于类型问题而失败。所以我所做的是,尝试将 BluetoothDevice 转换为包(flutter_blue_plus.dart),但它抛出以下错误。我想连接到经典设备和 BLE 设备。有人可以给我一些灯吗?
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart' as bluetoothLEManager;
connectToExternalDevice(BluetoothDevice connectingDevice) async {
if (connectingDevice.type == BluetoothDeviceType.le) {
final bbleDevice = connectingDevice as bluetoothLEManager.BluetoothDevice; // here is where I'm getting the below exception
print(bbleDevice);
}
try { // This part works if the connecting device is classic
classicDevice = connectingDevice;
await BluetoothConnection.toAddress(classicDevice.address).then((result) {
isBluetoothConnected = true;
connection = result;
notifyListeners();
connection?.input?.listen(onDataReceived).onDone(() {
print("On done");
});
});
} catch (exception) {
print("exception");
}
}
Exception has occurred.
•
_TypeError (type 'BluetoothDevice' is not a subtype of type 'BluetoothDevice' in type cast where
BluetoothDevice is from package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart
BluetoothDevice is from package:flutter_blue_plus/flutter_blue_plus.dart
这两个
BluetoothDevice
是完全不同的类型,只是名称相同而已。如果您确实愿意,可以使用第二个包中 BluetoothDevice
的构造函数,并用从第一个包中 BluetoothDevice
获取的信息填充它。例如:
final bbleDevice = bluetoothLEManager.BluetoothDevice.fromId(connectingDevice.address);
请注意,不能保证这在任何情况下都有效,因为不同的类型可能有不同的实现,并且缺乏其他类型上存在的属性。