Alp
Alp

Reputation: 377

How can I add line numbers to TextField on Flutter?

I am trying to add line numbers to text field on Flutter, like on any text editors. I have text that overflows to next line, so I want to show where lines start and end.

First way that came to my mind was to separate the screen into two columns, one for line numbers on left and one for right for the textfield. However, due to screen size differences, I can't know when a line will overflow.

Is there any more formal way to do it?

Upvotes: 15

Views: 2075

Answers (3)

willypede
willypede

Reputation: 199

First, initialize a List of TextField and an currentLine integer variables. TextField must contain properties named textInputAction and onEditingComplete. So each time you press enter, it is considered as finished with current TextField, creating a new TextField and add it into List of TextField and will move the focus to the new TextField. Line numbers will be coming from inputDecoration of each TextField and the value will be from currentLine variable. curentLine++ also ran inside onEditingComplete.

Upvotes: 1

Mohammad Shamsi
Mohammad Shamsi

Reputation: 571

you can use TextSelection()

TextSelection selection = TextSelection(baseOffset: 0, extentOffset: text.length);
List<TextBox> boxes = textPainter.getBoxesForSelection(selection);
int numberOfLines = boxes.length;

get numberOfLines in your Text, count, and show for each line.

Upvotes: 0

rgisi
rgisi

Reputation: 942

Check out this article about LineMetrics.

As you can see, this gives you a list of metadata concerning your rendered text lines. Using the line numbers and the hardBreak attribute together, you can compute the line numbers to display in the left hand column.

Upvotes: 0

Related Questions