首页 > 解决方案 > 如何在颤动的异步函数中访问字符串

问题描述

我在有状态小部件中有一个异步函数。在BuildContext下,我有这个功能,

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

如何使用numberOfChildrenText 小部件内部的变量。

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

但它说numberOfChild

在此处输入图像描述

如何在文本小部件中使用它?

标签: flutterdartasynchronousasync-awaitfuture

解决方案


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}');
        }
      },
    )

推荐阅读