Home > Software engineering >  Change colour of widget depending on index/variable
Change colour of widget depending on index/variable

Time:10-12

I have a custom BottomNav bar and successfully changing the background colour depending on the selectedIndex. I'm doing this via a ternary statement:

backgroundColor: selectedIndex == 0
      ? const Color.fromARGB(255, 0, 52, 35)
      : const Color.fromARGB(255, 0, 13, 52),

Now I've added a 3rd screen, I want to set up an if statement along these lines:

backgroundColor: 
      if (selectedIndex == 0)
      {const Color.fromARGB(255, 0, 52, 35);}
      if (selectedIndex == 1)
      {const Color.fromARGB(255, 0, 13, 52);}
      if (selectedIndex == 2)
      {const Color.fromARGB(255, 87, 0, 54);},

It may just be a simple syntax issue - I'm new to Flutter.

CodePudding user response:

You can create a separate method with switch.

Color getColor(int selectedIndex) {
  switch (selectedIndex) {
    case 0:
      return const Color.fromARGB(255, 0, 52, 35);

    case 1:
      return const Color.fromARGB(255, 0, 13, 52);

    case 2:
      return const Color.fromARGB(255, 87, 0, 54);

    default:
      return Colors.green;
  }
}

And use

backgroundColor: getColor(selectedIndex),

More about switch-and-case

CodePudding user response:

You can define a function like this:

Color getBackgroundColor(int selectedIndex){
   if (selectedIndex == 0){
      return const Color.fromARGB(255, 0, 52, 35);
   }else if (selectedIndex == 1){
      return const Color.fromARGB(255, 0, 13, 52);
   }else {
      return const Color.fromARGB(255, 87, 0, 54);
   }
}

and use it like this:

backgroundColor: getBackgroundColor(selectedIndex),

CodePudding user response:

You can actually nest ternary expressions to get what you want, like:

backgroundColor: selectedIndex == 0
  ? const Color.fromARGB(255, 0, 52, 35)
  : selectedIndex == 1
    ? const Color.fromARGB(255, 0, 13, 52)
    : const Color.fromARGB(255, 87, 0, 54),

Although I'd recommend Yeasin Sheikh's answer more, especially if you want to add even more indexes

  • Related