skip to Main Content

Using a textformfield widget, I need to change the color in the background according to the focus and unfocus status, but this change does not change on the screen at the time of focus and unfocus.
Below is a code sample.

Here it is;


FocusNode _focusNode = FocusNode();

Container(
   width: double.infinity,
   color: _focusNode.hasFocus ? Colors.red : Colors.black,
   child: TextFormField(
             focusNode: _focusNode,
          ),
)

2

Answers


  1. try another approach of doing it, by adding a listener on the FocusNode in the StatefullWidget that will change the color based on it:

    First, in you’re State object:

      FocusNode _focusNode = FocusNode();
      Color _color = Colors.red;
    
      @override
      void initState() {
        _focusNode.addListener(
          () {
            if (_focusNode.hasFocus) {
              setState(() {
                _color = Colors.green;
              });
            } else {
              setState(() {
                _color = Colors.red;
              });
            }
          },
        );
        super.initState();
      }
    

    this will listen to the FocusNode, when it has to focus it will update the color to green, otherwise, it’s red.

    Then in the widget:

       Container(
       width: double.infinity,
       color: _color,
       child: TextFormField(
                 focusNode: _focusNode,
              ),
    )
    
    Login or Signup to reply.
  2. You can use ValueNotifier

     ValueNotifier<bool> isFocused = ValueNotifier<bool>(false);
     FocusNode _focusNode = FocusNode();
    
    
    @override
      void initState() {
        super.initState();
        _focusNode.addListener(
          () {
            if (_focusNode.hasFocus) {
              isFocused.value = true;
            } else {
              isFocused.value = false;
            }
          },
        );
      }
    
    //Your Widget
     ValueListenableBuilder(
         valueListenable: isFocused,
         builder: (context, mobile, child) {
              return Container(
                 width: double.infinity,
                 color: isFocused.value ? Colors.red : Colors.blue,
                 child: TextFormField(
                    focusNode: _focusNode,
                  ),
              );
           },
       ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search