【问题标题】:Implementing comment section for each post in flutter with cloud firestore使用 Cloud Firestore 为每个帖子实现评论部分
【发布时间】:2021-10-29 13:44:57
【问题描述】:

我正在创建 instagram 应用程序克隆,并在后端使用 firebase。这是一个初学者级别的项目,所以编码和结构是基本的。

我被困在每个帖子下添加评论部分。我正在使用 streambuilder 来显示数据并尝试创建一个函数,其中在提要屏幕上的每个图像都会有一个评论框,该评论框连接到 cloud-firestore 中的当前图像文档。

以下是我的数据库代码和图片:

class FeedScreen extends StatefulWidget {
  const FeedScreen({Key? key}) : super(key: key);

  @override
  _FeedScreenState createState() => _FeedScreenState();
}

class _FeedScreenState extends State<FeedScreen> {
  User? user = FirebaseAuth.instance.currentUser;


  

@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      bottomNavigationBar: BottomNavigation(),
      appBar: AppBar(
        backgroundColor: Colors.black,
        automaticallyImplyLeading: false,
        title: Text(
          "Platform",
          style: TextStyle(
            color: Colors.white,
            fontSize: 32.96,
            fontWeight: FontWeight.w500,
            fontFamily: 'Yaldevi',
          ),
        ),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection('users').snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot){
          if(snapshot.hasData){
            final List<DocumentSnapshot> documents = snapshot.data!.docs;
            return ListView(
              children: documents.map((doc) => SingleChildScrollView(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ListTile(
                        leading: doc['profileImage'] == null ?
                        CircleAvatar(
                          radius: 16.6,
                          backgroundColor: Colors.white24,
                        ) :
                        CircleAvatar(
                            radius: 16.6,
                            backgroundImage: NetworkImage(
                                doc['profileImage']
                            )
                        ),
                        title: Text(
                            doc['displayName'],
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.5,
                            )
                        ),
                        subtitle: doc['title'] !=null ?
                        Text(
                          doc['title'],
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 12.5,
                          ),
                        ) :
                        Text(
                            "Some Title",
                            style: TextStyle(
                              color: Colors.white,
                            )
                        ),
                      ),
                      if(doc['photoURL'] != null) ... [
                        Container(
                          height: 400,
                          width: 400,
                          child: Image(
                            image: NetworkImage(
                              doc['photoURL'],
                            ),
                            fit: BoxFit.contain,
                          )
                        ),
                        IconButton(
                          icon: Icon(
                            Icons.mode_comment_outlined,
                            color: Colors.white,
                          ),
                          onPressed: () {
                            Navigator.push(context,
                            MaterialPageRoute(
                              builder: (context) =>
                                  CommentSection(),
                            ));
                          },

                        )

                      ] else if(doc['photoURL'] == null) ...[
                        Container(
                          height: 400,
                          width: 400,
                          child: Image(
                            image: AssetImage(
                              "assets/images/placeholder.png"
                            ),
                            fit: BoxFit.contain,
                          )
                        )
                      ],
                      ListTile(
                          leading: Padding(
                            padding: EdgeInsets.only(bottom: 13.5 ),
                            child: Text( "@ " +
                                doc['displayName'],
                              style: TextStyle(
                                color: Colors.white,
                              ),
                            ),
                          ),
                          subtitle: Padding(
                              padding: EdgeInsets.only(bottom: 13.5),
                              child: doc['decsription'] != null ?
                              Text( ":" +
                                  doc['decsription'],
                                  style: TextStyle(
                                    color: Colors.white,
                                  )
                              ) :
                              Text(
                                  "Some Descritiption",
                                  style: TextStyle(
                                    color: Colors.white,
                                  )
                              )
                          )
                      ),
                    ]
                ),
              )).toList(),
            );
          } else {
            return CircularProgressIndicator();
          }
        }
      )
    );
  }
}







这是评论屏幕代码


import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';


class CommentSection extends StatefulWidget {
  // const CommentSection({Key? key}) : super(key: key);

  @override
  _CommentSectionState createState() => _CommentSectionState();
}

class _CommentSectionState extends State<CommentSection> {
  var username = ' ';
  List photoURL = [];

  User? user = FirebaseAuth.instance.currentUser;
  CollectionReference userRef = FirebaseFirestore.instance.collection('users');

  final _formKey = GlobalKey<FormState>();
  late String comments = ' ';




  sendComment() async {
    final isValid = _formKey.currentState!.validate();
    final name = user!.displayName;


    var res = await  userRef.where('userid', isEqualTo: user!.uid).get();



      _formKey.currentState!.save();

      var doc = userRef.doc('photoURL');
      doc.set({
        'comment' : comments,
      });



  }






  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body:  Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Form(
                  key: _formKey,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(top: 50),
                            child: TextFormField(
                                style: TextStyle(
                                  color: Colors.white,
                                ),
                                decoration: InputDecoration(
                                    labelText: "Leave a Comment..",
                                    labelStyle: TextStyle(
                                      color: Colors.white,
                                    )
                                ),
                                onSaved: (value) {
                                  comments = value!;
                                }
                            ),
                          )

                        ],
                      )
                  ),

              ElevatedButton.icon(
                  onPressed: sendComment,
                  icon: Icon(Icons.send,
                      color: Colors.white,
                  ),
                  label: Text(
                    "Send"
                  ))
            ],
          )
      ),
    );
  }
}

【问题讨论】:

  • 你分享的代码有什么问题?当您在调试器中单步执行代码时,哪一行没有按照您的预期执行?
  • problem ist in the code,i embedded the code for better understanding, im 询问我可以使用显示图像实现评论部分的方法或功能,评论应该与firestore中的特定图像文档一起添加,就像我尝试创建一个单独收集评论,但将为数据库中的每个图像获取评论,我正在尝试保存和检索特定图像的评论数据,就像我们在 instagram 中看到和使用的一样!
  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: firebase flutter google-cloud-firestore


【解决方案1】:

这是一个非常广泛的用例,老实说有点过于宽泛,无法在 Stack Overflow 上回答。我建议专注于更具体、更具体的问题。

例如,您在评论中提到:

我尝试为评论创建一个单独的集合,但是将为数据库中的每个图像获取评论,我正在尝试保存和检索特定图像的评论数据

要允许仅读取特定图像上的 cmets,您需要将数据库中的每个评论与图像相关联。两种最常见的方法是:

  1. 为顶级集合中的每个图像创建一个文档,然后在该文档下为该特定图像上的 cmets 创建一个子集合。
  2. 创建单个顶级 cmets 集合,并将图像的 ID 存储在每个评论文档中。

【讨论】:

  • 好的去试试!
  • 第一个接近者工作了!
猜你喜欢
  • 2015-10-11
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多