I'm trying to dynamically change the color of a button in a list of buttons, meaning that if one of the three buttons is pressed, the other two should change to the default color. With my current setup the button that has been pressed changes colors, but the inactive buttons don't return to the original state, which makes the impression that all buttons are active. Thanks for your help!
This is the parent container that uses the array to render the buttons:
class Categories extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _Categories();
}
}
class _Categories extends State<Categories> {
int activeCategory = 0;
final titles = ["Experiences", "Adventures", "Activities"];
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: titles.mapIndexed((index, title) => CategoryButton(index, title, activeCategory)).toList()
);
}
}
This is the button:
class CategoryButton extends StatefulWidget {
CategoryButton(this.currentIndex, this.title, this.activeCategory, {Key? key}) : super(key: key);
@override
State<CategoryButton> createState() => _CategoryButtonState();
int currentIndex, activeCategory;
final String title;
}
class _CategoryButtonState extends State<CategoryButton> {
@override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
return InkWell(
onTap: () {
setState(() {
widget.activeCategory = widget.currentIndex;
});
},
child: Container(
height: 38.0,
width: screenWidth * 0.30,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
color: Color(widget.activeCategory == widget.currentIndex ? 0xFF63D1D9 : 0x00FFFFFF)
),
child: Center(
child: Text(
widget.title,
style: const TextStyle(
fontFamily: "Poppins",
fontSize: 15.6,
color: Color(0xFF332418)
)
)
)
)
);
}
}
CodePudding user response:
try to get ontap
function from the Categories state as parameter.use the setState
method in there
CodePudding user response:
So basically, I removed the button from its own separate widget and added it to the categories widget. Here is the new code:
class Categories extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _Categories();
}
}
class _Categories extends State<Categories> {
int activeCategory = 0;
final titles = ["Experiences", "Adventures", "Activities"];
@override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: titles.mapIndexed((index, title) => InkWell(
onTap: () {
setState(() {
activeCategory = index;
});
},
child: Container(
height: 38.0,
width: screenWidth * 0.30,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50.0),
color: Color(activeCategory == index ? 0xFF63D1D9 : 0x00FFFFFF)
),
child: Center(
child: Text(
title,
style: const TextStyle(
fontFamily: "Poppins",
fontSize: 15.6,
color: Color(0xFF332418)
)
)
)
)
)).toList()
);
}
}