首页 > 解决方案 > Flutter:如何通过 ThemeData 更改 TextFormField prefixIcon 不聚焦颜色?

问题描述

Flutter:我可以通过设置 Theme.accentColor 来更改 TextFormField 的 prefixIcon 焦点颜色,但是在没有焦点时找不到任何方法来更改 prefixIcon 颜色。

标签: flutterdart

解决方案


Use FocusNode Class, this will keep a track of when you have the focus on that particular TextFormField.

Note: Make sure you assign different FocusNode object to different TextFormField() if you have multiple class.

Here is your solution:

FocusNode _focusNode;

@override
void dispose() {
  super.dispose();
  _focusNode.dispose();
}

@override
void initState() {
  super.initState();
  _focusNode = new FocusNode();
  _focusNode.addListener(_onOnFocusNodeEvent);
}

_onOnFocusNodeEvent() {
  setState(() {
    // Re-renders
  });
}

TextFormField(
  focusNode: _focusNode
  decoration: InputDecoration(
     border: InputBorder.none,
     prefixIcon: Padding(
       padding: EdgeInsets.all(0.0),
       child: Icon(
         Icons.search,
         color: this.getPrefixIconColor(),
       ) // icon is 48px widget.
     )
   )
)

//This will change the color of the icon based upon the focus on the field
Color getPrefixIconColor(){
  return _focusNode.hasFocus ? Colors.black : Colors.grey
}

Let me know if that helps. Thanks


推荐阅读