【发布时间】:2020-06-23 13:33:27
【问题描述】:
您好,我是 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 中。有人可以指出我,我在哪里犯了错误? 谢谢!!
【问题讨论】:
-
很难纠正,因为我们无法真正看到您如何更改值。我的第一个猜测是你忘了把 SetState() 放在你改变值的地方,但我不能确定。
-
如果您可以看到代码,startResendTimer() 是我使用 setState() 方法更新值的方法。 getResendWidget() 是我使用它的方法。在 getResendWidget() 中,我得到了更新的值,我在 RichText() 中设置了更新的值,但它没有反映在屏幕上。
-
什么是 CustomScreenBg ?我在没有它的情况下运行了你的示例,它工作正常,所以一定有问题
-
Tbh 我不明白你构建的双重返回是如何工作的,对我来说它甚至无法编译,而且我以前从未见过这样的事情。
-
感谢您的评论,您的评论让我明白了问题所在。这个 CustomScreenBg 是另一个 Stateful Widget。所以,我的错误是,我在另一个有状态小部件中使用了一个有状态小部件。这导致了问题。我将嵌套的小部件转换为无状态小部件,现在它工作正常。抱歉,我无法更好地解释它。
标签: flutter dart statelesswidget