Hibok
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

111 rader
2.7 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. final bool isOnlyRichText;
  11. CountDownButton(this.text,this.countDownCallBack,{this.countDownTime=5*60,this.align=Alignment.center,this.onPress,this.isOnlyRichText=false});
  12. @override
  13. State<StatefulWidget> 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. super.initState();
  38. secondsPassed = widget.countDownTime;
  39. timer = Timer.periodic(Duration(seconds: 1), (Timer t){
  40. handleTick();
  41. });
  42. }
  43. @override
  44. void dispose() {
  45. super.dispose();
  46. timer?.cancel();
  47. }
  48. @override
  49. Widget build(BuildContext context) {
  50. // ~/ 取整操作
  51. int seconds = secondsPassed % 60;
  52. int minutes = secondsPassed ~/ 60;
  53. return widget.isOnlyRichText?RichText(
  54. maxLines: 1,
  55. textAlign: TextAlign.center,
  56. text: TextSpan(children: [
  57. TextSpan(
  58. text: widget.text,
  59. style: TextStyle(
  60. color: Colors.white,
  61. fontSize: 16)),
  62. TextSpan(
  63. text:' ('+ getFull(minutes)+' : '+getFull(seconds)+')',
  64. style: TextStyle(
  65. color: Colors.white, fontSize: 13)),
  66. ])):
  67. Container(
  68. alignment: widget.align,
  69. // margin: EdgeInsets.only(left: 30, right: 30, top: 20,bottom: 20),
  70. height: 48,
  71. child: RaisedButton(
  72. color: Color(0xff3875E9),
  73. shape: RoundedRectangleBorder(
  74. borderRadius: BorderRadius.all(Radius.circular(10))),
  75. child: RichText(
  76. maxLines: 1,
  77. textAlign: TextAlign.center,
  78. text: TextSpan(children: [
  79. TextSpan(
  80. text: widget.text,
  81. style: TextStyle(
  82. color: Colors.white,
  83. fontSize: 16)),
  84. TextSpan(
  85. text:' ('+ getFull(minutes)+' : '+getFull(seconds)+')',
  86. style: TextStyle(
  87. color: Colors.white, fontSize: 13)),
  88. ])) ,
  89. onPressed: widget.onPress),
  90. );
  91. }
  92. }