calculateFontSize method

double calculateFontSize(
  1. String text,
  2. double maxWidth, {
  3. double minFontSize = 8,
  4. double maxFontSize = 100,
})

Implementation

double calculateFontSize(String text, double maxWidth, {double minFontSize = 8, double maxFontSize = 100}) {
  double fontSize = maxFontSize;
  final textPainter = TextPainter(
    text: TextSpan(text: text, style: TextStyle(fontSize: fontSize)),
    maxLines: 1,
    textDirection: TextDirection.ltr,
  );

  while (fontSize > minFontSize) {
    textPainter.text = TextSpan(text: text, style: TextStyle(fontSize: fontSize));
    textPainter.layout();

    if (textPainter.size.width <= maxWidth) {
      break;
    }
    fontSize -= 1;
  }

  return fontSize;
}