Home > OS >  Flutter Textbutton doesn't reset instant
Flutter Textbutton doesn't reset instant

Time:08-03

I was trying to code a TikTakToe game in FLutter but failed at the point where I tried to make a button which resets the fields.

bool gameover = false;

class Field extends StatefulWidget {
  const Field({Key? key, required this.fieldnumber}) : super(key: key);
  final int fieldnumber;

  @override
  State<Field> createState() => _FieldState();
}

class _FieldState extends State<Field> {
  String playersign = "";
  @override
  Widget build(BuildContext context) {
    return TextButton(
      child: Text(
        gameover ? "" : signlist[widget.fieldnumber],
        style: const TextStyle(fontSize: 60),
      ),: const TextStyle(fontSize: 60),
          ),

The button for the reset:

onPressed: () {
    setState(() {
        gameover = true;
    });
},

The buttons reset, but only when I'm clicking on them and not instant as I would like them to do.

I also tried:

setState(() {
     signlist = ["", "", "", "", "", "", "", "", ""];
});

CodePudding user response:

Change gameover variable place into _FieldState class.

class Field extends StatefulWidget {
  const Field({Key? key, required this.fieldnumber}) : super(key: key);
  final int fieldnumber;

  @override
  State<Field> createState() => _FieldState();
}

class _FieldState extends State<Field> {
  String playersign = "";
  bool gameover = false;
  @override
  Widget build(BuildContext context) {
    return TextButton(
      child: Text(
        gameover ? "" : signlist[widget.fieldnumber],
        style: const TextStyle(fontSize: 60),
      ),: const TextStyle(fontSize: 60),
          ),

CodePudding user response:

You need to put gameOver variable inside of Field widget and dont forget to use camelCase in naming variables, on the other hand you have to pass onPressed to TextButton if you dont want to be clickable just pass onPressed: null

class Field extends StatefulWidget {
  const Field({Key key}) : super(key: key);

  @override
  State<Field> createState() => _FieldState();
}

class _FieldState extends State<Field> {
  String playerSign = ""; 
  bool gameOver = false; // put var inside
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextButton(
          onPressed: null,
          child: Text(
            gameOver ? "" : signlist[widget.fieldnumber],
            style: const TextStyle(fontSize: 60),
          ),
        ),
        TextButton(
          onPressed: () {
            setState(() {
              setState(() {
                gameOver = true;
              });
            });
          },
          child: const Text(
            "reset",
            style:  TextStyle(fontSize: 60),
          ),
        ),
      ],
    );
  }
}

result

  • Related