【问题标题】:How to call a function when a button is clicked 10 times in flutter?在颤动中单击按钮10次时如何调用函数?
【发布时间】:2021-11-23 11:26:07
【问题描述】:

如何在单击按钮 10 次时调用方法。这是按钮的代码。

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

【问题讨论】:

  • 您可以向按钮添加一个计数器并增加它的点击次数,然后应用 count == 10 时的逻辑
  • 您可以向按钮添加一个计数器并增加它的点击次数,然后应用当 count == 10 ` int answerWasSelected =1; 时的逻辑NextQuestionButton( onClick: () { setState(() { answerWasSelected++; }); if (answerWasSelected==10) { _nextQuestion(); } else { return answerWasSelected; } }, ) `

标签: android flutter loops dart button


【解决方案1】:

尝试在父状态小部件中添加计数变量。
并在单击按钮时增加计数变量并检查计数是否超过 10。
如果计数结束,则执行方法并重置计数。

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;
                }
              },
            )
...

【讨论】:

    【解决方案2】:

    您可以向按钮添加一个计数器并增加它的点击次数,然后应用计数 == 10 时的逻辑

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

    【讨论】:

      【解决方案3】:

      只需为您的按钮创建一个计数器,当计数大于 9 时,将计数设为 0 并调用您的方法。

          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") ;
                     
                    },
                  )
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-04
        • 2020-12-23
        • 1970-01-01
        • 2019-08-11
        • 2023-03-21
        • 2013-02-26
        • 2014-01-11
        • 1970-01-01
        相关资源
        最近更新 更多