I have a Card widget with TextFormField as a child. I want to increase the height of the card each time a user gets to a new line. The card is wrapped in a Container and I have a height variable to determine the height.

How can I detect new line in TextFormField? Also whenever the text wraps to the next line.


Solution 1: DAVE chintan

I think you need to create a function to check the TextFormField specific line.

I think this an be useful for you "https://stackoverflow.com/questions/45900387/multi-line-textfield-in-flutter"


Solution 2: Aditi Mohan

To update height without pressing enter:

onChanged: (String e) {
    int sizeIncreaseConstant = 30; //the fontSize 20 + buffer
    int widthOfCharacter = 17; // 85% of fontsize
    int newNumLines = ((e.length * widthOfCharacter)/widthOfContainer).truncate();
    if( newNumLines != numLines) {
        setState(() {
            if(newNumLines > numLines) 
                heightOfContainer = heightOfContainer + sizeIncreaseConstant;
            else
                heightOfContainer = heightOfContainer - sizeIncreaseConstant;
            numLines = newNumLines;
        });
    }
},

initial values:

int numLines = 0;
double widthOfContainer = 120;
double heightOfContainer = 50;
//fontSize = 20;

For this, you will have to use a font that has equal width for all characters like Monospace. And you will also need to determine the width of the character based on fontSize. It is supposed to be 50-60% of the font size but 85% worked for me.