【发布时间】:2020-02-14 08:46:50
【问题描述】:
当我调用我的倒计时小部件时,我有这个例外:
在构建 Countdown(dirty, state: _CountdownState#97b4a) 时引发了以下 NoSuchMethodError: 在 null 上调用了方法 '~/'。 接收方:空 尝试调用:~/(3600)
用户创建的导致错误的小部件的祖先是 容器
初始化状态为空
1ms 后,我的 appbar 中显示我的倒计时,这很好,但是为什么呢?
class IneatAppBarPollWidget {
getAppBar(String title, String logo, Candidate candidate) {
return AppBar(
title: Text(title),
leading: Image.asset(
logo,
fit: BoxFit.contain,
height: 32,
),
actions: <Widget>[
new Container(
child: new Row(
children: <Widget>[
new Container(
margin:EdgeInsets.only(right: 10),
child: new Countdown(),
),
new CircleAvatar(
child: new Text(
'${candidate.firstname[0].toUpperCase()}.${candidate.lastname[0].toUpperCase()}',
style: TextStyle(fontSize: 20),
),
backgroundColor: Colors.white,
),
],
),
margin: EdgeInsets.only(right: 10),
),
],
);
}
}
class Countdown extends StatefulWidget {
@override
_CountdownState createState() => _CountdownState();
}
class _CountdownState extends State<Countdown> {
Timer _timer;
int seconds;
@override
Widget build(BuildContext context) {
return Center(
child: Text(
constructTime(seconds),
style: TextStyle(
fontSize: 18, color: Colors.white, fontStyle: FontStyle.italic),
),
);
}
String constructTime(int seconds) {
int hour = seconds ~/ 3600;
int minute = seconds % 3600 ~/ 60;
int second = seconds % 60;
return formatTime(hour) +
":" +
formatTime(minute) +
":" +
formatTime(second);
}
String formatTime(int timeNum) {
return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
}
@override
initState() {
getDate();
startTimer();
super.initState();
}
void getDate() async {
var now = DateTime.now();
String creationDate = await Poll().getCreationDateToSF();
DateTime creationDateTime = DateTime.parse(creationDate);
seconds = creationDateTime.difference(now).inSeconds;
}
void startTimer() {
const period = const Duration(seconds: 1);
_timer = Timer.periodic(period, (timer) {
setState(() {
seconds--;
});
if (seconds == 0) {
cancelTimer();
}
});
}
void cancelTimer() {
if (_timer != null) {
_timer.cancel();
_timer = null;
}
}
@override
void dispose() {
super.dispose();
cancelTimer();
}
}
【问题讨论】:
-
如果没有您向我们展示您的 Countdown() 小部件,我看不出我们在这方面有何帮助。
-
@Marc 我编辑了我的帖子,抱歉
-
只是一个疯狂的猜测......它可能是秒或计时器实例变量的初始化问题?
-
好吧也许......但为什么在 1ms 后我的 appbar 中有结果? @马克
-
错误发生在方法 getDate 和 creationDate String 但为什么呢? @马克
标签: android flutter mobile flutter-layout