【发布时间】:2020-08-17 14:03:22
【问题描述】:
我正在尝试使用 flutter_blue 对蓝牙应用程序进行编程,该应用程序仅在找到具有设备名称的特定设备时才会停止搜索设备。问题是 while 循环将返回多个设备对象,而不是只返回一个并从那里停止代码。
我无法打破循环、listen() 或 while 函数。
所以我的问题是:在找到设备后立即停止内部循环、listen() 和 while 循环,我该怎么做才能只将一个设备添加到列表中?
Future<void> specificDevice({deviceName: ''}) async {
// reset values
_reset();
// Start scanning and keep on as long as no Device found
print('Starting search..');
while (_deviceFound == false) {
await _flutterBlue.startScan(
timeout: Duration(seconds: 10),
);
_stream = _flutterBlue.scanResults.listen((results) async {
print('looking..');
// Return found Devices
innerloop:
for (ScanResult r in results) {
counter++;
print('CounterForSchleife: $counter');
//Does found device equal searched Device?
if (r.device.name.contains(deviceName)) {
_deviceFound = true;
devices.add(r.device);
print('Device found...');
_stream.cancel();
break innerloop;
}
}
if (_deviceFound) {
print('Broke innerloop');
// _stream.cancel();
}
});
await _flutterBlue.stopScan();
}
}
【问题讨论】:
-
我解决了这个问题,将流监听放在 while 循环之外。它碰巧使应用程序崩溃,它会继续启动新的流,直到它们发出声音。流实际上已被取消,但由于其中有很多流,实际上需要一段时间才能关闭所有流。
标签: loops flutter bluetooth break listen