skip to Main Content

I am working on an App Brewery Angela’s course on Flutter, and I have reached the BMI calculator application. Everything was fine until I tried to change the color of the Male and Female cards using Gesture Detector upon tapping the card. The problem is that the color of the card changes only the first time I click it, and when I click it again, it should return to its original color, but it remains colored with the new color.

Here is the code for the card:

Expanded(
  child: GestureDetector(
    onTap: () {
      setState(() {
        updateColour(0);
      });
    },
    child: ReusableCard(
      colour: maleCardColour,
      cardChild: CardContent(
          contentIcon: FontAwesomeIcons.male,
          contentText: 'MALE'
      ),
    ),
  ),
),

And here is the code for changing the color:

void updateColour(int gender) {
  if (gender == 1) {
    if (maleCardColour == inactiveCardColour) {
      maleCardColour = activeCardColor;
      print("male pressed");
    } else {
      maleCardColour = inactiveCardColour;
      print(maleCardColour);
    }
  }
  if (gender == 0) {
    if (femaleCardColour == inactiveCardColour) {
      femaleCardColour = activeCardColor;
      print("female pressed");
    } else {
      femaleCardColour == inactiveCardColour;
    }
  }
}

Can you please help me solve this issue I have been at it for almost three days now.

I tried changing the colors from hex code to material colors and it did not work.
I tried making the colors change inside the setState() within the Gesture Detection code and it still did not work.
I tried to create an enum that changes based on gender selection and changed the logic in the updatecolor function to change the color based on the value of the enum. Also did not work.

I am expecting for the card to change the color from inactive to active when I tap the card. And change back to inactive color when tapped again.

2

Answers


  1. Whenever the maleCardColour variable is updated, you should call setState((){}) for the ReusableCard widget to rebuild.

    Login or Signup to reply.
  2. First of all, you used the maleCardColour variable on the card to reflect the color but when you updateColor with gender 0, it is updating another variable value femaleCardColour instead of maleCardColour so you need to call updateColor(1) instead of updateColor(0)

    Secondly, you also have an issue in the femaleCardColor else condition, there should be an assignment operator instead of a comparison operator.

    femaleCardColour = inactiveCardColour;

    Btw another suggestion, you achieve this by using the simple flag logic as card selected or not instead of assigning the color again and tackling it as genders.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search