如何解决颤动:在第一个return语句后取消功能
我正在尝试使用flutter_blue编程一个蓝牙应用程序,该应用程序只会在找到具有设备名称的特定设备时才停止搜索设备。问题在于,while循环将返回多个设备对象,而不是仅返回一个设备对象,并从此处停止代码。
我无法中断循环,listen()或while函数。
所以我的问题:找到设备后立即停止innerloop,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();
}
}
解决方法
您可以使用CancelableOperation。
test("CancelableOperation with future",() async {
var cancellableOperation = CancelableOperation.fromFuture(
Future.value('future result'),onCancel: () => {debugPrint('onCancel')},);
// cancellableOperation.cancel(); // uncomment this to test cancellation
cancellableOperation.value.then((value) => {
debugPrint('then: $value'),});
cancellableOperation.value.whenComplete(() => {
debugPrint('onDone'),});
});
,
我解决了这个问题,方法是将流监听置于while循环之外。碰巧崩溃了该应用程序,每次while循环结束时,它将继续开始对流进行新的侦听。溪流实际上被取消了,但是由于有很多溪流,实际上要花一些时间才能关闭所有溪流
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。