getOrBuild method

TextPainter getOrBuild({
  1. required TextNode node,
  2. required TextStyle textStyle,
  3. required double maxWidth,
})

Implementation

TextPainter getOrBuild({
  required TextNode node,
  required TextStyle textStyle,
  required double maxWidth,
}) {
  final safeFontSize = clampPositiveFinite(node.fontSize, fallback: 24.0);
  final safeBoxSize = clampNonNegativeSizeFinite(node.size);
  final safeLineHeight =
      (node.lineHeight != null &&
          node.lineHeight!.isFinite &&
          node.lineHeight! > 0)
      ? node.lineHeight
      : null;
  final safeMaxWidth = clampNonNegativeFinite(maxWidth);
  final key = _TextLayoutKey(
    nodeId: node.id,
    text: node.text,
    fontSize: safeFontSize,
    fontFamily: node.fontFamily,
    isBold: node.isBold,
    isItalic: node.isItalic,
    isUnderline: node.isUnderline,
    align: node.align,
    lineHeight: safeLineHeight,
    maxWidth: safeMaxWidth,
    boxSize: safeBoxSize,
    color: textStyle.color ?? const Color(0xFF000000),
  );

  final cached = _entries.remove(key);
  if (cached != null) {
    _entries[key] = cached;
    _debugHitCount += 1;
    return cached;
  }

  final textPainter = TextPainter(
    text: TextSpan(text: node.text, style: textStyle),
    textAlign: node.align,
    textDirection: TextDirection.ltr,
    maxLines: null,
  );
  textPainter.layout(maxWidth: safeMaxWidth);
  _entries[key] = textPainter;
  _debugBuildCount += 1;
  _evictIfNeeded();
  return textPainter;
}