Home > Mobile >  Change color when onPressed in flutter using Provider
Change color when onPressed in flutter using Provider

Time:08-02

How can I change the color using Provider State Management instead of setState()

I have one Button by default color is black then - 1st click color is blue, 2nd click color is red, 3rd click color is green 4th click color is black(by default) or purple how can I do it using Provider

Model:

class DriverStatusState extends ChangeNotifier {
  var numberOfClicks = 0;
  Color buttonColor = Colors.red;

  void changeColor() {
    numberOfClicks  ;
    mapNumerOfClicksToColor(numberOfClicks);
    notifyListeners();
  }

  mapNumerOfClicksToColor(int num) {
    switch (num) {
      case 1:
        {
          buttonColor = Colors.orange;
        }
        break;
      case 2:
        {
          buttonColor = Colors.green;
        }
        break;
      default:
        {
          buttonColor = Colors.red;
        }
        break;
    }
    notifyListeners();
  }
}

Widget:

Consumer<DriverStatusState>(
            builder: (context, state, _) => ElevatedButton(
              child: Text('press me'),
              onPressed: () {
                state.mapNumerOfClicksToColor(0);
                     },
              style: ElevatedButton.styleFrom(primary: state.buttonColor),
            ),
          ),

CodePudding user response:

You need to hold the number of clicks inside a variable, and every time you click the button, you will increment the varibale, and change the color according to the new value.

Assuming you are familiar with Provider, you would do something like this inside your model:

var numberOfClicks = 0;
Color buttonColor = Colors.white;


void changeColor(){
   numberOfClicks  ;
   mapNumerOfClicksToColor(numberOfClicks);
   notifyListeners();
}

mapNumerOfClicksToColor(int num){
  switch(num){
    case 1:
       buttonColor = Colors.Blue;
    case 2:
        ....
    case 3:
        ....
  }
 notifyListeners();
}
  • Related