pirekare
pirekare

Reputation: 171

Return new document id and use it again with one button

I am making a chat page in part of my application. There is a field in the document that recording members, user id and timestamp. Also in the same document, there is a sub-collection that recording messages.

There is FloatingActionButton that opens a form to write title and text. My problem starts after here.

These codes are for onPress within the form.

onPressed: () async {
                    if (_sohbetFormu.currentState.validate()) {
                      var docId;
                      var refOne = FirebaseFirestore.instance
                          .collection("conversations");
                      await refOne.add({
                        "displayMessage": _textControllerTitle.text,
                        "members": _currentUid,
                      }).then((value) => docId = FieldPath.documentId);
                      _textControllerTitle.text = "";
                      var refTwo = FirebaseFirestore.instance
                          .collection("conversations/$docId/messages");
                      await refTwo.add({
                        "senderId": _currentUid,
                        "message": _textControllerText.text,
                        "timeStamp": DateTime.now(),
                      });
                      _textControllerText.text = "";
                      Navigator.pop(context);
                    }
                  },

First Problem: I cant use same document Id for sub-collection and information field. I tried to use FieldPath.documentId but it didn't work. FieldPath.documentId didn't return any id.

Second Problem You see "members" in codes. It should be array and record members. But it's String at the moment. How can i change it to array?

Upvotes: 1

Views: 53

Answers (1)

pirekare
pirekare

Reputation: 171

I solved problems.

At first one: I changed FieldPath.documentId to

.then((value) => docId = value.id);

At second one: I changed "message": _textControllerText.text, to

"members": FieldValue.arrayUnion(["$_currentUid"]),

I didn't delete the post just because it might work for others

Upvotes: 1

Related Questions