【问题标题】:flutter: Cancel function after first return statement颤振:第一个返回语句后取消功能
【发布时间】: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


【解决方案1】:

您可以使用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'),
  });
});

【讨论】:

    【解决方案2】:

    我解决了这个问题,将流监听放在 while 循环之外。它碰巧使应用程序崩溃,每次while循环完成时,它都会继续开始新的监听流。流实际上已被取消,但由于其中有很多流,实际上需要一段时间才能关闭所有流 .

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 2021-06-02
      • 2021-12-27
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多