counter_botton.dart 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:twong/utils/index.dart';
  4. class CounterButton extends StatefulWidget {
  5. final int max;
  6. final String before;
  7. final String loading;
  8. final Function onClick;
  9. final Color color;
  10. final Color disableColor;
  11. CounterButton({ this.max = 60, this.before = "获取验证码", this.onClick,
  12. this.loading = " s 后可重新获取", this.color = Colors.white,
  13. this.disableColor = Colors.white });
  14. @override
  15. State<StatefulWidget> createState() {
  16. return _CounterButtonState();
  17. }
  18. }
  19. class _CounterButtonState extends State<CounterButton> {
  20. var _counter;
  21. Timer _timer;
  22. String _codeTxt;
  23. var _enable = true;
  24. @override
  25. void initState() {
  26. super.initState();
  27. _codeTxt = widget.before;
  28. }
  29. @override
  30. Widget build(BuildContext context) {
  31. return Container(
  32. height: 38.px,
  33. width: 128.px,
  34. margin: EdgeInsets.only(bottom: 12.px),
  35. child: FlatButton(
  36. color: widget.color,
  37. child: Text(_codeTxt),
  38. shape: StadiumBorder(),
  39. disabledColor: widget.disableColor,
  40. onPressed: _enable ? _getCountdown : null,
  41. ),
  42. );
  43. }
  44. @override
  45. void dispose() {
  46. super.dispose();
  47. if(_timer != null) {
  48. _timer.cancel();
  49. }
  50. }
  51. void _getCountdown() {
  52. if(widget.onClick != null) {
  53. var ret = widget.onClick();
  54. if(ret != null && !ret) {
  55. return;
  56. }
  57. }
  58. setState(() {
  59. _enable = false;
  60. _counter = widget.max;
  61. _codeTxt = "$_counter${widget.loading}";
  62. });
  63. _timer = Timer.periodic(Duration(seconds: 1), (timer) {
  64. setState(() {
  65. if (_counter > 0) {
  66. _counter --;
  67. setState(() {
  68. _codeTxt = "$_counter${widget.loading}";
  69. });
  70. } else {
  71. _counter = widget.max;
  72. timer.cancel();
  73. setState(() {
  74. _enable = true;
  75. _codeTxt = "获取验证码";
  76. });
  77. }
  78. });
  79. });
  80. }
  81. }