Change prefix icon color of text form field in flutter on clicking the field

Viewed 21

I have a name form field in flutter app. There's a prefix icon in it. When I click the form field the color of icon changes to blue, rather I want to change it to green. How can I do that, can anyone please guide me? This is its code :


 TextFormField(
      decoration: InputDecoration(
        focusedBorder: OutlineInputBorder(
          borderSide: const BorderSide(color: Colors.green, width: 2.0),
          borderRadius: BorderRadius.circular(10.0),
        ),
        prefixIcon: const Icon(Icons.person),
       
        hintText: "Name",
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
      ),
    );
2 Answers

Use Theme color to change then define the focus node to determine when the field is on focus in order to apply these color changes

... 
  FocusNode _fieldNode = FocusNode(); //<-Define this then
...
TextFormField(
      decoration: InputDecoration(
        focusedBorder: OutlineInputBorder(
          borderSide: const BorderSide(color: Colors.green, width: 2.0),
          borderRadius: BorderRadius.circular(10.0),
        ),
        prefixIcon: Icon(Icons.person,
            color: _fieldNode.hasFocus
                ? Theme.of(context).primaryColor
                : Colors.purple)),
       
        hintText: "Name",
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
      ),
    );

Flutter's way to go is to use resolveWith. You can checkthe current state to check if the text field is focused, shows an error, etc. And depending on that you set the color.

From the docs (https://api.flutter.dev/flutter/material/InputDecoration-class.html):

final ThemeData themeData = Theme.of(context);
    return Theme(
      data: themeData.copyWith(
          inputDecorationTheme: themeData.inputDecorationTheme.copyWith(
        prefixIconColor:
            MaterialStateColor.resolveWith((Set<MaterialState> states) {
          if (states.contains(MaterialState.focused)) {
            return Colors.green;
          }
          if (states.contains(MaterialState.error)) {
            return Colors.red;
          }
          return Colors.grey;
        }),
      )),
      child: TextFormField(
        initialValue: 'abc',
        decoration: const InputDecoration(
          prefixIcon: Icon(Icons.person),
        ),
      ),
    );
Related