Timer.periodic 无法与提供者一起正常工作
我正在尝试在扩展了类 ChangeNotifier
(包 Provider)使我的变量time
每秒减少。
如果我不添加重新绘制占用 time
属性的所有小部件的 NotifyListeners
方法,则此方法可以正常工作,例如:
class PriceProvider extends ChangeNotifier{
int _time = 60;
int get time{
return _time;
}
void chronometer(){//method which activate the timer
Timer _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer){
print(DateTime.now());//I print the date so you can see how often the code is executed
_time += -1;//decrease time
if(_time == 0){
_time = 60;
}
// notifyListeners();
});
}
}
另一方面,如果我取消注释 NotifyListeners
方法,代码就会开始以指数方式每秒执行越来越多的次数(例如,首先执行一次,然后执行两次,然后是 5,然后是 9,依此类推):
这是我调用方法 chronometer
的代码:
class PriceWithClock extends StatelessWidget {
@override
Widget build(BuildContext context) {
PriceProvider priceProvider = Provider.of<PriceProvider>(context);
priceProvider.chronometer();
return CircularPercentIndicator(
radius: 100.0,
lineWidth: 5.0,
percent: 1-priceProvider.time/60,
center: Text("00:${priceProvider.time}"),
),
);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应将
priceProvider.chronometer();
放入构建方法中,因为它将在每个PriceWithClock
小部件构建中执行。就你而言,这种情况每秒都会发生。您可以做的是创建一个有状态小部件并在
initState()
方法内触发计时器:对于
build
方法,您可以使用context. watch
Provider 扩展方法来监听更新的time
值:最终结果如下所示:
You should not put the
priceProvider.chronometer();
inside the build method since it will be executed on everyPriceWithClock
widget build. And in your case, it would happen every second.What you can do, is create a Stateful widget and trigger the chronometer inside the
initState()
method:As for the
build
method, you could use thecontext.watch
Provider extension method to listen to the updatedtime
value:The final result looks like this: