我正在使用此代码订阅蓝牙变量。

flutterBlue.startScan(timeout: Duration(seconds: 4));

    // Listen to scan results
    flutterBlue.scanResults.listen((results) async {
      // do something with scan results
      for (ScanResult r in results) {
        print('${r.device.name} found! rssi: ${r.rssi}');
        if(r.device.name == kArduinoDeviceName){
          await r.device.connect();
          List<BluetoothService> services = await r.device.discoverServices();
          services.forEach((service) {
            if (service.uuid.toString() == kServiceUuid) {
              service.characteristics.forEach((characteristic) async {
                if (characteristic.uuid.toString() == CHARACTERISTIC_UUID) {
                  await characteristic.setNotifyValue(true);
                  characteristic.value.listen((value) {

                    print("received value: " + value.toString());

                    String receivedStr = ascii.decode(value);
                    print("receivedStr: " + receivedStr);
                    try {
                      Map<String, dynamic> jsonData = jsonDecode(receivedStr);
                      handleData(jsonData);
                    } catch(e){
                      print(e);
                    }
                  });
                }
              });
            }
          });
        }
      }
    });
    flutterBlue.stopScan();

问题是我没有得到完整的json值。它以21个字符为界。我已经用另一个应用程序验证了此值实际上是正确的,问题出在此characteristic.value.listen((value) {中。输出为:
I/flutter ( 6585): received value: [123, 34, 107, 109, 112, 104, 34, 58, 49, 49, 54, 44, 34, 114, 112, 109, 34, 58, 53, 56]
I/flutter ( 6585): receivedStr: {"kmph":116,"rpm":58
I/flutter ( 6585): FormatException: Unexpected end of input (at character 21)
I/flutter ( 6585): {"kmph":116,"rpm":58

最佳答案

我不得不用await device.requestMtu(512);使MTU更大

感谢:https://github.com/pauldemarco/flutter_blue/issues/611#issuecomment-645972227

09-13 11:47