41

How to add new document with custom id using Dart and Flutter?

PS: I can add new document to collection but its id sets randomly, using this code

postRef.add(data);

which postRef is CollectionReference and data is Map<String, dynamic>

Community
  • 1
  • 1
Shady Boshra
  • 2,521
  • 3
  • 23
  • 35

4 Answers4

59

You can use set() function instead of add().

Here's full code:

final CollectionReference postsRef = Firestore.instance.collection('/posts');

var postID = 1;

Post post = new Post(postID, "title", "content");
Map<String, dynamic> postData = post.toJson();
await postsRef.doc(postID).set(postData);

I hope that help anyone.

IAmJulianAcosta
  • 1,082
  • 2
  • 14
  • 30
Shady Boshra
  • 2,521
  • 3
  • 23
  • 35
  • Is it possible to create autoID? – Bagusflyer May 06 '20 at 07:23
  • Yes sure, you can use `await postsRef.add(postData);` that was the question really ! – Shady Boshra May 06 '20 at 12:52
  • from where do we bring '.toJson();' ?? it's not defined and would be cool instead of what i'm doing not is I take every class like Post() and map its fields into a map,, if .toJson(); work automatically would be cool,, from where can I import that ? or I just define that function like I'm already doing ? – Rageh Azzazy Feb 24 '21 at 02:37
  • @RagehElAzzazy it's a method I defined in tge class, to return a map with keys an fields I want. No difference between my code and your code, just it's a method in class. – Shady Boshra Feb 24 '21 at 10:01
  • @Shady Boshra, I did the same, thanks man, teslam ya m3allem – Rageh Azzazy Feb 26 '21 at 16:16
  • @Bagusflyer If you dont provide doc() a parameter, then its generates an auto-ID – A.Ktns Apr 07 '22 at 19:39
10

Update 2021:

Instead of using add, use set on the document.

var collection = FirebaseFirestore.instance.collection('collection');
collection 
    .doc('doc_id') // <-- Document ID
    .set({'age': 20}) // <-- Your data
    .then((_) => print('Added'))
    .catchError((error) => print('Add failed: $error'));
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
3
String uniqueCode = //Your Unique Code
DocumentReference reference = Firestore.instance.document("test/" + uniqueCode );

//Setting Data
Map<String, String> yourData;
reference.setData(yourData);
  • This works too but If its a shared database I would recommend handling the atomicity by making each transaction atomic as follows ```Firestore.instance.runTransaction((Transaction tx) async { await _firestoreRef.setData(data); }); ``` – Mahesh Jamdade May 30 '20 at 13:11
1

You can try this code to insert new Document with customID

    DocumentReference<Map<String, dynamic>> users = FirebaseFirestore
              .instance
              .collection('/users')
              .doc("MyCustomID");
          var myJSONObj = {
            "FirstName": "John",
            "LastName": "Doe",
          };
          users
              .set(myJSONObj)
              .then((value) => print("User with CustomID added"))
              .catchError((error) => print("Failed to add user: $error"));