颤动:在第一个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循环结束时,它将继续开始对流进行新的侦听。溪流实际上被取消了,但是由于有很多溪流,实际上要花一些时间才能关闭所有溪流

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...