Flutter中的Timer
Posted GY-93
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter中的Timer相关的知识,希望对你有一定的参考价值。
Flutter中的Timer
1.单次运行的定时器
- 源码:
factory Timer(Duration duration, void Function() callback)
if (Zone.current == Zone.root)
// No need to bind the callback. We know that the root's timer will
// be invoked in the root zone.
return Zone.current.createTimer(duration, callback);
return Zone.current
.createTimer(duration, Zone.current.bindCallbackGuarded(callback));
- 示例代码:
void countDown()
//创建一个单次的定时器
print("当前时间=======$DateTime.now()");
Timer timer = Timer(const Duration(seconds: 5), ()
print("5秒后执行定时器======$DateTime.now()");
setState(()
_counter++;
);
);
如果你立刻执行一个定时器,可以调用run方法:
/// Runs the given [callback] asynchronously as soon as possible.
///
/// This function is equivalent to `new Timer(Duration.zero, callback)`.
static void run(void Function() callback)
new Timer(Duration.zero, callback);
static const Duration zero = Duration(seconds: 0);
run()
:方法的实质是创建一个时间为0的定时器
创建定时器的时候, 如果传入的时间是负数或则0,这两种情况都当成时间是0,会立刻执行定时器,这一点官方文档是有说明的
2. 重复运行定时器
- 源码:
factory Timer.periodic(Duration duration, void callback(Timer timer))
if (Zone.current == Zone.root)
// No need to bind the callback. We know that the root's timer will
// be invoked in the root zone.
return Zone.current.createPeriodicTimer(duration, callback);
var boundCallback = Zone.current.bindUnaryCallbackGuarded<Timer>(callback);
return Zone.current.createPeriodicTimer(duration, boundCallback);
- 示例代码:
void countDown2()
//创建一个多次重复运行的定时器
print("当前时间=======$DateTime.now()");
Timer timer = Timer.periodic(const Duration(seconds: 3), (timer)
setState(()
print("3秒后执行定时器======$DateTime.now()");
_counter ++;
);
if (_counter == 5)
//循环5次之后停止定时器
timer.cancel();
print("执行5次之后停止定时器");
);
bool get isActive;
判断定时器,是否处于活跃状态
以上是关于Flutter中的Timer的主要内容,如果未能解决你的问题,请参考以下文章
Flutter:一小时从零构建一个简单的 App,以及你如何做到这一点!