getConnection method Null safety

Future<ConnectionWrapper> getConnection()

Implementation

Future<ConnectionWrapper> getConnection() async {
  await requireLock();

  final idleConnections =
      pools.values.where((conn) => !conn.handle).toList(growable: false);
  if (idleConnections.isNotEmpty) {
    idleConnections.first.lock();
    releaseLock();
    return idleConnections.first;
  } else {
    if (pools.length < _poolSize) {
      final conn = ConnectionWrapper(
          Uuid().v4().toString(), settings, removeConnection);
      conn.lock();
      await conn.open();
      pools.addEntries([MapEntry(conn.cid, conn)]);
      releaseLock();
      return conn;
    } else {
      // TODO: 连接池不为空,又没有空闲的连接。就等待 x ms 后再尝试
      for (var i = 0; i < 100; i++) {
        await Future.delayed(Duration(milliseconds: 10));
        final idleConns = pools.values
            .where((conn) => !conn.handle)
            .toList(growable: false);
        if (idleConns.isNotEmpty) {
          idleConns.first.lock();
          releaseLock();
          return idleConns.first;
        }
      }
      releaseLock();
      throw PoolOverloadedException();
    }
  }
}