1

I have an async function inside of a stateful widget. Under the BuildContext, I have this function,

getChildren() async {
      final String numberOfChildren = await FirebaseFirestore.instance
          .collection("children")
          .where("parentUID", isEqualTo: uid)
          .snapshots()
          .length
          .toString();
    }

How do I use the the numberOfChildren variable inside of a Text widget.

            Text(
                'Children: $numberOfChildren',
                style: TextStyle(
                  fontSize: 22,
                  color: Color(0xff74828E),
                  fontFamily: 'Rubik',
                  fontWeight: FontWeight.w900,
                ),
              ),

But it says that numberOfChild

enter image description here

How can I use this in a text widget?

3 Answers 3

1

This is because the variable numberOfChildren is local to that function. What you can do is make it global by declaring the variable right inside the class i.e

String numberOfChildren;
getChildren() async {
  numberOfChildren = await FirebaseFirestore.instance
      .collection("children")
      .where("parentUID", isEqualTo: uid)
      .snapshots()
      .length
      .toString();
}
Sign up to request clarification or add additional context in comments.

Comments

0
StreamBuilder<QuerySnapshot>(
    stream: FirebaseFirestore.instance
          .collection("children")
          .where("parentUID", isEqualTo: uid)
          .snapshots(), // async work
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
       switch (snapshot.connectionState) {
         case ConnectionState.waiting: return Text('Loading....');
         default:
           if (snapshot.hasError)
              return Text('Error: ${snapshot.error}');
           else
          return Text(
                'Children: ${snapshot.data.docs.length}');
        }
      },
    )

3 Comments

Please mark it as the correct answer to your question, thanks!
I will, but in 8 min, idk y there is a limit. I was going to
oh its 3 min, =)
0

That's basics of OOP You have to make numberOfChildren a variable of the class so you can use it on any function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.