clampByViewportWidth method

double clampByViewportWidth({
  1. required double minValue,
  2. required double maxValue,
  3. double minW = 360,
  4. double maxW = 1200,
})

Linearly interpolates between minValue and maxValue across the width range [minW, maxW], clamped at both ends — the CSS clamp() equivalent.

Returns minValue at or below minW, maxValue at or above maxW, and the proportional value in between. Values past either end are clamped, never extrapolated.

final fontSize = context.clampByViewportWidth(
  minValue: 14, maxValue: 20, minW: 360, maxW: 1200,
);

Hardening: if a caller passes a degenerate range (minW >= maxW, i.e. zero or negative span), this returns minValue instead of producing a NaN / Infinity from a divide-by-zero.

Width read (shared with responsiveByViewportWidth): reads the nearest MediaQuery width at the call site (MediaQuery.sizeOf(this).width) — not the ResponsiveScope's device class. In a normal single- MediaQuery app this equals the device width; it diverges only under a deliberately nested MediaQuery override, where it tracks the local sub-region (note the Viewport in the name). It rebuilds per-pixel by design and requires only a MediaQuery ancestor — no ResponsiveScope needed.

Implementation

double clampByViewportWidth({
  required double minValue,
  required double maxValue,
  double minW = 360,
  double maxW = 1200,
}) {
  final w = MediaQuery.sizeOf(this).width;
  final range = maxW - minW;
  if (range <= 0) return minValue; // degenerate-range guard (BEH-08)
  final t = ((w - minW) / range).clamp(0.0, 1.0);
  return minValue + (maxValue - minValue) * t;
}