Flutter中如何确保两个异步函数按顺序执行?
解决Flutter中BLE写入未完成就执行断开连接的问题
可能原因及解决方案
1. 确认writeCharacteristic方法正确实现异步逻辑
问题核心大概率是writeCharacteristic没有正确返回一个等待BLE写入操作完成的Future。如果这个方法内部没有等待写入操作结束就返回,await会直接跳过,导致disconnect提前执行。
检查你的writeCharacteristic实现,确保它:
- 返回
Future<void>类型 - 内部真正等待BLE写入操作完成后才结束Future
示例正确实现(以flutter_blue_plus为例):
Future<void> writeCharacteristic() async { // 替换为你的目标特征值对象 final targetCharacteristic = ...; // 等待写入操作完成 await targetCharacteristic.write([0x01, 0x02]); }
2. 捕获异常排查执行流程
如果写入过程中抛出异常但未被捕获,代码会直接跳过写入后的逻辑,提前执行disconnect。添加try-catch块打印日志,确认写入是否成功完成:
case BluetoothDeviceState.connected: try { await bleManager!.writeCharacteristic(); print("BLE写入操作已完成"); await bleManager.disconnect(); print("设备已断开连接"); } catch (e) { print("写入失败: $e"); } break;
3. 将回调式写入转换为Future(针对部分BLE库)
如果使用的BLE库写入操作是基于回调通知结果,而非返回Future,需要用Completer包装成Future,确保await能等待操作完成:
Future<void> writeCharacteristic() { final completer = Completer<void>(); // 假设库的写入方法是回调式 yourBleLibrary.write( targetCharacteristic, yourData, (bool success) { if (success) { completer.complete(); } else { completer.completeError("BLE写入失败"); } }, ); return completer.future; }
内容的提问来源于stack exchange,提问作者ASMA
相关产品推荐
相关产品推荐

