import 'package:flutter/material.dart'; import 'dart:async'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { final StreamController _streamController = StreamController<int>(); int count = 10; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("短信倒计时"), ), body: Center( child: StreamBuilder<int>( stream: _streamController.stream, initialData: 0, builder: (BuildContext context, AsyncSnapshot<int> snapshot) { return RaisedButton( onPressed: () async { if (snapshot.data == 0) { _startTimer(); } }, child: Text( snapshot.data == 0 ? "获取验证码" : '${snapshot .data} 秒后重发', style: snapshot.data == 0 ? TextStyle(color: Colors.blue, fontSize: 14) : TextStyle(color: Colors.grey, fontSize: 14), ), ); } ), ), ) ); } void _startTimer() { count = 60; _timer = Timer.periodic(Duration(seconds: 1), (timer) { if (count <= 0) { _cancelTimer(); return; } _streamController.sink.add(--count); }); } /// 取消倒计时的计时器。 void _cancelTimer() { // 计时器(`Timer`)组件的取消(`cancel`)方法,取消计时器。 _timer?.cancel(); } void dispose() { // TODO: implement dispose //关掉不需要的Stream; _streamController.close(); super.dispose(); } }