skip to Main Content

I want to get the number of lines in a text field. Currently, I am using this method:

 TextField(
                  scrollPadding: EdgeInsets.zero,
                  controller: textEditingController,
                  onChanged: (value) {
                    setState(() {
                      lineLength = 'n'.allMatches(value).length + 1;
                    });
                  },
                  maxLines: null,
                  textAlign: TextAlign.center,
                  keyboardType: TextInputType.multiline,
                  style: TextStyle(
                    height: fontHeight,
                    fontSize: fontSize,
                    color: Colors.white,
                  ),
                  decoration: const InputDecoration(
                    contentPadding: EdgeInsets.zero,
                    border: InputBorder.none,
                    hintText: 'Text...',
                  ),
                ),

However, the problem with this approach is that the user must press "enter" for a new line to be counted. I want when the width of the text field is limited and the text field wraps, the next line should also be considered as a new line.

2

Answers


  1. Kindly replace the following regular expression. This method is capable of handling various line break formats. I trust that it will prove to be beneficial.

    setState(() {
          lineLength = value.split(RegExp(r'r?n')).length;
        });
    
    Login or Signup to reply.
  2. Replace your on changed function with this :-

    lineLength = '\n'.allMatches(value).length + 1
    

    This will count n as a string character.
    Hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search