Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 933
wiradikusuma Avatar asked Apr 27 '19 16:04

wiradikusuma


People also ask

How do you change the label text style in Flutter?

Here is the step by step instructions: Step 1: Locate the file where you have placed the TextField widget. Step 2: Inside the TextField widget, add the decoration parameter and assign the InputDecoration widget. Step 3: Inside the InputDecoration widget, add the labelStyle parameter and assign the TextStyle widget.

How do you decorate a text box in Flutter?

By default, a TextField is decorated with an underline. You can add a label, icon, inline hint text, and error text by supplying an InputDecoration as the decoration property of the TextField . To remove the decoration entirely (including the underline and the space reserved for the label), set the decoration to null.


1 Answers

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.

like image 178
Noodles Avatar answered Oct 11 '22 00:10

Noodles