title: Flutter connecting to multiple BLE devices Synchronously
body: <p>I'm using flutter to work on an bluetooth low energy app, via the flutterBlue library, in which we are potentially connecting to multiple peripherals at the same time.
  I am able to connect to multiple peripherals if I connect to them individually and send commands to all of them simultaneously.
  For state management, my BluetoothHelper is the Model for my ScopedModel. </p>
  
  <pre><code>class BluetoothHelper extends Model {
  
    bool isProcessing = false; 
    int val = 0;
  
    FlutterBlue flutterBlue = FlutterBlue.instance; //bluetooth library instance
  
    StreamSubscription scanSubscription;
    Map&lt;DeviceIdentifier, ScanResult&gt; scanResults = new Map();
  
    /// State
    StreamSubscription stateSubscription;
    BluetoothState state = BluetoothState.unknown;
  
    /// Device
    List&lt;BluetoothDevice&gt; devicesList = new List(); //todo
  
    bool get isConnected =&gt; (deviceList.size != 0);
    StreamSubscription deviceConnection;
    StreamSubscription deviceStateSubscription;
    List&lt;BluetoothService&gt; services = new List();
    Map&lt;Guid, StreamSubscription&gt; valueChangedSubscriptions = {};
    BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;
  
    Future startScan(String uuid) async {
      isProcessing = true;
      if (val == 0) {
        Future.delayed(Duration(milliseconds: 25), () =&gt; scanAndConnect(uuid));
        val++;
      } else {
        Future.delayed(Duration(seconds: 4), () =&gt; scanAndConnect(uuid));
      }
    }
  
    scanAndConnect(String uuid){
      scanSubscription =
          flutterBlue.scan(timeout: const Duration(seconds: 120), withServices: [
            //new Guid('FB755D40-8DE5-481E-A369-21C0B3F39664')]
          ]).listen((scanResult) {
            if (scanResult.device.id.toString() == uuid) {
              scanResults[scanResult.device.id] = scanResult;
  
              print("found! Attempting to connect" + scanResult.device.id.toString());
              device = scanResult.device;
  
              //connect(device);
              connect(device);
            }
          }, onDone: stopScan);
    }
  
    Future connect(BluetoothDevice d) {
  
      deviceConnection = flutterBlue.connect(d).listen(
            null,
          );
  
      deviceStateSubscription = d.onStateChanged().listen((s) {
        if (s == BluetoothDeviceState.connected) {
          stopScan();
          d.discoverServices().then((s) {
            print("connected to ${device.id.toString()}");
            services = s;
            services.forEach((service) {
              var characteristics = service.characteristics;
              for (BluetoothCharacteristic c in characteristics) {
                if (c.uuid.toString() == '') {//we look for the uuid we want to write to
                  String handshakeValue ; //value is initiliazed here in code
                  List&lt;int&gt; bytes = utf8.encode(handshakeValue);
                  d.writeCharacteristic(c, bytes,
                      type: CharacteristicWriteType.withResponse);
                       devicesList.add(d);
                }
              }
            });
          });
        }
      });
  
    }
  }
  </code></pre>
  
  <p>I am trying to loop throw all peripheral Unique Identifier (UID) and then have them connect one after the other programmatically.</p>
  
  <p>This wasnt working out great. It would always end up connecting to the very last peripheral. Seems like the flutterblue instance can only scan for one uid at a time, and if it receives another request, it immediately drops the last request and moves to the new one.</p>
  
  <p>I applied this same logic to the connection of an individual peripheral logic where I'd tap one peripheral and the second immediately and it'd connect to the second one. (I'm not currently blocking the UI or anything while the connection process takes place)
  I need to wait till the first peripheral is connected before moving onto the next one. </p>
  
  <p>The code above is the only way I've gotten my peripherals but there are huge problems with this code. It can currently only connect to 2 devices. It's using delays instead of callbacks to achieve connection by giving enough time for the scan and connect to happen before moving onto the second peripheral.</p>
  
  <p>My first instinct was to make the convert the startScan and connect methods into async methods but this isnt working out well as I'd hope.</p>
  
  <p>{await connect(device); } => gives "The built in Identifier "await" cant be used as a type. I could just be setting up the asyncs incorrectly.</p>
  
  <p>I have looked around for alternatives and I've come upon Completers and Isolates. I'm not sure how relevant that might be.</p>
  
  <p>UI SIDE : </p>
  
  <p>I have the following method set for the ontap of a button wrapped within a scoped model descendant. This is going to reliably load peripheralUIDs list with a few uids and then connect to them one after the other. </p>
  
  <pre><code>connectAllPeripherals(BluetoothHelper model, List&lt;String&gt; peripheralUIDs) {
      for(var uuid in peripheralUIDs) { //list of strings containing the uuids for the peripherals I want to connect to
        model.startScan(uuid);
      }
  }
  </code></pre>