0

I am buildig a CustomPaint widget to display text in a custom way, using ParagraphBuilder, named it myHtmlWidget.

My problem is how to determine height of widget before painting it? I tried to call ParagraphBuilder in constructor of MyHtmlPainter and measure height, but I don't have width there!

This is a section of my build tree:

Widget myHtmlWidget(List<dom.Element> spans, TextAlign ebookTextAlign) {
    var painter = MyHtmlPainter(spans, ebookTextAlign);
    return CustomPaint(
      painter: painter,
      child: Container(
        height: 550, // **** THIS IS THE PROBLEM, I WANT IT TO MATCH/FIT TO THE HEIGHT OF RENDERED TEXT
      ),
    );
  }

and this is MyHtmlPainter:

class MyHtmlPainter extends CustomPainter {
  List<dom.Element> spans;
  TextAlign ebookTextAlign;

  ui.Paragraph paragraph;

  MyHtmlPainter(this.spans, this.ebookTextAlign);

  @override
  void paint(Canvas canvas, Size size) {
    var pin = Offset(0, 0);
    // To create a paragraph of text, we use ParagraphBuilder.
    final ui.ParagraphBuilder builder = ui.ParagraphBuilder(
      ui.ParagraphStyle(
        textDirection: ui.TextDirection.rtl,
        textAlign: ebookTextAlign,
        fontSize: ebookMainTextSize,
      ),
    )
      ..pushStyle(ui.TextStyle(color: const ui.Color(0xFF000000)));

    spans.forEach((spn) {
      if (spn.localName == "p")
        builder.addText("\n");
      builder.addText(spn.text + " ");
    });
    builder.pop();

    paragraph = builder.build()

      ..layout(ui.ParagraphConstraints(width: size.width));
    canvas.drawParagraph(paragraph, pin);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return null;
  }
}
AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210

0 Answers0