flutter:第一次返回语句后的取消功能



我正在尝试用flatter_blue编程一个蓝牙应用程序,该应用程序只有在找到具有设备名称的特定设备时才会停止搜索设备。问题是while循环将返回多个设备对象,而不是仅返回一个并从那里停止代码。

我有时无法中断循环、listen((或while函数。

所以我的问题是:我该怎么做才能在找到设备后立即停止innerloop、list((和while loop,从而只向列表中添加一个设备?

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循环结束时,它都会继续启动一个新的侦听流。流实际上被取消了,但由于有很多流,实际上需要一段时间才能关闭所有流.

最新更新