drawText method Null safety

void drawText(
  1. Canvas canvas,
  2. TextStyle style,
  3. String text,
  4. double w,
  5. Offset offset
)

Implementation

void drawText(
    Canvas canvas, TextStyle style, String text, double w, Offset offset) {
  final String normal;
  final String? superscript;
  final String? subscript;
  final caret = text.indexOf('^');
  if (caret == -1) {
    normal = text;
    superscript = subscript = null;
  } else {
    normal = text.substring(0, caret);
    final remain = text.substring(caret + 1);
    final caret2 = remain.indexOf('^');
    if (caret2 == -1) {
      superscript = remain;
      subscript = null;
    } else {
      superscript = remain.substring(0, caret2);
      subscript = remain.substring(caret2 + 1);
    }
  }
  TextSpan span = TextSpan(style: style, text: normal);
  TextPainter tp = TextPainter(
      text: span,
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr);
  if (superscript == null && subscript == null) {
    tp.layout(minWidth: w);
    tp.paint(canvas, offset);
  } else {
    const scale = 0.75;
    tp.layout();
    double width = tp.width;
    final TextPainter? tpSup;
    final TextPainter? tpSub;
    if (superscript == null) {
      tpSup = null;
    } else {
      tpSup = TextPainter(
          text: TextSpan(style: style, text: superscript),
          textAlign: TextAlign.center,
          textDirection: TextDirection.ltr);
      tpSup.layout();
      width += tpSup.width * scale;
    }
    if (subscript == null) {
      tpSub = null;
    } else {
      tpSub = TextPainter(
          text: TextSpan(style: style, text: subscript),
          textAlign: TextAlign.center,
          textDirection: TextDirection.ltr);
      tpSub.layout();
      if (tpSup != null) {
        final extra = tpSub.width - tpSup.width;
        if (extra > 0) {
          width += extra * scale;
        }
      } else {
        width += tpSub.width * scale;
      }
    }
    canvas.save();
    canvas.translate(offset.dx + (w - width) / 2, offset.dy);
    final integralCheat = normal == '\u222b';
    if (integralCheat) {
      canvas.translate(0, -5);
    }
    tp.paint(canvas, const Offset(0, 0));
    if (integralCheat) {
      canvas.translate(0, -6);
    }
    canvas.translate(tp.width, 30 - tp.height);
    canvas.scale(scale);
    tpSup?.paint(canvas, const Offset(0, 0));
    canvas.translate(0, 22);
    tpSub?.paint(canvas, const Offset(0, 0));
    canvas.restore();
  }
}