Yohan
Yohan

Reputation: 72

How to emptying hint text when focus in TextFormField Flutter

I want to make the hint text in TextFormField disappear when the field focused. But the hint text won't disappear until I insert a character in the field. I did the following. How can I make the hint text disappear when the field focused? Thanks!

Container buildTextField(bool isObscure, TextEditingController textEditingController, String hintText, bool onlyNumber) {
    return Container(
      width: double.infinity,
      height: 60,
      color: MyColors.primary,
      alignment: Alignment.center,
      child: Padding(
        padding: EdgeInsets.only(left: 15, right: 10),
        child: TextFormField(
          textAlign: TextAlign.center,
          keyboardType: onlyNumber ? TextInputType.number : TextInputType.text,
          decoration: InputDecoration(
            hintText: hintText,
            hintStyle: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.w600,
            ),
            border: InputBorder.none,
          ),
          style: TextStyle(
            color: Colors.white,
            decoration: TextDecoration.none,
            fontWeight: FontWeight.w600,
          ),
          obscureText: isObscure,
          controller: textEditingController,
        ),
      ),
    );
  }

enter image description here

Upvotes: 3

Views: 2314

Answers (2)

alexandreohara
alexandreohara

Reputation: 264

You probably have to add a listener to listen to focus changes:

FocusNode myFocusNode = FocusNode();

myFocusNode.addListener( () {
   setState((){});
}

And then, inside your InputDecoration you update the value:

hintText: myFocusNode.hasFocus ? hintText : ''

Upvotes: 4

Ravinder Kumar
Ravinder Kumar

Reputation: 7990

Use labelText instead,

 TextFormField(
            controller: fullNameController,
            validator: (value) {
              if (value.trim().isEmpty) {
                return Lang.enterFullName;
              }
              return null;
            },
            decoration: InputDecoration(
              labelText: Lang.fullName,
              prefixIcon: Icon(Icons.person),
            ),
            keyboardType: TextInputType.text,
            textInputAction: TextInputAction.next,
          ),

Upvotes: 2

Related Questions