最佳答案
您可以使用 Timer
这样做来自 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
关于flutter - 如何启用/禁用与倒数计时器相关的用于电话验证的按钮 ("resend code"按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62952821/