Flutter: use SVG as a Button and change color onPressed state

I want to create an icon button from an SVG. The icon, i.e. the SVG hast to change its color, when the button is in pressed state.

What I have is this:

TextButton(
   style: (disabled) ? iconButtonStyleDisabled : iconButtonStyle,
   onPressed: (!disabled) ? _onPressed : null,
   child: SvgPicture.asset(iconPath, ...));

Unfortunately SvgPicture doesn't care about the TextButtons state, so it won't change it's color. Nevertheless, it works like a charm with an Icon() as a child so my styles are working as intended.

I tried FlutterIcon.com, but when uploading my SVGs they get scrapped, so this won't work either. Maybe I can switch the whole SVG-child of the TextButton depending on it's state?

Any ideas?

Here's my iconButtonStyle which works fine with simple TextButtons and Icon as a child:

ButtonStyle get iconButtonStyle => ButtonStyle(
  shape: MaterialStateProperty.all<BeveledRectangleBorder>(const BeveledRectangleBorder()),
  foregroundColor: getColor(defaultColor: green_medium, pressedColor: context.theme.contentPrimary!), // TextColor
  iconColor: getColor(defaultColor: green_medium, pressedColor: context.theme.contentPrimary!), // TextColor
  backgroundColor: MaterialStateProperty.all(Colors.transparent),
  surfaceTintColor: getColor(defaultColor: green_medium, pressedColor: context.theme.contentPrimary!), // TextColor
  overlayColor: MaterialStateProperty.all(Colors.transparent));

MaterialStateProperty<Color> getColor({required Color defaultColor, required Color pressedColor}) {
getColor(Set<MaterialState> states) {
  if (states.contains(MaterialState.pressed)) {
    return pressedColor;
  }
  return defaultColor;
}

return MaterialStateProperty.resolveWith(getColor);
}


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation