Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change TextField decoration onFocus in Flutter

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

like image 522
eldos Avatar asked Jun 10 '18 17:06

eldos


1 Answers

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;
  }
}
like image 166
petraszd Avatar answered Nov 12 '22 04:11

petraszd