Flutter - 在活动模式下更改 TextFormField 背景(打字)

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

我想实现这个。

当文本表单域处于非活动状态时,其背景和填充颜色将为灰色。但是当我打字或者它处于活动模式时,它的背景颜色会是白色。

如何实现这种行为?

您可以将 FocusNode 与侦听器一起使用。

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

试试这个:

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

经过一些测试,我确定了正确答案。上面的回答很好。第一个有问题。 焦点节点变量必须在状态 class 内,以便它可以保存其状态

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