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.
 
 
 
 
 
 

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