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

711

Solution 1

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

Solution 2

try this:

class CustomTextFiled extends StatefulWidget {
  const CustomTextFiled({
    Key? key,
    this.focusNode,
    required this.fillColor,
    required this.focusColor,
    // add whaterver properties that your textfield needs. like controller and ..
  }) : super(key: key);

  final FocusNode? focusNode;
  final Color focusColor;
  final Color fillColor;

  @override
  _CustomTextFiledState createState() => _CustomTextFiledState();
}

class _CustomTextFiledState extends State<CustomTextFiled> {
  late FocusNode focusNode;

  @override
  void initState() {
    focusNode = widget.focusNode ?? FocusNode();
    focusNode.addListener(() {
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      focusNode: focusNode,
      decoration: InputDecoration(
        filled: true,
        fillColor: focusNode.hasFocus ? widget.focusColor : widget.fillColor,
      ),
    );
  }
}

Solution 3

You can use FocusNode with listener.

  late final FocusNode focusNode = FocusNode()
    ..addListener(() {
      setState(() {});
    });
    
 ....
  TextField(
    focusNode: focusNode,
    decoration: InputDecoration(
      fillColor: focusNode.hasFocus ? Colors.white : null,
      filled: focusNode.hasFocus ? true : null,
    ),
  )
Share:
711
Shaon
Author by

Shaon

Updated on November 25, 2022

Comments

  • Shaon
    Shaon over 1 year

    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?

  • Shaon
    Shaon over 2 years
    This solution doesn't work for textformfield inside bottom sheet.
  • Shaon
    Shaon over 2 years
    This solution doesn't work for textformfield inside bottom sheet.
  • Yeasin Sheikh
    Yeasin Sheikh over 2 years
    Question doesn't indicate placement on bottom sheet , you need to use StatefulBuilder in that case