use*_*322 6 dart flutter flutter-layout
我有一个按钮,它应该在 30 秒内出现。倒计时从 30 秒开始。当它达到 0 时,重新发送代码按钮应该出现/启用。
Jig*_*tel 17
你可以像这样使用Timerfrom 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();
}
}
Run Code Online (Sandbox Code Playgroud)
链接到 Dartpad 上的代码 - https://dartpad.dev/a59c751c4f6b4721a7af1cc27c67650b