Home > Mobile >  How to change flutter button border color based on MaterialState?
How to change flutter button border color based on MaterialState?

Time:03-18

Is there a way to change the flutter MateriaButton border color (or any other properties) based on the MaterialState?

ButtonStyle(
  backgroundColor: MaterialStateProperty.resolveWith<Color?>((states) => ...),
  overlayColor: MaterialStateProperty.resolveWith<Color?>((states) => ...),
  side: MaterialStateProperty.resolveWith<BorderSide?>((states) => {
    if (states.contains(MaterialState.pressed)) {
      return BorderSide(color: Colors.Blue);
    }
    return BorderSide(color: Colors.Red);
  }),
)

Trying to set the border in this way doesn't seem to have any effect on the side, but it stays always red. Both backgroundColor and overlayColor seem to change based on the state, but the side property doesn't. Is there a way to achieve this?

Edit: Setting the side property this way seems to work after all. Also the way proposed by @nagendra nag works well too. The actual problem seems to be that the animation seems to be slow, so the change isn't visible unless the button is pressed for a short moment.

CodePudding user response:

Try this

shape: MaterialStateProperty.resolveWith(
  (states) {
    if (states.contains(MaterialState.focused)) {
      return const RoundedRectangleBorder(
        side: BorderSide(color: Colors.red),
      );
    }
    if (states.contains(MaterialState.pressed)) {
      return const RoundedRectangleBorder(
        side: BorderSide(color: Colors.green),
      );
    }
    if (states.contains(MaterialState.hovered)) {
      return const RoundedRectangleBorder(
        side: BorderSide(color: Colors.blue),
      );
    }
  },
),
),
  • Related