Firestore / Flutter - 如何获取文档 ID?

Han*_*nna 11 firebase flutter google-cloud-firestore

这是我的代码

Future _save() async {

final StorageReference storageRef = FirebaseStorage.instance.ref().child('product/'+nameController.text+'.jpg');
final StorageUploadTask task = storageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await task.onComplete;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
StorageMetadata created = await taskSnapshot.ref.getMetadata();

Firestore.instance.collection('product').document()
    .setData({
  'name': nameController.text,
  'price': int.tryParse(priceController.text),
  'description': descriptionController.text,
  'creator': widget.user.uid,
  'created': DateTime.fromMillisecondsSinceEpoch(created.creationTimeMillis, isUtc: true).toString(),
  'modified': DateTime.fromMillisecondsSinceEpoch(created.updatedTimeMillis, isUtc: true).toString(),
  'url': downloadUrl,
  'id': //I want to set document Id here //
});
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到这个随机生成的文档的 ID?感谢您的帮助

die*_*per 12

之后collection您可以添加一个document并收到DocumentReference.

  final docRef = await Firestore.instance.collection('product').add({
    'name': nameController.text,
    'price': int.tryParse(priceController.text),
    'description': descriptionController.text,
    'creator': widget.user.uid,
    'created': DateTime.fromMillisecondsSinceEpoch(created.creationTimeMillis, isUtc: true).toString(),
    'modified': DateTime.fromMillisecondsSinceEpoch(created.updatedTimeMillis, isUtc: true).toString(),
    'url': downloadUrl,
  });
Run Code Online (Sandbox Code Playgroud)

现在您可以获取文档 ID:

 docRef.documentID 
Run Code Online (Sandbox Code Playgroud)


Cen*_*MUR 6

你这样做

DocumentReference documentReference = Firestore.instance.collection('product').document();    
documentReference.setData({
        'name': nameController.text,
        'price': int.tryParse(priceController.text),
        'description': descriptionController.text,
        'creator': widget.user.uid,
        'created': DateTime.fromMillisecondsSinceEpoch(created.creationTimeMillis, isUtc: true).toString(),
        'modified': DateTime.fromMillisecondsSinceEpoch(created.updatedTimeMillis, isUtc: true).toString(),
        'url': downloadUrl,
        'id': documentReference.documentID
      });
Run Code Online (Sandbox Code Playgroud)

文件编号

documentReference.documentID
Run Code Online (Sandbox Code Playgroud)


Mat*_*ias 5

cloud_firestore包 v0.14.0 起:

已弃用:documentID 已被弃用,取而代之的是 id。

所以而不是

ref.documentId
Run Code Online (Sandbox Code Playgroud)

使用

ref.id
Run Code Online (Sandbox Code Playgroud)

检索随机生成的文档 ID。