flutter中验证码倒计时

flutter中更换手机号,验证码倒计时的一种写法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zzc_app/utils/dio/dio.dart';

class PhoneNumber extends StatefulWidget {
final userinfo;
PhoneNumber(this.userinfo, {Key key}) : super(key: key);

@override
_PhoneNumberState createState() => _PhoneNumberState();
}

class _PhoneNumberState extends State<PhoneNumber> {
final _codeController = TextEditingController();

Timer _countdownTimer;
String _codeCountdownStr = '获取验证码';
int _countdownNum = 59;

_getcode() async {
//获取验证码
var res = await Net().get('verification-code', {
'phone_number': widget.userinfo['phone_number'],
'type': "change_phone"
});
reGetCountdown();
}


@override
void initState() {
super.initState();
}

void reGetCountdown() {
setState(() {
if (_countdownTimer != null) {
return;
}
// Timer的第一秒倒计时是有一点延迟的,为了立刻显示效果可以添加下一行
_codeCountdownStr = '${_countdownNum--}(s)';
_countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
setState(() {
if (_countdownNum > 0) {
_codeCountdownStr = '${_countdownNum--}(s)';
} else {
_codeCountdownStr = '获取验证码';
_countdownNum = 59;
_countdownTimer.cancel();
_countdownTimer = null;
}
});
});
});
}

// 不要忘记在这里释放掉Timer
@override
void dispose() {
_countdownTimer?.cancel();
_countdownTimer = null;
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('绑定手机号')),
body: Container(
padding: EdgeInsets.only(left: 10, right: 10, top: 10),
child: ListView(
children: <Widget>[
ListTile(
leading: Text('当前手机号'),
title: Text(widget.userinfo['phone_number']),
),
Divider(),
ListTile(
title: TextField(
controller: _codeController,
decoration: InputDecoration(hintText: '请输入验证码'),
),
trailing: RaisedButton(
onPressed: _countdownNum >= 59 ? _getcode : null,
child: Text(_codeCountdownStr),
),
),
],
),
),
);
}
}
文章作者: Joker
文章链接: https://qytayh.github.io/2020/08/flutter%E4%B8%AD%E9%AA%8C%E8%AF%81%E7%A0%81%E5%80%92%E8%AE%A1%E6%97%B6/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Joker's Blog