Hibok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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