在Flutter中更改TextField焦点时的装饰。

7
我希望在TextField获得焦点时,填充颜色使用不同的颜色,在正常状态下使用另一种颜色。如何实现这样的效果?
同样地,是否可以根据TextField的状态自定义其他样式呢?
编辑:
我想为移动应用程序中的Flutter实现类似于以下搜索栏过渡效果的颜色过渡: Searchbar transition

分配自定义的focusManager,然后根据焦点变化进行操作。 - Tree
你可以按照这里提到的方式使用ThemeData来设置OutlineInputBorder的样式:https://stackoverflow.com/questions/50622399/how-to-style-the-outlineinputborder-of-inputdecoration - Krzysztof Skrzynecki
@KrzysztofSkrzynecki 我知道像轮廓边框颜色这样的特定属性可以通过ThemeData进行配置,因为InputDecorator会检查 isFocused 状态。但是对于像 fillColor 这样的属性不是这种情况。 - eldos
1个回答

17
你可以将自己的FocusNode对象传递给文本字段的focusNode属性。 FocusNode具有addListener方法,在其中您可以调用setState,从而重新呈现小部件。
class _ChangingColorsExampleState extends State<ChangingColorsPage> {
  FocusNode _focusNode;

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

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

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

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        backgroundColor: _getAppBarBackgroundColor(),
        title: new Text('Changing Colors'),
      ),
      body: new Container(
        color: _getContainerBackgroundColor(),
        padding: new EdgeInsets.all(40.0),
        child: new TextField(
          style: new TextStyle(color: _getInputTextColor()),
          focusNode: _focusNode,
        )
      ),
    );
  }

  Color _getContainerBackgroundColor() {
    return _focusNode.hasFocus ? Colors.blueGrey : Colors.white;
  }

  Color _getAppBarBackgroundColor() {
    return _focusNode.hasFocus ? Colors.green : Colors.red;
  }

  Color _getInputTextColor() {
    return _focusNode.hasFocus ? Colors.white : Colors.pink;
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接