Home > Blockchain >  Textformfield focus change in other widgets on instant
Textformfield focus change in other widgets on instant

Time:12-22

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,
          ),
)

CodePudding user response:

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,
          ),
)

CodePudding user response:

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,
              ),
          );
       },
   ),
  • Related