I am trying to create a container with a gesture detector that changes color onTap, but for some reason it is not doing so. I have a bool and a function to setstate and change it, and in the backgroundColor of the container I have it changing based on the color of the bool. Any advice would be greatly appreciated.
import 'package:flutter/material.dart';
class VotingButton extends StatefulWidget {
@override
State<VotingButton> createState() => _VotingButtonState();
}
class _VotingButtonState extends State<VotingButton> {
bool savePressed = false;
void buttonPressed() {
setState(() {
if (savePressed == false) {
savePressed == true;
} else if (savePressed == true) {
savePressed == false;
}
});
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 18.0),
child: GestureDetector(
onTap: () {
buttonPressed;
print(savePressed); //stays false for some reason
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: savePressed ? Colors.blue : Colors.red[400],
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 40),
child: Text(
'I'll be Here!',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
),
),
);
}
}
4
Answers
In
GestureDetector
you not callingbuttonPressed
method properlyTry this:
And optimise code by making change into
buttonPressed
methodTry this:
Try this, I change a little bit your buttonPressed method, and GestureDetector onTap. Hope it helps
Try the following code: