Hibok
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

96 行
2.2 KiB

  1. import 'dart:async';
  2. import 'package:flutter/cupertino.dart';
  3. import 'package:flutter/material.dart';
  4. class CountDownButton extends StatefulWidget{
  5. final String text;
  6. final Function countDownCallBack;
  7. final Function onPress;
  8. final int countDownTime;
  9. final AlignmentGeometry align;
  10. CountDownButton(this.text,this.countDownCallBack,{this.countDownTime=5*60,this.align=Alignment.center,this.onPress});
  11. @override
  12. State<StatefulWidget> createState() {
  13. return CountDownButtonState();
  14. }
  15. }
  16. class CountDownButtonState extends State<CountDownButton> {
  17. int secondsPassed ;
  18. Timer timer;
  19. void handleTick() {
  20. // if (isActive) {
  21. if(secondsPassed==1){
  22. widget.countDownCallBack();
  23. timer?.cancel();
  24. return;
  25. }
  26. setState(() {
  27. secondsPassed = secondsPassed - 1; //需要更新UI
  28. });
  29. // }
  30. }
  31. getFull(int sec){
  32. return sec<10?'0$sec':'$sec';
  33. }
  34. @override
  35. void initState() {
  36. super.initState();
  37. secondsPassed = widget.countDownTime;
  38. timer = Timer.periodic(Duration(seconds: 1), (Timer t){
  39. handleTick();
  40. });
  41. }
  42. @override
  43. void dispose() {
  44. super.dispose();
  45. timer?.cancel();
  46. }
  47. @override
  48. Widget build(BuildContext context) {
  49. // ~/ 取整操作
  50. int seconds = secondsPassed % 60;
  51. int minutes = secondsPassed ~/ 60;
  52. return Container(
  53. alignment: widget.align,
  54. // margin: EdgeInsets.only(left: 30, right: 30, top: 20,bottom: 20),
  55. height: 48,
  56. child: RaisedButton(
  57. color: Color(0xff3875E9),
  58. shape: RoundedRectangleBorder(
  59. borderRadius: BorderRadius.all(Radius.circular(10))),
  60. child: RichText(
  61. maxLines: 1,
  62. textAlign: TextAlign.center,
  63. text: TextSpan(children: [
  64. TextSpan(
  65. text: widget.text,
  66. style: TextStyle(
  67. color: Colors.white,
  68. fontSize: 16)),
  69. TextSpan(
  70. text:' ('+ getFull(minutes)+' : '+getFull(seconds)+')',
  71. style: TextStyle(
  72. color: Colors.white, fontSize: 13)),
  73. ])) ,
  74. onPressed: widget.onPress),
  75. );
  76. }
  77. }