【问题标题】:Capture a BLE characteristic and assign it to a variable in Flutter捕获 BLE 特征并将其分配给 Flutter 中的变量
【发布时间】:2023-04-07 11:56:01
【问题描述】:

我需要在按下时立即捕获特征的特定值。所以我为此写了一个函数。问题是,到目前为止,我无法将值分配给变量。解决问题的最佳方法是什么?

我正在使用下面的 flutter_blue 示例代码: https://pub.dev/packages/flutter_blue#-readme-tab-

我的功能是:

  List<int> _testReadCharacteristic(String uuid) {
    List<int> value;
    device.services.forEach((ls) async {
      //Scans the Liste for all services
      ls.forEach((s) async {
        // Scans the List of services for a specific service
        // do something with s
        List<BluetoothCharacteristic> characteristics = s.characteristics;
        for (BluetoothCharacteristic c in characteristics) {
          // Scans all characteristics
          if (c.uuid.toString().toUpperCase().substring(4, 8) == uuid) {
            value = await c.read();
            print('**************** value is: $value');
          }
        }
      });
    });
    return value;
  }

按钮的代码是:

        RaisedButton(
          onPressed: () {
           capturedValue = _testReadCharacteristic('1100');
          print('***********The captured Value is: $capturedValue');
          },
          child: const Text('Read Characteristic',
              style: TextStyle(fontSize: 20)),
        ),

当我按下按钮时,我首先打印出捕获的值,它是 Null。之后,我得到一个值的打印,这正是我想要分配给 captureValue 的值。如何更改订单以便使用 captureValue?

【问题讨论】:

    标签: flutter bluetooth-lowenergy assign


    【解决方案1】:

    问题是List.forEach 不尊重/等待异步函数。这意味着您的变量永远不会及时分配,而是返回空,然后在异步完成读取后分配。

    您可以实现您的预​​期行为,您必须将_testReadCharacteristic 转换为和同步方法,并在您的按钮onPressed 处理程序中等待它。此外,您需要使用Future.forEach 而不是List.forEach,以便外部方法可以等待结果:

    List<int> _testReadCharacteristic(String uuid) async {
        List<int> value;
        await Future.forEach(device.services.forEach((ls) async {
            //Scans the Liste for all services
            await Future.forEach(ls, (s) async {
            // Scans the Liste of services for a specific service
            // do something with s
            List<BluetoothCharacteristic> characteristics = s.characteristics;
                for (BluetoothCharacteristic c in characteristics) {
                    // Scans all characteristics
                    if (c.uuid.toString().toUpperCase().substring(4, 8) == uuid) {
                       value = await c.read();
                       print('**************** value is: $value');
                    }
                }
            });
        });
        return value;
    }
    

    最后在你的onPressed

    capturedValue = await _testReadCharacteristic('1100');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 2018-08-22
      • 1970-01-01
      • 2014-11-08
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多