Change TextField decoration onFocus in Flutter
Asked Answered
D

1

7

I would like to have a different fillColor for the TextField when it is in the focused state and a different one in the normal state. How to achieve this kind of behavior?

Similarly, is it possible to customize other styles as well based on the state of the TextField?

Edit:

I was aiming for a color transition something in lines of this for mobile with flutter.

Searchbar transition

Deakin answered 10/6, 2018 at 17:15 Comment(3)
assing custom focusManager, and than act based on change of focus.Taproot
or you can use ThemeData as mentioned here: #50622899Charlatanry
@KrzysztofSkrzynecki I know that certain properties like outline border color are configurable via ThemeData as InputDecorator checks isFocused state. But that is not the case with properties like fillColorDeakin
R
17

You can pass your own FocusNode object to your text field's focusNode attribute. FocusNode has addListener method in which you can call setState and thus re-render your widget.

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;
  }
}
Remscheid answered 11/6, 2018 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.