我目前正在尝试等待BLE连接导致以下两种结果之一:
与其返回所需的true或false值,而是立即返回null,而无需等待函数完成。
我正在使用dart的Future和async功能,以等待connect功能完成。这是下面的代码:
BLE Connect方法:
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 ...
}
我在这里做什么错了?
答案 0 :(得分:3)
正如GüntherZöchbauer所指出的那样,错误出在"Helloworld"
部分。您将在那里返回一个没人会看到的值,也不会从周围的函数中返回任何东西。
您位于异步函数中,因此可以使用onDone
来迭代流。
您还希望在第一次获得连接事件时停止监听流,因为您只关心第一个连接。连接事件流本身永不停止。
await for
如果您不想使用static Future<bool> connect(BluetoothDevice d) async {
// Connect to device
Duration timeout = const Duration(seconds: 5);
await for (var s in _flutterBlue.connect(d, timeout: timeout)) {
deviceState = s;
if (s == BluetoothDeviceState.connected) {
device = d;
device.discoverServices().then((s) {
... Some service discovery stuff ...
});
return true;
}
}
// The stream ended somehow, there will be no further events.
return false;
}
(并且不想使用异步功能开始),建议您使用await for
在{{1 }}:
firstWhere
还有一点怀疑,就是没有人等待listen
返回的未来。确保这是正确的。
答案 1 :(得分:0)
onDone
部分没有达到您的期望。
请尝试:
static Future<bool> connect(BluetoothDevice d) async {
// Connect to device
Duration timeout = new Duration(seconds: 5);
await _flutterBlue.connect(d, timeout: timeout).listen((s) {
deviceState = s;
if (s == BluetoothDeviceState.connected) {
device = d;
device.discoverServices().then((s) {
... Some service discovery stuff ...
});
}
}).asFuture();
return deviceState == BluetoothDeviceState.connected;
}