flutter_blue部分特征属性识别异常 无法写入特征问题求助
问题根因说明
你遇到的问题核心有两类可能:
- 你的蓝牙特征仅开启了*无响应写(writeWithoutResponse)*权限,未开启带响应写权限。flutter_blue的
write方法默认使用带响应写(withoutResponse = false),不符合特征权限要求;其他第三方蓝牙工具通常会自动适配写入类型,所以可以写入成功。 - flutter_blue原生层对该特征的属性解析异常,导致返回的
properties字段和设备实际支持的能力不符。另外从你给出的源码可以看到,flutter_blue的write方法本身没有内置权限校验,你看到的无写入权限报错大概率是业务代码中自行判断characteristic.properties.write的值抛出的。
解决方案
方案1:切换写入类型(优先尝试,90%以上场景可解决)
先打印当前特征的两个写入相关属性确认:
print("带响应写权限:${characteristic.properties.write}"); print("无响应写权限:${characteristic.properties.writeWithoutResponse}");
如果writeWithoutResponse为true,调用write方法时指定withoutResponse参数为true即可:
// 填入你要写入的字节数组,指定无响应写入 await characteristic.write([0x01, 0x02...], withoutResponse: true);
方案2:绕过业务代码的权限校验
如果确认其他工具可以正常写入该特征,但两个写入属性都为false,说明是flutter_blue属性解析异常,直接去掉业务代码中对characteristic.properties.write的判断逻辑,直接调用write方法即可,可根据设备的写入要求选择是否带响应。
方案3:修改flutter_blue源码强制开启指定特征的写入权限
如果你不想修改原有业务的权限校验逻辑,可以直接修改flutter_blue的源码,对指定UUID的特征强制开启写入权限:
找到bluetooth_characteristic.dart文件中的BluetoothCharacteristic.fromProto构造方法,修改properties的赋值逻辑:
BluetoothCharacteristic.fromProto(protos.BluetoothCharacteristic p) : uuid = new Guid(p.uuid), deviceId = new DeviceIdentifier(p.remoteId), serviceUuid = new Guid(p.serviceUuid), secondaryServiceUuid = (p.secondaryServiceUuid.length > 0) ? new Guid(p.secondaryServiceUuid) : null, descriptors = p.descriptors .map((d) => new BluetoothDescriptor.fromProto(d)) .toList(), // 替换下方的XXXX为你要写入的特征UUID字符串,匹配到时强制开写入权限 properties = p.uuid == "XXXX-XXXX-XXXX-XXXX" ? CharacteristicProperties( broadcast: p.properties.broadcast, read: p.properties.read, writeWithoutResponse: true, write: true, notify: p.properties.notify, indicate: p.properties.indicate, authenticatedSignedWrites: p.properties.authenticatedSignedWrites, extendedProperties: p.properties.extendedProperties, notifyEncryptionRequired: p.properties.notifyEncryptionRequired, indicateEncryptionRequired: p.properties.indicateEncryptionRequired, ) : new CharacteristicProperties.fromProto(p.properties), _value = BehaviorSubject.seeded(p.value);
其他排查点
- 确认你获取的特征所属的服务UUID正确,部分设备存在相同UUID的特征归属于不同服务的情况,选错服务也会导致属性异常。
- 确认蓝牙连接正常,且已经完成必要的配对/加密流程,部分设备需要配对后才会返回正确的特征属性。
内容的提问来源于stack exchange,提问作者Engineer Tr
相关产品推荐
相关产品推荐

