为什么我的void函数不会更新我的int变量?

时间:2020-05-04 05:57:16

标签: firebase flutter dart google-cloud-firestore

我有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),


2 个答案:

答案 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方法中,请检查以下内容:

https://stackoverflow.com/a/61548797/7015400

相关问题