skip to Main Content

How do I change the color of the icon when pressing the button so that it remains in its new color and does not change after the second press or exiting the application.

Example:

enter image description here

3

Answers


  1. Save state of button in local data and use this data when create UI for color of button. There are ways to save and read data in Flutter,

    There are a few options:

    Login or Signup to reply.
  2. You can do it in several ways: Using StatefulWidget, Bloc, Provider, ValueListenable, etc. The most simple way is a StatefulWidget. You have to save the current state of the button on a variable on the widget state, and you call the method setState() on the onPressed parameter on the Button widget. So, on the Icon widget, you choose the color based on the button state.
    The widget state should looks something like this:

    ...
    class _SampleWidgetState extends State<SampleWidget> {
      bool _buttonIsPressed = false;
      @override
      Widget build(BuildContext context) {
        return MaterialButton(
            child: Icon(
                Icons.remove_red_eye_rounded,
                color: _buttonIsPressed? Colors.blueAccent : Colors.white
            ),
            onPressed: (){
                setState(() {
                  _buttonIsPressed = !_buttonIsPressed;
                });
            }
        );
      }
    }
    

    But, remember, my friend. Try to use logic as little as posible on the user interface. Just little things like colors and so on.

    Login or Signup to reply.
  3. Use ValueNotifier for notifying color of the button.

    ValueNotifier<Set<int>> colorButton = ValueNotifier([]);
    

    inside code

    ValueListenableBuilder(
      valueListenable: colorButton,
      builder: (BuildContext context, Set<int> colorButtonValue, _) {       
        if (colorButtonValue.isNotEmpty) {
          return GestureDetector(
            onTap: () {
              colorButton.value.remove(idIndex);
              colorButton.notifyListeners();
            },
            child: IconButton(
              icon: Icons.emoji_emotions,                             
              color: whiteColor
            ),
          );
        } else {
          return GestureDetector(
            onTap: () {
              colorButton.value.add(idIndex);
              colorButton.notifyListeners();
            },
            child: IconButton(
              icon: Icons.emoji_emotions,                         
              color: redColor,
            ),
          );
        }
      },
    ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search