How to wait for ble connection to actually be made before continuing

Solution for How to wait for ble connection to actually be made before continuing
is Given Below:

I’m using Flutter’s flutter_reactive_ble package and am having a problem trying to do operations in a for loop.

Situation:

  • I have a list of device ids
  • I want to loop through this list and do the following: connect, write to some characteristics, disconnect

Here’s my code: (note: this is in the onPressed section of an IconButton)

IconButton(
  ...
  ...
  onPressed:
for (String deviceId in deviceIdList) {
                    try {
                      await Provider.of<BleDeviceConnector>(context, listen: false)
                          .connect(deviceId)
                          .then((value) => loadStuff(context))
                          .then((value) =>
                          Provider.of<BleDeviceConnector>(context, listen: false)
                              .disconnect(deviceId));
                    } catch (e) {
                      print(e);
                    }
)

The problem I’m having is that the first ‘connect’ function gets called, but it doesn’t wait to actually connect before continuing in the loop.

This results in the entire loop being completed before my device even connects.

FYI…The first device does end up connecting, but then the whole app freezes because I believe it’s in a lost state.

Thanks for any help/suggestions.

— UPDATE —

I decided to split this up and was able to get the loop to connect and load to multiple devices.

However, I’m still having issues disconnecting from all of the connected devices. I have a list of device Ids that I’m connected to, and have tried the following:

  1. for loop that calls the following on each deviceId in the deviceIdList:

    await Provider.of<BleDeviceConnector>(context, listen: 
    false).disconnect(deviceId);
    
  2. Implemented a button that tries to disconnect from one device at a time (one per button click)

Both attempts result in being able to disconnect from the first connected device in the list, but fails to successfully disconnect from any of the rest.

Any ideas? Thanks!