flutter中如何在firebasefirestore中添加记录时获取用户文档id

r7knjye2  于 2023-06-24  发布在  Flutter
关注(0)|答案(2)|浏览(119)

我创建了一个基本的应用程序添加后,我需要存储后id
我不想用我自己的方式生成任何id,以知道是否有另一种方式
这是我的代码添加职位

IconButton(onPressed: () async {
                    await FirebaseFirestore.instance.collection("posts").doc().set(
                        {
                          'message':txtpost.text,
                          'postby':FirebaseAuth.instance.currentUser!.email,
                          'posttime':Timestamp.now(),
                          'likes':[],
                          'postid':?????// here how to get current document id
                        });
                    print('Post Added Successfully...');
                    txtpost.clear();

                  }, icon: Icon(Icons.send))
nx7onnlm

nx7onnlm1#

下面的代码应该可以做到这一点:

IconButton(
        onPressed: () async {
          final documentRef = FirebaseFirestore.instance.collection('posts').doc();
          final documentId = documentRef.id;
              await documentRef.set(
                  {
                    'message':txtpost.text,
                    'postby':FirebaseAuth.instance.currentUser!.email,
                    'posttime':Timestamp.now(),
                    'likes':[],
                    'postid': documentId
                  });
              print('Post Added Successfully...');
              txtpost.clear();
        },
        icon: Icon(Icons.send),
      ),

每个文档引用都带有一个ID。您可以获取此ID并将其设置为post ID。

rqmkfv5c

rqmkfv5c2#

当没有提供路径时,可以使用调用函数 doc 时自动生成的ID。
因此,您可以首先获取文档的引用,然后存储帖子。
下面是代码的样子:

IconButton(
            onPressed: () async {
              final docRef =
                  FirebaseFirestore.instance.collection('posts').doc();
              final docId = docRef.id;
              docRef.set(
                {
                  'message': txtpost.text,
                  'postby': FirebaseAuth.instance.currentUser!.email,
                  'posttime': Timestamp.now(),
                  'likes': [],
                  'postid': docId
                },
              );
              print('Post Added Successfully...');
              txtpost.clear();
            },
            icon: Icon(Icons.send),
          ),

相关问题