Solved: flutter custom height textfield with suffix icon

Question

Asked by Fahim H on January 01, 2022 (source).

How can I create a custom height text field with a suffix icon? Right now the TextField I created has alignment issues, i.e the text and suffix icon is not aligned equally:

  Widget _buildPassInput(BuildContext context) {
    return Container(
      height: 45,
      decoration: BoxDecoration(
        border: Border.all(
          color: CustomColors.primary,
        ),
      ),
      child: Center(
        child: TextField(
          controller: _passController,
          cursorColor: CustomColors.primary,
          textAlignVertical: TextAlignVertical.center,
          style: CustomTexts.search,
          keyboardType: TextInputType.text,
          autofocus: false,
          obscureText: _obscureText,
          decoration: InputDecoration(
            hintText: "Password",
            hintStyle: CustomTexts.search,
            border: InputBorder.none,
            isDense: true,
            contentPadding: EdgeInsets.all(8),
            suffix: InkWell(
              onTap: () {
                setState(() {
                  _obscureText = !_obscureText;
                });
              },
              child: Icon(
                _obscureText ? Icons.visibility : Icons.visibility_off,
                color: CustomColors.primary,
                size: MediaQuery.of(context).size.width * 0.05,
              ),
            ),
          ),
        ),
      ),
    );
  }

The default TextField height was not working for me so I need to create a custom one. The suffix icon is centered but the text is showing a little below center

Answer

Question answered by Ravindra S (source).

Try below code hope its help to you.I have add it prefixIcon also if you dont need then remove prefixIcon code

Refer TextFormField here

Refer InputDecoration here

declare bool variable:

bool obsecureText = true;

Create function for show and hide password:

void showPassword() {
    setState(() {
      obsecureText = !obsecureText;
    });
  }

Your Widget:

TextFormField(
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Password Required';
        }
        return null;
      },
      obscureText: obsecureText,
      decoration: InputDecoration(
        suffixIcon: IconButton(
          onPressed: showPassword,
          icon: Icon(
            obsecureText ? Icons.visibility_off : Icons.visibility,
          ),
        ),
        prefixIcon: Icon(
          Icons.vpn_key,
        ),
        border: OutlineInputBorder(),
        labelText: 'Password',
        hintText: 'Enter Password Here',
      ),
    ),

Your result screen-> enter image description here

FLUTTER
SHARE: