我想实现这一目标。
当文本表单字段处于非活动状态时,其背景填充颜色将为灰色。但是当我打字或它处于活动模式时,它的背景颜色将是白色的。
如何实现这种行为?
试试这个:
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,
),
);
}
}
您可以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 _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,
);
}
}