Search code examples
flutterdartflutter-layouttextfield

Align hint text in multiline TextField in Flutter


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(),
              ),
            ),
          ),
        ),

Solution

  • 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