Flutter Firestore使用自定义ID添加新文档

Sha*_*hra 5 dart flutter google-cloud-firestore

如何使用Dart和Flutter添加具有自定义ID的新文档?

PS:我可以使用此代码将新文档添加到集合中,但其ID会随机设置

postRef.add(data);

postRefCollectionReferencedataMap<String, dynamic>

Cop*_*oad 10

2021 年更新:

不要使用,而是在文档上add使用。set

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'));
Run Code Online (Sandbox Code Playgroud)


Sha*_*hra 8

您可以使用setfunction代替add

这是完整的代码:

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.document(postID).setData(postData);
Run Code Online (Sandbox Code Playgroud)

希望对任何人有帮助。