GridView.count() 在 cron 中更改值时不更新



我想做什么

我正在尝试做的是从 API 调用中检索数据,并将响应中的数据每分钟传递给GridView.count()小部件,因为数据可能会发生变化。

我使用FutureBuilder小部件和cron/cron.dartCron功能来做到这一点,如果有帮助的话。

这是代码:

FutureBuilder<dynamic>(
future: Api.getFoods(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
List<Widget> slots = [];
if (snapshot.data == null) {
return Text('');
}
var data = snapshot.data;
cron.schedule(new Schedule.parse('*/1 * * * *'), () async {
setState(() {
data = snapshot.data;
});
slots = [];
});
for (int i = 0; i < snapshot.data.length; i++) {
slots.add(new FoodSlot(
snapshot.data[i]['name'],
snapshot.data[i]['created_at'],
snapshot.data[i]['qty'].toString()
));
}
return new GridView.count(
crossAxisCount: 2,
scrollDirection: Axis.vertical,
children: slots
);
})

FoodSlot小组件创建一个Card,并显示卡片上参数中传递的值。

我尝试了什么

调试后,我看到 cron 作业工作正常,但GridView小部件无法更新。

我尝试使用Text小部件而不是GridView并返回 API 调用返回的值,并且小部件按预期每 1 分钟自动更新一次。

为什么GridView.count()会这样,我该如何解决这个问题?


更新

在数据库中进行更改时,GridView 会更新,但仅在重新启动应用程序(使用 are not r(时更新。

解决了!

事实证明,我必须在FoodSlot小部件中添加 cron 作业并定期更新小部件本身。

最终在FoodSlotinitState()函数中添加了以下内容:

@override
void initState() {
super.initState();
colorSettings = HelperFunctions.setStateColour(expiry);
cron.schedule(new Schedule.parse('*/1 * * * *'), () async {
setState(() {
Api.getFood(id).then((res) {
expiry = res['created_at'];
name = res['name'];
qty = res['qty'].toString();
colorSettings = HelperFunctions.setStateColour(expiry);
});
});
});
}

其中idFoodSlot小组件引用的数据库条目的 ID。

希望这对某人有所帮助:)

最新更新