'How do I darken one container in a GestureDetector when I have multiple buttons created with a Widget constructor in Flutter Dart
So I have a piece of code where I need to add multiple buttons to the same page. I am using a GestureDetector since I don't like the onPress animation for the actual buttons.
I wish to darken the color when it's touched. The way it happens doesn't really matter, as long as I don't have to add different variables for every button I add. My current code is using a single variable for each of the buttons, which, needless to say, changes all the buttons when the variable is updated.
GestureDetector(
onTap: () {
// Funtion to change color of PageButton child
setState(() {
colorTapped = !colorTapped;
});
},
child: PageButton(
text: 'BUTTON 1',
color: colorTapped,
),
),
SizedBox(
height: 10,
),
GestureDetector(
onTap: () {
// Funtion to change color of PageButton child
setState(() {
colorTapped = !colorTapped;
});
},
child: PageButton(
text: 'BUTTON 2',
color: colorTapped,
),
),
PageButton widget:
class PageButton extends StatelessWidget {
PageButton(
{required this.text, this.width, this.height, required this.color});
final String text;
bool color;
// final IconData icon;
final double? width;
final double? height;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: color ? Color(0x66DE4B4D) : Color(0xFFEF4B4D),
),
child: Center(
child: Text(
text,
style: kLargeButtonTextStyle,
),
),
width: width ?? MediaQuery.of(context).size.width * 0.9,
height: height ?? 50.0,
padding: EdgeInsets.fromLTRB(30.0, 5.0, 10.0, 5.0),
);
}
}
Long story short: I want to change the color of the child Widget onTap without having to create a variable each time I add a button
Solution 1:[1]
I think you should use the approach described by flutter documentation to animate the properties of a container: you have to modify the instance properties based on the GestureDetector onTap property.
This means:
- you have to make it a stateful widget, in order to allow it to change
- use its instance variables to change separately every single button's property
Here's the link: Flutter Documentation: Animate the properties of a container
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sachax |
