I am having an issue with the setState and I'm not sure what is the issue.
What I'm trying to do is to update the fields after the click of a button. Please see my code below. The turn indicator that I have implemented works, so the state is updating but the widget inside the custom Board widget is not changing. It only changes when I save the code in IDE, so I guess it is a wrong setState function.
I am expecting that when I click the button and the requirements are met, it will update into one of two images that I have put into files.
I have tried to put setState in the button but it doesn't work
Function in Main:
void changeTurn(Tile tile) {
if (turnController.isThisMyTurn(Turn.playerOneTurn) == true &&
tile.tileMark == TileMark.blank) {
setState(() => tile.setTileContentX());
setState(() => turnController.switchTurn());
}
if (turnController.isThisMyTurn(Turn.playerTwoTurn) == true &&
tile.tileMark == TileMark.blank) {
setState(() => tile.setTileContentO());
setState(() => turnController.switchTurn());
}
}
Tile widget:
class Tile extends StatefulWidget {
@override
State<Tile> createState() => _TileState();
Widget tileContent = Text('');
TileMark tileMark = TileMark.blank;
setTileContentX() {
tileContent = Image.asset('assets/images/X.png');
tileMark = TileMark.X;
}
setTileContentO() {
tileContent = Image.asset('assets/images/O.png');
tileMark = TileMark.O;
}
}
class _TileState extends State<Tile> {
@override
Widget build(BuildContext context) {
return widget.tileContent;
}
}
enum TileMark {
X,
O,
blank,
}
Button that I need to update in the custom Board widget:
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Color.fromARGB(255, 162, 212, 138),
),
onPressed: () {
widget.switchTurn(tile1);
},
child: tile1,
),