How to Use a TextPainter to Draw Text In Flutter in 2021?

Jul 12

Using a Text Painter To Draw Text:

Today we will talk about that how we can use a text painter in a flutter to draw a text.

As we all know, text widgets allow us to display text in Flutter.
In the Flutter framework,  we use the CustomPaint widget to paint. CustomPainter widget then uses another parameter “CustomPainter” as an object.
@override
void paint(Canvas canvas, Size size) {
  final textStyle = TextStyle(
    color: Colors.black,
    fontSize: 30,
  );
  final textSpan = TextSpan(
    text: 'Hello, world.',
    style: textStyle,
  );
  final textPainter = TextPainter(
    text: textSpan,
    textDirection: TextDirection.ltr,
  );
  textPainter.layout(
    minWidth: 0,
    maxWidth: size.width,
  );
  final offset = Offset(50, 100);
  textPainter.paint(canvas, offset);
}

TextSpan line must be changed. It was either drawing the text invisible or with a white background.

You must also specify the TextDirection parameter in the TextPainter constructor, otherwise, you’ll receive an exception

TextSpan span = new TextSpan(style: new TextStyle(color: Colors.grey[600]), text: 'Yrfc');

TextSpan span = new TextSpan(style: new TextStyle(color: Colors.blue[800]), text: name);
TextPainter tp = new TextPainter(text: span, textAlign: TextAlign.left, textDirection: TextDirection.ltr);
tp.layout();
tp.paint(canvas, new Offset(5.0, 5.0));

Some Points To Remember:

  • If your background is white, your text is set to the default white color.
  • Flutter tries to avoid assuming text direction, so you need to set it explicitly. Languages like English use the abbreviation ltr for left-to-right. The other option is rtl (right-to-left), which some other languages use. It reduces bugs when developers use the code in language contexts they did not expect.

Final Words:

In this short article, we explained that how you can easily draw a text using a Text painter. You can copy this code & practice at home. If you have any problem using this code then you can let us know.
Thanks for reading out this article & connected with us (The world’s best flutter development company). If you need any kind of help in flutter or you want to build a brand new flutter app for your business then just message us.