import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class CountDownButton extends StatefulWidget{ final String text; final Function countDownCallBack; final Function onPress; final int countDownTime; final AlignmentGeometry align; CountDownButton(this.text,this.countDownCallBack,{this.countDownTime=5*60,this.align=Alignment.center,this.onPress}); @override State createState() { return CountDownButtonState(); } } class CountDownButtonState extends State { int secondsPassed ; Timer timer; void handleTick() { // if (isActive) { if(secondsPassed==1){ widget.countDownCallBack(); timer?.cancel(); return; } setState(() { secondsPassed = secondsPassed - 1; //需要更新UI }); // } } getFull(int sec){ return sec<10?'0$sec':'$sec'; } @override void initState() { super.initState(); secondsPassed = widget.countDownTime; timer = Timer.periodic(Duration(seconds: 1), (Timer t){ handleTick(); }); } @override void dispose() { super.dispose(); timer?.cancel(); } @override Widget build(BuildContext context) { // ~/ 取整操作 int seconds = secondsPassed % 60; int minutes = secondsPassed ~/ 60; return Container( alignment: widget.align, // margin: EdgeInsets.only(left: 30, right: 30, top: 20,bottom: 20), height: 48, child: RaisedButton( color: Color(0xff3875E9), shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10))), child: RichText( maxLines: 1, textAlign: TextAlign.center, text: TextSpan(children: [ TextSpan( text: widget.text, style: TextStyle( color: Colors.white, fontSize: 16)), TextSpan( text:' ('+ getFull(minutes)+' : '+getFull(seconds)+')', style: TextStyle( color: Colors.white, fontSize: 13)), ])) , onPressed: widget.onPress), ); } }