[英]Change background color on TextField when focused
我有一个包含很多输入字段的表单。 当 TextField 具有焦点时,我想更改背景颜色:
这是我的文本字段:
TextFormField(
focusNode: _textFieldFocus,
decoration: InputDecoration(
labelText: 'Input test',
filled: true,
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 3),
),
),
),
我已经搜索了一段时间来寻找解决方案,但似乎您必须将 TextField 包装在使用 FocusNode 的有状态小部件中。 在这篇文章中看到了一个例子: 焦点时如何更改 TextFiled 小部件背景颜色
我不太热衷于这个解决方案,因为我有很多文本字段,我认为没有必要为我拥有的每个“哑”文本输入创建有状态实例。 如果有 focusBackgroundColor 属性或类似属性,我会更喜欢。 那么有没有比将 TextField 包装在有状态小部件中更简单的解决方案?
在FocusNode
上添加一个侦听器以使用setState
进行 UI 更新。 要改变颜色,我们可以使用fillColor: _textFieldFocus.hasFocus? Colors.purple: null
fillColor: _textFieldFocus.hasFocus? Colors.purple: null
,修改你想要的颜色。
late final _textFieldFocus = FocusNode()
..addListener(() {
setState(() {});
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
TextFormField(
focusNode: _textFieldFocus,
decoration: InputDecoration(
fillColor: _textFieldFocus.hasFocus ? Colors.purple : null,
labelText: 'Input test',
filled: true,
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 3),
),
),
),
],
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.