flutter - 如何启用/禁用与倒数计时器相关的按钮(用于电话验证的“重新发送代码”按钮)?
解决方案
你可以这样做使用Timer
from dart:async
..
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
int secondsRemaining = 30;
bool enableResend = false;
Timer timer;
@override
initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 1), (_) {
if (secondsRemaining != 0) {
setState(() {
secondsRemaining--;
});
} else {
setState(() {
enableResend = true;
});
}
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextField(),
const SizedBox(height: 10),
FlatButton(
child: Text('Submit'),
color: Colors.blue,
onPressed: () {
//submission code here
},
),
const SizedBox(height: 30),
FlatButton(
child: Text('Resend Code'),
onPressed: enableResend ? _resendCode : null,
),
Text(
'after $secondsRemaining seconds',
style: TextStyle(color: Colors.white, fontSize: 10),
),
],
);
}
void _resendCode() {
//other code here
setState((){
secondsRemaining = 30;
enableResend = false;
});
}
@override
dispose(){
timer.cancel();
super.dispose();
}
}
链接到 Dartpad 上的代码 - https://dartpad.dev/a59c751c4f6b4721a7af1cc27c67650b
推荐阅读
- javascript - 将道具传递给动态 TabNavigator
- javascript - 如何滚动固定的双导航栏?
- ios - 如何仅针对横向禁用 UIPageViewController 的分页?
- javascript - 使用 @babel/standalone 时 JavaScript 堆内存不足
- ios - 调试信息“DWARF”和崩溃日志
- javascript - 如何添加指向 Google GeoChart 地图的链接?
- javascript - MongoDB 的聚合函数有问题,得到错误消息不明白为什么
- typescript - 打字稿:如何将字符串转换为类型
- python - 如何平均熊猫数据框中的前瞻性数据
- javascript - 日历调度程序类似控件以指定值范围