Pradeep Kumar
Pradeep Kumar

Reputation: 43

How to change TextField's textLable color on focus

What should I add in my code to achieve TextField's textLable color as Green on focus.

 TextField(
  keyboardType: TextInputType.emailAddress,
  cursorColor: CustomColors.seaweed,
  keyboardAppearance: Brightness.light,
  autocorrect: false,
  style: TextStyle(
      color: Colors.black
  ),
  decoration: InputDecoration(
    fillColor: CustomColors.seaweed,
    hasFloatingPlaceholder: true,
    labelText: "Email",
    hintText: "Please enter email",
    focusedBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: CustomColors.seaweed)
    ),

  ),

)

enter image description here

Upvotes: 4

Views: 941

Answers (1)

Hugo Passos
Hugo Passos

Reputation: 8427

Create a FocusNode and add a listener to it. When it's focused, change the label color to green.

class Foo extends StatefulWidget {
  @override
  createState() => _FooState();
}

class _FooState extends State<Foo> {
  final FocusNode focusNode = FocusNode();

  TextStyle labelStyle;

  @override
  void initState() {
    super.initState();
    focusNode.addListener(onFocusChange);
  }

  void onFocusChange() {
    setState(() {
      labelStyle = focusNode.hasFocus ? TextStyle(color: Colors.green) : null;
    });
  }

  @override
  void dispose() {
    focusNode.removeListener(onFocusChange);
    super.dispose();
  }

  ...

  TextField buildTextField() {
    return TextField(
      focusNode: focusNode,
      decoration: InputDecoration(
        labelStyle: labelStyle,
        ...
      ),
      ...
    );
  }
}

Upvotes: 2

Related Questions