【问题标题】:How to retrive firebase subDocs - flutter如何检索firebase subDocs - 颤振
【发布时间】:2021-03-25 12:19:10
【问题描述】:

我想从 Firebase 检索一个子文档,我需要收集特定用户在他们的个人资料页面上提出和回答的问题数量,我正在成功检索问题数量,因为它在主文档中,@ 987654321@,但我无法检索答案,它是问题的子文档image 2 sub doc,我尝试从 AsyncSnaphot - DocumentSnapshot - 动态更改,但在任何地方都没有运气。提前谢谢你。

```Widget followers(
   BuildContext context, AsyncSnapshot<DocumentSnapshot> asyncSnapshot) {
   return Container(
   color: constantColors.green,
   height: MediaQuery.of(context).size.height*0.09,
   child: Row(
    children: [
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
                  .collection('questions')
                  .snapshots(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Container();
                } else {
                  return Provider.of<Authentication>(context, listen: false)
                              .getUserUid ==
                          asyncSnapshot.data.data()['user uid']
                      ? Text(snapshot.data.docs.length.toString(), style: TextStyle(fontSize: 24),)
                      : Text('0');
                }
              }),
          Text('asked'),
        ],
      ),
      Column(
        children: [
          StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
                  .collection('questions').doc().collection('answers')
                  .snapshots(),
              builder: (context, snapshot){
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Container();
                } else {
                  return Provider.of<Authentication>(context, listen: false)
                      .getUserUid ==
                      asyncSnapshot.data.data()['user uid']
                      ? Text(snapshot.data.docs.length.toString(), style: TextStyle(fontSize: 24),)
                      : Text('0');
                }
              }),
          Text('answered')

        ],
      )
    ],
  ),
);

} ```

编辑:将我的答案的更多代码添加到 Firebase 功能中

answerAdder(BuildContext context,
  AsyncSnapshot<DocumentSnapshot> documentSnapshot, String QuesID) {
  return showModalBottomSheet(
    elevation: 0,
    backgroundColor: Colors.transparent,
    isScrollControlled: true,
    context: context,
    builder: (context) {
      return Container(
        height: MediaQuery.of(context).size.height * 0.8,
        width: MediaQuery.of(context).size.width,
        margin: EdgeInsets.symmetric(horizontal: 5),
        decoration: BoxDecoration(
          color: constantColors.white,
          borderRadius: BorderRadius.only(
              topRight: Radius.circular(25), topLeft: Radius.circular(25)),
        ),
        child: Column(
          children: [
            Divider(
              indent: 110,
              endIndent: 110,
              thickness: 4,
              color: Colors.grey,
            ),
            Padding(
              padding: const EdgeInsets.all(5.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  MaterialButton(
                    onPressed: () {
                      Provider.of<PostFunctions>(context, listen: false)
                          .addAnswer(
                              context,
                              documentSnapshot.data.data()['question id'],
                              answerController.text,
                              titleController.text)
                          .whenComplete(() {
                        Navigator.pop(context);
                      });
                      Navigator.pop(context);
                    },
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15)),
                    color: constantColors.cyangrad,
                    child: Text(
                      'add answer',
                      style: TextStyle(fontWeight: FontWeight.w600),
                    ),
                  )
                ],
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height * 0.2,
              child: Padding(
                padding: const EdgeInsets.all(5.0),
                child: TextField(
                  controller: answerController,
                  maxLines: 8,
                  cursorColor: constantColors.green,
                  decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(15),
                      hintText: 'Please enter your answer',
                      isDense: true,
                      enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20),
                          borderSide: BorderSide.none),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20),
                          borderSide: BorderSide.none),
                      fillColor: Colors.grey[300],
                      filled: true),
                ),
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height * 0.2,
              child: Padding(
                padding: const EdgeInsets.all(5.0),
                child: TextField(
                  controller: titleController,
                  maxLines: 8,
                  cursorColor: constantColors.green,
                  decoration: InputDecoration(
                      contentPadding: EdgeInsets.all(15),
                      hintText: 'Please enter your title',
                      isDense: true,
                      enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20),
                          borderSide: BorderSide.none),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20),
                          borderSide: BorderSide.none),
                      fillColor: Colors.grey[300],
                      filled: true),
                ),
              ),
            ),
          ],
        ),
      );
    });}

上传答案的未来方法

Future addAnswer(BuildContext context, String postId,
  String answer, String answerTitle) async {
  return FirebaseFirestore.instance
    .collection('questions')
    .doc(postId)
    .collection('answers')
    .doc(answerTitle)
    .set({
  'answer': answer,
  'username': Provider.of<FirebaseOps>(context, listen: false).initUsername,
  'user uid':
  Provider.of<Authentication>(context, listen: false).getUserUid,
  'userimage':
  Provider.of<FirebaseOps>(context, listen: false).initUserimage,
  'useremail':
  Provider.of<FirebaseOps>(context, listen: false).initUseremail,
  'time': Timestamp.now(),
});

}

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    问题出在.collection('questions').doc().collection('answers')

    您需要在doc() 函数中传递文档名称。把它当成一条路!

    以你的例子,应该是:
    .collection('questions').doc('hoo lala').collection('answers')

    【讨论】:

    • 感谢您的回复,但是如果您可以看到我的代码,我想以编程方式检查每个问题,所以我必须浏览每个文档并查看用户是否回答了任何问题,并显示他在他们的个人资料中回答的答案数。
    • 为此,您需要使用列表 .doc(qusetionList[index]) 并且您可以从第一个 .collection('questions') 填充 questionList 。只需使用questionList.add(snapshot.data.docs[index].id)!填充列表后,触发第二个集合!
    • 非常感谢您的回答,但我没有明白,我对编程很陌生这是我编程的第 1 个月,您能解释一下吗?
    • 你确定!我只是想进一步了解您的要求。您只想显示问题和答案计数吗?还是其他数据?你是如何添加答案的?来自你的 Flutter 应用?
    • 请不要将您的代码放在答案中,否则会被标记!您可以编辑您的问题或在某处托管您的代码并向我发送链接
    猜你喜欢
    • 2019-06-11
    • 2020-09-10
    • 2020-12-03
    • 2021-12-09
    • 2020-10-20
    • 2021-10-09
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多