autoFit static method

void autoFit(
  1. ChartScale scale, {
  2. required num dataMin,
  3. required num dataMax,
  4. int minLines = 4,
  5. int maxLines = 7,
  6. bool forceZero = false,
  7. double minSpan = 0,
})

Computes chart-friendly axis bounds and gridlines.

  • minLines / maxLines: bounds on the gridline count (endpoints included). Both must be >= 2.
  • forceZero: if true, pins the axis to include exactly 0 as a bound whenever the data doesn't already straddle zero.
  • minSpan: the minimum allowed max - min before nice rounding. If the data range is narrower than this, it's widened (toward zero first for same-sign data, symmetrically otherwise). 0 disables this.

Implementation

static void autoFit(
  ChartScale scale, {
  required num dataMin,
  required num dataMax,
  int minLines = 4,
  int maxLines = 7,
  bool forceZero = false,
  double minSpan = 0,
}) {
  assert(minLines >= 2, 'minLines must be >= 2 (need at least start/end)');
  assert(maxLines >= minLines, 'maxLines must be >= minLines');
  assert(dataMax >= dataMin, 'dataMax must be >= dataMin');
  assert(minSpan >= 0, 'minSpan must be >= 0');

  var min = dataMin.toDouble();
  var max = dataMax.toDouble();

  if (minSpan > 0) {
    final result = _applyMinSpan(min, max, minSpan);
    min = result.$1;
    max = result.$2;
  }

  // Degenerate case: no data range at all (a single point, or every
  // value identical). There's no objectively "correct" answer, so we
  // fall back to a small nominal span centered on the value.
  if (max - min <= 0) {
    final nominalRange = max == 0 ? 1.0 : max.abs();
    min -= nominalRange / 2;
    max += nominalRange / 2;
  }

  if (forceZero) {
    final result = _applyForceZero(min, max);
    min = result.$1;
    max = result.$2;
  }

  final step = _chooseStep(min, max, minLines, maxLines);
  final niceMin = (min / step).floor() * step;
  final niceMax = (max / step).ceil() * step;

  scale.min = niceMin;
  scale.max = niceMax;
  scale.setLinesByStep(step);
}