flutter 页面打开时开始计数的简单计时器[抖动]

ulmd4ohb  于 2023-02-05  发布在  Flutter
关注(0)|答案(3)|浏览(142)

我有一个页面,我想向用户显示他们在页面上的经过时间,类似于Forest应用程序对番茄方法所做的,但是我的页面不是倒计时,而是计时。
我一直无法让计时器在页面加载时启动。我还想让计时器停止,并在用户退出页面时打印经过的时间。并将经过的时间数据传递到后端或其他页面。使用的包是https://pub.dev/packages/simple_timer
如何才能最好地实现这一点?谢谢Maven!

class TimerPage extends StatefulWidget {

  @override
  _TimerPageState createState() => _TimerPageState();
}

class _TimerPageState extends State<TimerPage>
    with SingleTickerProviderStateMixin {
  TimerController _timerController;
  TimerProgressTextCountDirection _progressTextCountDirection =
      TimerProgressTextCountDirection.count_up;

  @override
  void initState() {
    _timerController = TimerController(this);
    _timerController.start();
    _timerController.forward(from: 0.0);
    _timerController.addListener(_printLatestValue);

    super.initState();
  }

  _printLatestValue() {
    print("${_timerController.duration}");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff04072E),
      appBar: AppBar(
        title: Text('Aloha', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.black,
      ),
      body: WillPopScope(child: SafeArea(
        child: SingleChildScrollView(
          child: Column(children: <Widget>[
            Container(
              margin: EdgeInsets.symmetric(vertical: 10),
              child: SimpleTimer(
                controller: _timerController,
                duration: const Duration(seconds: 0),
                displayProgressIndicator: false,
                backgroundColor: Colors.grey,
                progressTextStyle: TextStyle(color: Colors.white, fontSize: 60),
              ),
            ),
ElevatedButton( onPressed: ()  {
_printLatestValue();
                Navigator.pushReplacement<void, void>(
                    context,
                    MaterialPageRoute<void>(
                    builder: (BuildContext context) =>  MainPage()));
              },child: Text('Next'))
          ]),
        ),
      ),
),
    ); 
  }
}

插入后出现的错误

_timerController.start();
    _timerController.forward(from: 0.0);

qhhrdooz

qhhrdooz1#

您应该在initState中调用_timerController.start()来启动计时器:)要显示时间或在用户退出页面后传递时间,您可以使用两种方法来高效地完成此操作:Navigator弹出结果和一个WillPopScope小部件,只需将页面 Package 成一个WillPopScope,并在回调函数中调用Navigator.pop

hl0ma9xz

hl0ma9xz2#

使用我的这个包https://pub.dev/packages/count_up_flutter它有简单的实现检查出我的github repo

bfnvny8b

bfnvny8b3#

在您的错误屏幕中说...在开始之前在initState()上添加此行

_timeController = TimerController.seconds(15);

相关问题