【问题标题】:Can't get Flutter Countdown/Timer Widget to count down无法让 Flutter Countdown/Timer Widget 倒计时
【发布时间】:2022-01-06 21:52:11
【问题描述】:

我正在尝试创建一个简单的小部件,它在构建时从 10 开始倒计时。我预计这会开始倒计时,但它仍然停留在 10 点。谁能看到这里出了什么问题?

class GameTimer extends StatefulWidget {
  const GameTimer({
    Key? key,
  }) : super(key: key);

  @override
  State<GameTimer> createState() => _GameTimerState();
}

class _GameTimerState extends State<GameTimer> {
  initState() {
    _startTimer();
  }

  int _counter = 10;
  late Timer _timer;

  void _startTimer() {
    _counter = 10;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState() {
        _counter--;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
        child: Text('$_counter',
            style: TextStyle(
              fontSize: 48,
              fontWeight: FontWeight.bold,
            )));
  }
}

【问题讨论】:

    标签: flutter timer countdown statefulwidget


    【解决方案1】:

    你需要在 initState 之前 @override 并且在里面你需要调用 super.initState()

    【讨论】:

      【解决方案2】:

      首先,您的 initState 没有覆盖 super 方法。所以应该是这样的:

      @override
      initState() {
         _startTimer();
         super.initState();
      }
      

      其次,在您的_startTimer 中,您要声明一个名为setState 的新函数。你错过了几个括号:

      setState(() {
         _counter--;
      });
      

      【讨论】:

        【解决方案3】:

        您的代码中有错误

        add super.initState(); in init state 
        

        seconde 你的回调函数应该看起来像 设置状态((){ _counter--;

          });
        

        【讨论】:

          【解决方案4】:

          你快到了!!!!!!

          您错过了将 setState 回调包装在括号中。

          更新代码:

          class GameTimer extends StatefulWidget {
            const GameTimer({
              Key? key,
            }) : super(key: key);
          
            @override
            State<GameTimer> createState() => _GameTimerState();
          }
          
          class _GameTimerState extends State<GameTimer> {
            initState() {
              _startTimer();
            }
          
            int _counter = 10;
            late Timer _timer;
          
            void _startTimer() {
              _counter = 10;
              _timer = Timer.periodic(Duration(seconds: 1), (timer) {
                setState(() {
                  _counter--;
                });
              });
            }
          
            @override
            Widget build(BuildContext context) {
              return SizedBox(
                  child: Text('$_counter',
                      style: TextStyle(
                        fontSize: 48,
                        fontWeight: FontWeight.bold,
                      )));
            }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-12-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多