[英]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.