1

我想实现这一目标。

在此处输入图像描述

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

如何实现这种行为?

4

3 回答 3

2

试试这个:

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

于 2022-02-01T13:48:51.737 回答
1

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

  late final FocusNode focusNode = FocusNode()
    ..addListener(() {
      setState(() {});
    });
    
 ....
  TextField(
    focusNode: focusNode,
    decoration: InputDecoration(
      fillColor: focusNode.hasFocus ? Colors.white : null,
      filled: focusNode.hasFocus ? true : null,
    ),
  )
于 2022-02-01T13:23:03.603 回答
0

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

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,
    );
  }
}
于 2022-02-09T04:34:42.293 回答