nearestEnabled method

int? nearestEnabled(
  1. int index, {
  2. bool? forward,
})

The live row nearest index (clamped to the column), index itself when it is live. forward picks which way to look first: true, the rows after; false, before; null, the nearer (before on a tie). A looping column counts its distances round the ends. Null when no row is live.

Implementation

int? nearestEnabled(int index, {bool? forward}) {
  final from = index.clamp(0, itemCount - 1);
  if (isEnabled(from)) return from;
  int? step(int sign) {
    for (var d = 1; d < itemCount; d++) {
      var i = from + sign * d;
      if (looping) {
        i %= itemCount;
      } else if (i < 0 || i >= itemCount) {
        return null;
      }
      if (isEnabled(i)) return i;
    }
    return null;
  }

  if (forward != null) {
    return step(forward ? 1 : -1) ?? step(forward ? -1 : 1);
  }
  final before = step(-1);
  final after = step(1);
  if (before == null || after == null) return before ?? after;
  int distance(int i) {
    final d = (i - from).abs();
    return looping ? (d < itemCount - d ? d : itemCount - d) : d;
  }

  return distance(after) < distance(before) ? after : before;
}