wiradikusuma
wiradikusuma

Reputation: 1919

Flutter TextField, how to use different style for label inside vs above the text field

I have the following TextField:

TextField(
    decoration: InputDecoration(
        labelStyle: TextStyle(
            color: I_WANT_TO_CHANGE_THIS,
        ),
        labelText: widget.label,
    ),
);

How do I change the color so that when it's inside the text field (a hint), it's GRAY, and when it's floating above the text field (being focused), it's BLACK.

Upvotes: 8

Views: 25139

Answers (1)

Noodles
Noodles

Reputation: 4080

Try using a FocusNode:

class _MyHomePageState extends State<MyHomePage> {

  FocusNode _focusNode = FocusNode();
  Color color;

  @override
  Widget build(BuildContext context) {

    _focusNode.addListener(() {
      setState(() {
       color = _focusNode.hasFocus ? Colors.blue : Colors.red; 
      });
    });

    return Scaffold(
      body: Center(
        child: TextField(
          focusNode: _focusNode,
          decoration: InputDecoration(
            labelText: 'Label',
            labelStyle: TextStyle(
              color: _focusNode.hasFocus ? Colors.blue : Colors.red,
            )
          ),
          autofocus: false,
        ),
      )
    );
  }
}

Notice that in this particular example the textfield will always be in focus once selected, since there's only one textfield.

Upvotes: 9

Related Questions