Skip to content

Instantly share code, notes, and snippets.

@CaiJingLong
Last active October 10, 2018 09:26
Show Gist options
  • Save CaiJingLong/2a1d92ef7e1219b12c88644fbbccce07 to your computer and use it in GitHub Desktop.
Save CaiJingLong/2a1d92ef7e1219b12c88644fbbccce07 to your computer and use it in GitHub Desktop.
flutter 倒计时按钮 代码片段
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
typedef String TextMaker(int time);
class CountTimerButton extends StatefulWidget {
final Function onTap;
final TextMaker textMaker;
const CountTimerButton({
Key key,
@required this.onTap,
@required this.textMaker,
int maxSecond = maxTime,
}) : super(key: key);
@override
_CountTimerButtonState createState() => _CountTimerButtonState();
}
const maxTime = 15;
class _CountTimerButtonState extends State<CountTimerButton> {
int time = 0;
Timer timer;
@override
void initState() {
super.initState();
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FlatButton(
onPressed: _getTap(),
child: Text(widget.textMaker(time)),
);
}
Function _getTap() {
if (time == 0) {
return () => _startCountDown();
}
return null;
}
_startCountDown() {
widget.onTap?.call();
setState(() {
time = maxTime;
});
timer?.cancel();
timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
time = maxTime - timer.tick;
if (time == 0) {
timer.cancel();
}
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment