Search code examples
flutterflutter-textformfield

Flutter - change TextFormField background when in active mode (Typing)


I want to achieve this.

enter image description here

While a text form field is inactive, its background, fill color will be grey. But when I am typing or it is in active mode, its background color will be white.

How to achieve this behavior?


Solution

  • After going through some tests, I have finalized the correct answer. The above answer is good. The first one has a problem. Focus Node variable must be inside the state class so that it can preserve its state.

    class _GlobalTextFormFieldState extends State<GlobalTextFormField> {
      late FocusNode focusNode;
    
      @override
      void initState() {
        focusNode = FocusNode();
        focusNode.addListener(() {
          setState(() {});
        });
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return TextFormField(
          focusNode: focusNode,
        );
      }
    }