我有一个ListView
,它从API获取数据,API调用首先由initState()
进行,并分配给List<DataFromApi> dataFromApi = [];
。一段时间后,我再次对同一API进行了后台调用,然后获取数据并分配给
dataFromApi
setState(() {
dataFromApi = [];
for (DataFromApi td in resData.data) {
dataFromApi.add(td);
}
});
记录时,数据会更改,但UI不会更改。如何更新ListView?
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<DataFromApi> dataFromApi = [];
@override
void initState() {
loadData();
super.initState();
fetchFirstData();
initTimedDataCall();
}
initTimedDataCall() {
Timer.periodic(Duration(minutes: 5), (timer) {
setState(() {
timedCall();
});
});
}
fetchFirstData() async {
final response = await http.get(
Utils.getDataUrl,
);
if (response.statusCode == 200) {
final resData = DataListFromJson(response.body);
if (resData.status == 1) {
print(response.body);
setState(() {
dataFromApi = [];
for (DataFromApi td in resData.data) {
dataFromApi.add(td);
}
});
}
///
///
/// DOING SOME MORE THINGS IN FIRST CALL
///
///
}
}
timedCall() async {
final response = await http.get(
Utils.getDataUrl,
);
if (response.statusCode == 200) {
final resData = DataListFromJson(response.body);
if (resData.status == 1) {
print(response.body);
setState(() {
dataFromApi = [];
for (DataFromApi td in resData.data) {
dataFromApi.add(td);
}
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: dataFromApi.length,
itemBuilder: (context, index) {
return Text('${dataFromApi[index].title}');
}
),
);
}
}
答案 0 :(得分:0)
计算完成后尝试调用setState
timedCall() async {
final response = await http.get(
Utils.getDataUrl,
);
if (response.statusCode == 200) {
final resData = DataListFromJson(response.body);
if (resData.status == 1) {
print(response.body);
dataFromApi = [];
for (DataFromApi td in resData.data) {
dataFromApi.add(td);
}
setState(() {
});
}
}
}
对其他方法使用类似的方法。这是我的工作