Home > Enterprise >  Flutter: vertically center TextField in a Container?
Flutter: vertically center TextField in a Container?

Time:08-07

As you can see on the picture the text is sticked to the top of the container. I would prefer if it would be in the center of it...

enter image description here

This is my code:

Padding(
      padding: EdgeInsets.symmetric(horizontal: 8),
      child: Container(
        decoration: BoxDecoration(
            border: Border.all(color: Colors.black, width: 1),
            borderRadius: BorderRadius.all(Radius.circular(20)),
            color: Colors.green),
        child: Center(
          child: Padding(
            padding: EdgeInsets.only(left: 20),
            child: TextField(
              textAlignVertical: TextAlignVertical.bottom,
              textAlign: TextAlign.start,
              cursorColor: Colors.black,
              maxLength: 1,
              decoration: new InputDecoration.collapsed(hintText: ""),
              keyboardType: TextInputType.text,
              autocorrect: false,
              maxLines: 1,
              enableSuggestions: false,
              style: TextStyle(
                color: Colors.white,
                fontSize: 24,
              ),
            ),
          ),
        ),
      ),
    );

I want the text in the center (sorry for my paint skill):

enter image description here

Also I would like to set a padding to the letter counter in the right bottom corner if it is possible?

Thanks in advance.

CodePudding user response:

The issue raise from decoration: InputDecoration.collapsed(), the TextField and counter is talking the space and positioning the text like that. You can use counterText: "", inside InputDecoration.

Container(
  decoration: BoxDecoration(
      border: Border.all(color: Colors.black, width: 1),
      borderRadius: BorderRadius.all(Radius.circular(20)),
      color: Colors.green),
  child: TextField(
    controller: TextEditingController()..text = "A",
    textAlignVertical: TextAlignVertical.center,
    textAlign: TextAlign.start,
    cursorColor: Colors.black,
    maxLength: 1,
    decoration: InputDecoration(
        counterText: "",
        hintText: "",
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(20)),
        )),
    keyboardType: TextInputType.text,
    autocorrect: false,
    maxLines: 1,
    enableSuggestions: false,
    style: TextStyle(
      color: Colors.white,
      fontSize: 24,
    ),
  ),
),

Add the padding and others decoration if needed

enter image description here

  • Related