如何解决在页面打开时开始计数的简单计时器 [Flutter]
我有一个页面,我想向用户显示他们在该页面上所用的时间,类似于 Forest 应用程序为其番茄工作法所做的一个页面。然而,我的不是倒数,而是倒数。
我一直无法让计时器在页面加载时启动。此外,我想让计时器停止并在用户退出页面后打印经过的时间。并将经过的时间数据传递到后端或其他页面。使用的包是https://pub.dev/packages/simple_timer
如何最好地实现这一目标?谢谢各位专家!
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);
解决方法
您应该在 _timerController.start()
内调用 initState
来启动计时器 :) 要在用户退出页面后显示时间或传递时间,您可以使用两件事来有效地做到这一点:导航器弹出窗口结果和一个 WillPopScope
小部件。只需将页面包装到 WillPopScope
中并在回调中使用结果调用 Navigator.pop
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。