[英]How to change the user entered text color in TextformField
我想在用戶輸入內容時更改文本的顏色。 但是只有當用戶輸入一些東西時。 否則,它應該保持相同的灰色。 為此,我在組件內創建了一個焦點節點並將其分配給 textformfield focusNode
屬性。 在initState
,我添加了一個偵聽器,因此每當我的 textformfield 具有焦點時,我都可以更改提示文本的顏色以及邊框顏色。 但這給了我一個錯誤,我無法更改用戶輸入文本的顏色。
FocusNode _focusNode = FocusNode();
@override
void initState() {
_focusNode.addListener(() {
setState(() => color = _focusNode.hasFocus ? Colors.blue : Colors.grey);
});
super.initState();
}
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
我的組件如下所示:
return Container(
height: MediaQuery.of(context).size.height * 0.06,
child: Material(
elevation: 5.0,
borderRadius: BorderRadius.all(
Radius.circular(30.0),
),
child: TextFormField(
controller: textController,
focusNode: _focusNode,
onTap: _requestFocus,
keyboardType: this.widget.type,
textAlignVertical: TextAlignVertical.bottom,
onChanged: (value) => {
setState(() {
_color = Colors.blue;
})
},
style: TextStyle(
color: color,
fontWeight: FontWeight.w400,
fontSize: 15.0,
),
obscureText: widget.obscureText,
decoration: InputDecoration(
filled: true,
fillColor: Color(0xFFFCFCFC),
hintText: this.widget.hintText,
isDense: true,
contentPadding: EdgeInsets.all(40.0),
hintStyle: TextStyle(
color: _focusNode.hasFocus ? Colors.blue : Colors.grey,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(50.0),
),
borderSide: const BorderSide(color: Colors.white, width: 0.0),
),
prefixIcon: Icon(
this.widget.icon,
color: Colors.grey,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(50.0)),
borderSide: BorderSide(
color: Colors.blue,
),
),
),
validator: (String value) {
return;
},
),
),
);
我無法確定我做錯了什么。
編輯:我在initSate
和onChanged
屬性中移動了焦點節點的初始化,我在setState
中將顏色設置為灰色。 但仍然給出錯誤Failed assertion: line 742 pos 12: 'attached': is not true.
我通過進行這些更改解決了這個問題:
void _requestFocus() {
setState(() {
FocusScope.of(context).unfocus();
FocusScope.of(context).requestFocus(_focusNode);
});
}
刪除 onChanged 回調並將文本字段設置為藍色。 而已。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.