嗨,我是 Flutter 和尝试使用 statefull 小部件的新手。我正在尝试构建一个计时器并希望在文本中显示它。
这是我的小部件类。
class MobileVerification extends StatefulWidget {
static const String MOBILE = 'mobile';
final Map<String, dynamic> args;
MobileVerification(this.args);
@override
State<StatefulWidget> createState() {
return MobileVerificationState(args);
}
}
这是我的州课
class MobileVerificationState extends State<MobileVerification> {
int remainingTime = 30;
Timer timer;
bool isResendBtnEnabled = false;
MobileVerificationState(this.args);
@override
void initState() {
super.initState();
startResendTimer();
}
startResendTimer() {
timer = new Timer.periodic(new Duration(seconds: 1), (time) {
setState(() {
remainingTime -= 1;
});
if (remainingTime == 0) {
time.cancel();
setState(() {
isResendBtnEnabled = true;
});
}
});
}
@override
void dispose() {
timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CustomScreenBg(
body: _getOtpVerificationPage());
}
_getOtpVerificationPage() {
return Container(
margin: EdgeInsets.only(top: 24, bottom: 24, left: 12, right: 12),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
getResendWidget(),
CustomButton(
AppString.verify,
isValidateBtnEnabled ? _onValidate : null,
textColor: AppColor.WHITE.color,
bgColor: AppColor.PRIMARY.color,
),
],
),
);
}
Widget getResendWidget() {
Logger.d(remainingTime.toString()); // Here I am getting changed value.
if (isResendBtnEnabled) {
return CustomButton(
AppString.resend,
_onResend,
textColor: AppColor.WHITE.color,
bgColor: AppColor.PRIMARY.color,
);
}
return RichText(
text: TextSpan(
text: 'Resend in ${remainingTime}s', <== But here value is not getting reflected. It stays same as 30
style: TextStyle(color: AppColor.GRAY.color, fontSize: 18),
),
);
}
}
计时器工作得很好,我也得到了更新的价值。但是更新后的值并没有反映在 RichText 中。有人可以指出我,我在哪里犯了错误?谢谢!!