Align hint text in multiline TextField in Flutter

2,551

Solution 1

This is an ugly solution, but it works. Other solutions (e.g., setting the textAlignVertical to TextAlignVertical.center) don't work since the maxLines is not null.

Add a TextStyle to the hintText and set the height of the TextStyle to 2.8. You need to reduce this when the fontSize is bigger because the height will be multiplied by the fontSize to make the line height. I added a contentPadding to make sure the text doesn't overflow(because now the text begins from the center of the TextField).

TextField(
                    maxLines: 3,
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.symmetric(vertical: 30),
                      hintText: 'Bio',
                      hintStyle: TextStyle(
                        height: 2.8,
                      ),
                      prefixIcon: Icon(Icons.chrome_reader_mode),
                      fillColor: Colors.grey[200],
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10.0),
                        borderSide: BorderSide(),
                      ),
                    ),
                  ),

Result:

res

Solution 2

Although in your particular case problem can be solved by adding a newline character (hintText: '\nBio'), a better solution is to use labelText property instead of a hintText. By default label is aligned with the center of the TextField.

      TextField(
        maxLines: 3,
        decoration: InputDecoration(
          labelText: 'Bio',
          prefixIcon: Icon(Icons.chrome_reader_mode),
          fillColor: Colors.grey[200],
          filled: true,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
            borderSide: BorderSide(),
          ),
        ),
      ),
   
Share:
2,551
Rishav Kumar
Author by

Rishav Kumar

Updated on December 23, 2022

Comments

  • Rishav Kumar
    Rishav Kumar over 1 year

    I have a multiline TextField with a prefixIcon, so now the Icon is in the center vertically and hint text is at top left. I want both of them to be aligned, either at the top or in the center vertically.

    The code used is

        Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10.0),
              child: TextField(
                maxLines: 3,
                decoration: InputDecoration(
                  hintText: 'Bio',
                  prefixIcon: Icon(Icons.chrome_reader_mode),
                  fillColor: Colors.grey[200],
                  filled: true,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(),
                  ),
                ),
              ),
            ),