我有3个int变量,我希望在初始化状态期间通过void函数进行更新。我尝试将它们打印出来,并且该值正确,但是当我尝试在容器中显示它们时,它仍然显示0。
int equipmentCount1 = 0;
int equipmentCount2 = 0;
int equipmentCount3 = 0;
@override
void initState() {
getEquipmentCount('Hammer', equipmentCount1);
getEquipmentCount('Spanner', equipmentCount2);
getEquipmentCount('Screwdriver', equipmentCount3);
super.initState();
}
void getEquipmentCount(String type, int counter) async {
await Firestore.instance
.collection('Notes')
.document('CarNotes')
.collection('PM Overview')
.document(type)
.collection(type)
.getDocuments()
.then((QuerySnapshot snapshot) {
setState(() {
return counter = snapshot.documents.length;
});
});
print(counter);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(equipmentCount1),
Text(equipmentCount2),
Text(equipmentCount3),
答案 0 :(得分:1)
您应该传递一个回调函数,以便可以更新状态。 这是一个示例:
@override
void initState() {
getEquipmentCount('Hammer', (int count) => setState(() {
equipmentCount1 = count;
}));
// same for the others
super.initState();
}
void getEquipmentCount(String type, ValueChanged<int> onCountChanged) {
Firestore.instance
.collection('Notes')
.document('CarNotes')
.collection('PM Overview')
.document(type)
.collection(type)
.getDocuments()
.then((QuerySnapshot snapshot) {
onCountChanged(snapshot.documents.length);
});
});
print(counter);
}
此外,由于您在await
上使用then
,因此Future
也不是必需的,并且setState
中的函数不需要返回任何内容。 / p>
答案 1 :(得分:1)
该值仍为0,因为在您的方法中,您仅更改方法内部的counter
变量,而不更改实例变量equipmentCount3
。您可以创建一个列表以添加所有3个值,然后在build
方法内使用该列表:
int equipmentCount1 = 0;
int equipmentCount2 = 0;
int equipmentCount3 = 0;
List<int> listOfEquipments = List();
void getEquipmentCount(String type, int counter) async {
await Firestore.instance
.collection('Notes')
.document('CarNotes')
.collection('PM Overview')
.document(type)
.collection(type)
.getDocuments()
.then((QuerySnapshot snapshot) {
setState(() {
listOfEquipments.add(snapshot.documents.length);
});
});
}
要将list
添加到build
方法中,请检查以下内容: