好久不見(jiàn)了,文章有一段時(shí)間沒(méi)有更新了,最近一直在沉迷工作無(wú)法自撥??。上周,應(yīng)公司號(hào)召以及上次Google大會(huì)中Flutter宣講的感染,計(jì)劃將公司新項(xiàng)目采用Flutter技術(shù)實(shí)現(xiàn)。大概花了幾天熟悉了一下Flutter基礎(chǔ)語(yǔ)法和結(jié)構(gòu)組成,便著手開始項(xiàng)目的搭建和基礎(chǔ)模塊功能開發(fā),畢竟只有通過(guò)實(shí)戰(zhàn)才能加快新技術(shù)的熟悉和“消化”。
說(shuō)到驗(yàn)證碼功能,我們通常的做法可能是借助于計(jì)時(shí)器來(lái)實(shí)現(xiàn),抱著幾乎肯定的態(tài)度趕緊去查了一下 Flutter 官網(wǎng)有沒(méi)有相關(guān)的計(jì)時(shí)器組件。果不其然,官方的確為我們提供了一個(gè) Timer 組件來(lái)實(shí)現(xiàn)倒計(jì)時(shí),我們來(lái)看看官方對(duì)于它的描述:
A count-down timer that can be configured to fire once or repeatedly.
即它是一個(gè)支持一次或者多次周期性觸發(fā)的計(jì)時(shí)器。首先,讓我們來(lái)熟悉這兩種場(chǎng)景下的基本用法。
單次觸發(fā)
這種情況下的一般場(chǎng)景是作為延時(shí)器來(lái)使用,我們并不會(huì)接收到倒計(jì)時(shí)的進(jìn)度,只會(huì)在倒計(jì)時(shí)結(jié)束后收到回調(diào)提醒。例如,我們來(lái)看下 Flutter 官方提供的示例代碼:
const timeout = const Duration(seconds: 3);
const ms = const Duration(milliseconds: 1);
startTimeout([int milliseconds]) {
var duration = milliseconds == null ? timeout : ms * milliseconds;
return new Timer(duration, handleTimeout);
}
...
void handleTimeout() { // callback function
...
}
從上面代碼可以看到,通過(guò) new Timer(Duration duration, void callback()) 方式創(chuàng)建的定時(shí)器會(huì)提供一個(gè) callback 回調(diào)方法來(lái)處理計(jì)時(shí)結(jié)束后的操作。這顯然不符合我們驗(yàn)證碼功能中實(shí)時(shí)顯示進(jìn)度的需求,讓我們來(lái)看看 Timer 如何重復(fù)性觸發(fā)回調(diào)。
周期性觸發(fā)
周期性觸發(fā)計(jì)時(shí)回調(diào)的場(chǎng)景就很普遍了,只要是涉及到定時(shí)相關(guān)的操作可能都離不開它:我們既需要被告知計(jì)時(shí)什么時(shí)候結(jié)束,也需要實(shí)時(shí)地監(jiān)測(cè)計(jì)時(shí)的進(jìn)度。這正符合了我們最初想要的驗(yàn)證碼功能這個(gè)需求。dart-async 包 同樣為我們提供了 Timer.periodic 構(gòu)造方法來(lái)創(chuàng)建一個(gè)可以重復(fù)回調(diào)的計(jì)時(shí)器:
Timer.periodic(
Duration duration,
void callback(
Timer timer
)
)
此外,官方是這樣描述 callback 參數(shù)的:
The
callbackis invoked repeatedly withdurationintervals until canceled with the cancel function.
大概意思是:callback 回調(diào)方法會(huì)伴隨時(shí)間推移而被多次調(diào)用(調(diào)用周期為 duration),直到調(diào)用 Timer.cancel 方法。值得注意的是,周期性回調(diào)的計(jì)時(shí)器并不會(huì)“結(jié)束計(jì)時(shí)”,或者說(shuō)它并不會(huì)自動(dòng)結(jié)束計(jì)時(shí)任務(wù),所以我們需要手動(dòng)去統(tǒng)計(jì)時(shí)間并及時(shí)取消計(jì)時(shí)任務(wù)。具體如何操作呢?說(shuō)了這么多,下面讓我們進(jìn)入本文正題:驗(yàn)證碼倒計(jì)時(shí)實(shí)現(xiàn)吧??。其實(shí),該功能的實(shí)現(xiàn)代碼很簡(jiǎn)單,這里就直接貼代碼了:
Timer _countDownTimer;
int _currentTime = 60;
bool get _isTimeCountingDown => _currentTime != 60;
void _startTimeCountDown() {
if (_countDownTimer != null) {
timer.cancel();
timer = null;
}
_countDownTimer = Timer.periodic(Duration(seconds: 1), (timer) {
if (timer.tick == 60) {
_currentTime = 60;
_countDownTimer.cancel();
_countDownTimer = null;
} else {
_currentTime--;
}
setState(() {
});
});
}
@override
void dispose() {
_countDownTimer?.cancel();
_countDownTimer = null;
super.dispose();
}
我們可以通過(guò) Timer.tick 來(lái)獲取當(dāng)前計(jì)時(shí)(遞增)的進(jìn)度,同時(shí)借助于 _currentTime 來(lái)標(biāo)記計(jì)時(shí)的進(jìn)度值,其他的邏輯代碼應(yīng)該就比較好理解了。
什么?你以為到這里就完了?哈哈,當(dāng)然不會(huì),假如倒計(jì)時(shí)功能需要在我們項(xiàng)目里有很多不同的使用情景,那么就該對(duì)倒計(jì)時(shí)這個(gè)功能進(jìn)行封裝了,況且,通過(guò) setState 方式來(lái)實(shí)時(shí)展示倒計(jì)時(shí)進(jìn)度而去刷新整個(gè)視圖樹著實(shí)不太友好。
倒計(jì)時(shí)封裝
目前,F(xiàn)lutter 狀態(tài)管理方案呈現(xiàn)“百家爭(zhēng)鳴”之態(tài),個(gè)人還是比較喜歡 Provider 來(lái)管理狀態(tài)。下面就用 Provider 來(lái)將倒計(jì)時(shí)功能封裝為一個(gè)組件:
import 'dart:async';
import 'package:flutter/material.dart';
/// 計(jì)時(shí)器組件
class CountDownTimeModel extends ChangeNotifier {
final int timeMax;
final int interval;
int _time;
Timer _timer;
int get currentTime => _time;
bool get isFinish => _time == timeMax;
CountDownTimeModel(this.timeMax, this.interval) {
_time = timeMax;
}
void startCountDown() {
if (_timer != null) {
_timer.cancel();
_timer = null;
}
_timer = Timer.periodic(Duration(seconds: interval), (timer) {
if (timer.tick == timeMax) {
_time = timeMax;
timer.cancel();
timer = null;
} else {
_time--;
}
notifyListeners();
});
}
void cancel() {
if (_timer != null) {
_timer.cancel();
_timer = null;
}
}
@override
void dispose() {
_timer.cancel();
_timer = null;
super.dispose();
}
}
具體如何使用呢?熟悉 Provider 用法的小伙伴應(yīng)該就不用多說(shuō)了,這邊為了演示方便,就以下面這個(gè)效果為例:

點(diǎn)擊“獲取驗(yàn)證碼”按鈕開始 60 秒倒計(jì)時(shí)服務(wù),結(jié)束倒計(jì)時(shí)過(guò)程中按鈕需要處于不可點(diǎn)擊狀態(tài),倒計(jì)時(shí)結(jié)束后恢復(fù)點(diǎn)擊狀態(tài)。具體代碼如下:
class _LoginPageState extends State<TestPage> {
@override
Widget build(BuildContext context) {
final logo = Hero(
tag: 'hero',
child: CircleAvatar(
backgroundColor: Colors.transparent,
radius: 48.0,
child: Image.asset(ImageAssets.holder_logo),
),
);
final email = TextFormField(
keyboardType: TextInputType.emailAddress,
autofocus: false,
initialValue: 'alucard@gmail.com',
decoration: InputDecoration(
hintText: 'Email',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
),
);
final password = TextFormField(
autofocus: false,
initialValue: 'some password',
obscureText: true,
decoration: InputDecoration(
hintText: 'Password',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
),
);
final loginButton = Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
onPressed: () {
},
padding: EdgeInsets.all(12),
color: Colors.lightBlueAccent,
child: Text('Log In', style: TextStyle(color: Colors.white)),
),
);
final forgotLabel = FlatButton(
child: Text(
'Forgot password?',
style: TextStyle(color: Colors.black54),
),
onPressed: () {},
);
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.only(left: 24.0, right: 24.0),
children: <Widget>[
logo,
SizedBox(height: 48.0),
email,
SizedBox(height: 8.0),
ScreenUtils.verticalSpace(2),
Stack(
children: <Widget>[
password,
PartialConsumeComponent<CountDownTimeModel>(
model: CountDownTimeModel(60, 1),
builder: (context, model, _) => Positioned(
right: 10,
bottom: 1,
top: 1,
child: FlatButton(
disabledColor: Colors.grey.withOpacity(0.36),
color: Colors.white70.withOpacity(0.7),
onPressed: !model.isFinish ? null : () {
model.startCountDown();
},
child: Text(
model.isFinish ? '獲取驗(yàn)證碼' : model.currentTime.toString()+'秒后重新獲取',
style: TextStyle(color: model.isFinish ? Colors.lightBlueAccent : Colors.white),
)
),
),
),
],
),
SizedBox(height: 24.0),
loginButton,
forgotLabel
],
),
),
);
}
}
這里,我們通過(guò)在 CountDownTimeModel 中定義的 isFinish 字段來(lái)判斷倒計(jì)時(shí)是否正在進(jìn)行,進(jìn)而處理按鈕的各種狀態(tài)(如顏色、點(diǎn)擊狀態(tài)、文字內(nèi)容等)。此處為了方便對(duì)當(dāng)前頁(yè)面狀態(tài)進(jìn)行管理,我單獨(dú)封裝了一個(gè)公用的消費(fèi)者組件:
class PartialConsumeComponent<T extends ChangeNotifier> extends StatefulWidget {
final T model;
final Widget child;
final ValueWidgetBuilder<T> builder;
PartialConsumeComponent({
Key key,
@required this.model,
@required this.builder,
this.child
}) : super(key: key);
@override
_PartialConsumeComponentState<T> createState() => _PartialConsumeComponentState<T>();
}
class _PartialConsumeComponentState<T extends ChangeNotifier> extends State<PartialConsumeComponent<T>> {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<T>.value(
value: widget.model,
child: Consumer<T>(
builder: widget.builder,
child: widget.child,
),
);
}
}
最后
本人剛接觸 Flutter 兩周左右,有些地方可能會(huì)為了開發(fā)進(jìn)度而忽略一些細(xì)節(jié),如有不嚴(yán)謹(jǐn)或者疏漏之處歡迎指正。此外,后續(xù)我將為大家?guī)?lái)更多 Android 和 Flutter 方面文章,請(qǐng)期待。