Home > Software engineering >  How to call a function when a button is clicked 10 times in flutter?
How to call a function when a button is clicked 10 times in flutter?

Time:11-23

How can I call a method when a button is clicked 10 times. Here is the code for button.

NextQuestionButton(
              onClick: () {
                if (answerWasSelected) {
                  _nextQuestion();
                } else {
                  return;
                }
              },
            )

CodePudding user response:

Try to add a count variable at parent stateful widget.
And increase count variable when button is clicked and check whether count is over than 10.
If count is over, excute method and reset count.

class ParentWidget extends StatefulWidget {
}

class _ParentWidget extends State<ParentWidget> {
   int buttonCount = 0;

   Widget build(BuildContext context) {
       return ...

          NextQuestionButton(
              onClick: () {
                buttonCount  = 1;
                if (answerWasSelected && buttonCount > 9) {
                  buttonCount = 0;
                  _nextQuestion();
                } else {
                  return;
                }
              },
            )
...

CodePudding user response:

you can add a counter to the button and increase it's count on click then apply logic that when count == 10

int answerWasSelected =1;


NextQuestionButton(
              onClick: () {
 setState(() {
    answerWasSelected  ;
  });
                if (answerWasSelected==10) {
                  _nextQuestion();
                } else {
                  return answerWasSelected;
                }
              },
            )
`

CodePudding user response:

Just make a counter for your button and when count is getter than 9 then make the count 0 and call your method.

    class YourScreen extends StatefulWidget {
}

class _YourScreen extends State<YourScreen> {
   int countOnButton = 0;

   Widget build(BuildContext context) {
       return Scaffold(

     body:     NextQuestionButton(
              onClick: () {
                countOnButton  = 1;
                answerWasSelected && countOnButtoon > 9 
                 ?  _nextQuestion()
                 :  print("methed not working") ;
               
              },
            )
);
  • Related