Flutter align hint text to center vertically and horizontally in SearchBar Widget when height is less than default

287 Views Asked by At

I am trying to create a search bar in my app which includes a hint text in it. However my output of it looks weird where the hint text is not align to the center vertically on the SearchBar. The img and block below is my output and my code:

img

SearchBar(
  hintText: 'Search Employee',
  hintStyle: MaterialStateProperty.all(const TextStyle(color: Color(0xFFA1A5C0), fontSize: 11)),
  constraints: const BoxConstraints(minHeight: 28),
  leading: const Icon(Icons.search, size: 15),
  elevation: const MaterialStatePropertyAll(0),
  side: MaterialStateProperty.all(const BorderSide(color: Color.fromRGBO(1, 1, 1, 0.1))),
  shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(40))),
)
2

There are 2 best solutions below

0
amir_a14 On BEST ANSWER

This was known bug and flutter team fixed this, but it takes time to merge into stable channel, so you can use TextField instead like this:

  TextField(
    decoration: InputDecoration(
      hintText: 'Search Employee',
      hintStyle: const TextStyle(color: Color(0xFFA1A5C0), fontSize: 18),
      border: OutlineInputBorder(
        borderSide: const BorderSide(color: Color.fromRGBO(1, 1, 1, 0.1)),
        borderRadius: BorderRadius.circular(40),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: const BorderSide(color: Color.fromRGBO(1, 1, 1, 0.1)),
        borderRadius: BorderRadius.circular(40),
      ),
      prefixIcon: const Icon(Icons.search, size: 36),
      prefixIconColor: Colors.black,
      constraints: const BoxConstraints(minHeight: 28),
      isDense: true,
      fillColor: Colors.white,
      filled: true,
    ),
  ),
1
Karan Mehta On

You should use custom control like this one :

Container(
                margin: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25),
                    border: Border.all(width: 1)),
                child: TextFormField(
                    style: const TextStyle(fontSize: 12),
                    decoration: const InputDecoration(
                      alignLabelWithHint: true,
                      contentPadding:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                      hintText: "Search Employee",
                      hintStyle:
                          TextStyle(color: Color(0xFFA1A5C0), fontSize: 12),
                      border: InputBorder.none,
                    )),
              ),

Benefits of using something like this are:

  1. Fully customisable UI
  2. You can add controls as per your requirement