paint method

void paint(
  1. Canvas canvas,
  2. Offset offset
)

Paints the text onto the given canvas at the given offset.

Valid only after layout has been called.

If you cannot see the text being painted, check that your text color does not conflict with the background on which you are drawing. The default text color is white (to contrast with the default black background color), so if you are writing an application with a white background, the text will not be visible by default.

To set the text style, specify a TextStyle when creating the TextSpan that you pass to the TextPainter constructor or to the text property.

Implementation

void paint(Canvas canvas, Offset offset) {
  final _TextPainterLayoutCacheWithOffset? layoutCache = _layoutCache;
  if (layoutCache == null) {
    throw StateError(
      'TextPainter.paint called when text geometry was not yet calculated.\n'
      'Please call layout() before paint() to position the text before painting it.',
    );
  }

  if (!layoutCache.paintOffset.dx.isFinite || !layoutCache.paintOffset.dy.isFinite) {
    return;
  }

  if (_rebuildParagraphForPaint) {
    Size? debugSize;
    assert(() {
      debugSize = size;
      return true;
    }());

    final ui.Paragraph paragraph = layoutCache.paragraph;
    // Unfortunately even if we know that there is only paint changes, there's
    // no API to only make those updates so the paragraph has to be recreated
    // and re-laid out.
    assert(!_inputWidth.isNaN);
    layoutCache.layout._paragraph = _createParagraph(text!)..layout(ui.ParagraphConstraints(width: _inputWidth));
    assert(paragraph.width == layoutCache.layout._paragraph.width);
    paragraph.dispose();
    assert(debugSize == size);
  }
  assert(!_rebuildParagraphForPaint);
  canvas.drawParagraph(layoutCache.paragraph, offset + layoutCache.paintOffset);
}