简体   繁体   中英

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

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)),
      ),
    );

Use Theme since this is probably controlled by your app primary color: wrap with Theme() widget

Theme(
   data: Theme.of(context).copyWith(
   primaryColor: Color()
    ), 
   child: TextField())

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),
        ),
      ),
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM