【发布时间】:2018-12-20 00:31:59
【问题描述】:
我目前正在尝试等待 BLE 连接产生以下两种结果之一:
- 设备连接成功,或
- 扫描超时后设备连接失败
不会根据需要返回 true 或 false 值,而是立即返回 null,而无需等待函数完成。
我正在使用 dart 的 Future 和异步功能来等待连接功能的完成。下面是我的代码:
BLE 连接方法:
static Future<bool> connect(BluetoothDevice d) async {
// Connect to device
Duration timeout = new Duration(seconds: 5);
deviceConnection = _flutterBlue.connect(d, timeout: timeout).listen((s) {
deviceState = s;
if (s == BluetoothDeviceState.connected) {
device = d;
device.discoverServices().then((s) {
... Some service discovery stuff ...
});
}
}, onDone: () {
return deviceState == BluetoothDeviceState.connected;
});
}
从哪里调用connect方法:
bool isConnected = await FlutterBLE.connect(device);
if(isConnected) {
... Do some stuff ...
} else {
... Do some other stuff ...
}
我在这里做错了什么?
【问题讨论】:
标签: dart flutter dart-async