Home > OS >  ForegroundColor in button style doesn't change the icon color
ForegroundColor in button style doesn't change the icon color

Time:11-30

I need to customize my button style when it is disabled and enabled, I use this code to change text color in my button:

ButtonStyle(
   textStyle: MaterialStateProperty.resolveWith(
    (state) {
      if (state.contains(MaterialState.disabled)) {
        return Theme.of(context).textTheme.headline6?.copyWith(
            foreground: Paint()
              ..color = DisabledAlertTextColor.light);
      } else {
        return Theme.of(context).textTheme.headline6?.copyWith(
            foreground: Paint()
              ..color = AlertColor.light);
      }
    },
  ),
);

but I need to change the icon color from style too, but I don't find any solution even by changing foreground color.

This is my button and I have to change the icon color to grey as an example.

enter image description here

CodePudding user response:

just return color for example:

Color getColor(Set<MaterialState> states) {
      const Set<MaterialState> interactiveStates = <MaterialState>{
        MaterialState.pressed,
        MaterialState.hovered,
        MaterialState.focused,
      };
      if (states.any(interactiveStates.contains)) {
        return Colors.blue;
      }
      return Colors.red;
    }

    return TextButton(
      style: ButtonStyle(
        foregroundColor: MaterialStateProperty.resolveWith(getColor),
      ),
      onPressed: () {},
      child: Row(children: const [
        Icon(Icons.delete),
        Text('delete')
      
      ]
       ),
    );
  }

CodePudding user response:

Try this one:

ElevatedButton.icon(
              icon: const Icon(Icons.eleven_mp_rounded),
              onPressed: () {
                setState(() {});
              },
              style: ButtonStyle(
                foregroundColor: MaterialStateProperty.resolveWith<Color>(
                  (Set<MaterialState> states) {
                    if (states.contains(MaterialState.pressed)) {
                      return Theme.of(context).colorScheme.error;
                    } else if (states.contains(MaterialState.disabled)) {
                      return Colors.green;
                    }
                    return Colors.blueGrey; // Use the component's default.
                  },
                ),
              ),
              label: const Text("Button"),
            ),
  • Related