Home > Software design >  How to change textfield background color on focus
How to change textfield background color on focus

Time:03-10

I need to change textfield background color grey to white when user tap on textfiled. Focused textfield's background color should change grey to white and other un focused textfield background color stay remain grey.

i tried this

inputDecorationTheme: InputDecorationTheme(
        filled: true,
        fillColor: AppColors.textFieldBG,
        focusColor: AppColors.white,
        hintStyle: const TextStyle(color: AppColors.labelText, fontSize: 16),
        contentPadding:
            const EdgeInsets.symmetric(horizontal: 10, vertical: 20),

        focusedBorder: OutlineInputBorder(
            borderSide: const BorderSide(color: Colors.black26),
            borderRadius: BorderRadius.circular(10)),
        disabledBorder: OutlineInputBorder(
            borderSide: const BorderSide(color: Colors.transparent),
            borderRadius: BorderRadius.circular(10)),
        enabledBorder: UnderlineInputBorder(
          borderSide: const BorderSide(color: Colors.transparent),
          borderRadius: BorderRadius.circular(10),
        ),  

Here is text-filed code:

    TextField(
              focusNode: focusNode,
              onChanged: onChanged,
              controller: controller,
              maxLines: maxLines,
              onTap: onTap,
              enabled: isEnable,
              decoration: InputDecoration(
                  filled: true,
                  fillColor: AppColors.textFieldBG,
                  focusColor: AppColors.white,
                  hintText: hintText,
                  suffixIcon: isShowSuffixIcon
                      ? InkWell(
                          onTap: onTapIcon,
                          child: const Icon(
                            Icons.date_range_outlined,
                            color: AppColors.labelText,
                          ),
                        )
                      : null),
            ),

CodePudding user response:

You can do something like this:

FocusNode _focusNode = FocusNode();
Color _color = Colors.grey;
@override
void initState() {
  _focusNode.addListener(() {
    if(_focusNode.hasFocus){
      setState(() {
        _color = Colors.white;
      });
    }
    else{
      setState(() {
        _color = Colors.grey;
      });
    }
  });
}
TextField(
  decoration: InputDecoration(
    fillColor: _color,
    filled: true
  ),
  focusNode: _focusNode,
),

CodePudding user response:

You just need to use a Focus node for the TextField

Just follow along this documentation you will get to know more about the possibilities you can get with using the Focus Node for textFormField or textField.

  • Related