skip to Main Content

I have two functions in flutter. the first one is belManager.writeCharacteristic and the second one is belManager.disonnect I want to execute belManager.disonnect() after belManager.writeCharacteristic is completed. However for some reason bleManager.disonenct() is called before belManager.writeCharacteristic is completed.
this is the code:

   switch (currentState) {
                    case BluetoothDeviceState.connected:
          await bleManager!.writeCharacteristic();
                      await bleManager.disconnect()
                      break;
                    case BluetoothDeviceState.disconnected:
                      print("please connect");
                      break;

thanks in advance for your suggestions.

2

Answers


  1. Follow these steps and update your question with more detailed code if it doesn’t help:

    • Check if your function has async, without it all the awaits are useless.
    • Put a try/catch inside the switch, so if it generates an exception, you can easily find it.
    • Call the disconnect() method inside a .then() right after your writeCharacteristic(), by doing so you should be able to "force" firing disconnect() method only when writeCharacteristic() is completed.
    • Check if the Future from writeCharacheristic() is normally completed and it does what it should.

    If this doesn’t help please comment below and update your question, happy coding!

    Login or Signup to reply.
  2. You just need to wrap your logic inside Async Function so you can easily await the methods.

      getConnectionStatus(var currentState)async{
    switch (currentState) {
      case BluetoothDeviceState.connected:
        await bleManager!.writeCharacteristic();
    await bleManager.disconnect()
    break;
    case BluetoothDeviceState.disconnected:
    print("please connect");
    break;}}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search