scaleFontSize method

double scaleFontSize(
  1. double unscaledFontSize
)

Computes the scaled font size from the given unscaledFontSize, according to the user's platform preferences.

Many platforms allow users to scale text globally for better readability. Given the font size the app developer specified in logical pixels, this method converts it to the preferred font size (also in logical pixels) that accounts for platform-wide text scaling. The return value is always non-negative.

The scaled value of the same font size input may change if the user changes the text scaling preference (in system settings for example). The onTextScaleFactorChanged callback can be used to monitor such changes.

Instead of directly calling this method, applications should typically use MediaQuery.textScalerOf to retrive the scaled font size in a widget tree, so text in the app resizes properly when the text scaling preference changes.

Implementation

double scaleFontSize(double unscaledFontSize) {
  assert(unscaledFontSize >= 0);
  assert(unscaledFontSize.isFinite);

  if (textScaleFactor == 1.0) {
    return unscaledFontSize;
  }

  final int unscaledFloor = unscaledFontSize.floor();
  final int unscaledCeil = unscaledFontSize.ceil();
  if (unscaledFloor == unscaledCeil) {
    // No need to interpolate if the input value is an integer.
    return _scaleAndMemoize(unscaledFloor) ?? unscaledFontSize * textScaleFactor;
  }
  assert(unscaledCeil - unscaledFloor == 1, 'Unexpected interpolation range: $unscaledFloor - $unscaledCeil.');

  return switch ((_scaleAndMemoize(unscaledFloor), _scaleAndMemoize(unscaledCeil))) {
    (null, _) || (_, null)                   => unscaledFontSize * textScaleFactor,
    (final double lower, final double upper) => lower + (upper - lower) * (unscaledFontSize - unscaledFloor),
  };
}