计时器

计时器的实现依赖于Timer.periodic,这个函数与JS中的setInterval很类似,是用于定时触发某个动作的,因此,可以考虑定义一个Stateful类型的Widget,在其中定义一个startTimer函数,在其中每隔1000毫秒就执行一次setState触发组件重绘,同时将时间设置为当前时间:

DateTime now = DateTime.now();
 
startTimer(){
    Duration duration = Duration(microseconds: 1000);
    Timer.periodic(duration, (Timer t) {
      if(!mounted){
        return;
      }
      setState(() {
        now = DateTime.now();
      });
    });
  }

 在状态机初始化的时候开始计时:

@override
  State<StatefulWidget> createState() {
    var state = new BaseClockState();
    state.startTimer();
    return state;
  }

 然后,在build函数中返回需要构建的日期格式就可以了。

@override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Text.rich(
        TextSpan(
            text: "${now.year}-${now.month}-${now.day} ${DateFormatter.pad0(now.hour)}:${DateFormatter.pad0(now.minute)}:${DateFormatter.pad0(now.second)}",
            style: TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.w700,
              color: Colors.red,
              height: 1.5,
            )
        )
    );

 效果图:

 

posted @ 2020-10-15 16:00  猎喵Rachel  阅读(111)  评论(0)    收藏  举报