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

时间:2018-12-04 04:17: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 //
});
}

如何获取此随机生成的文档ID? 谢谢您的帮助

5 个答案:

答案 0 :(得分: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
      });

文档ID

documentReference.documentID

答案 1 :(得分:2)

您可以通过调用ref.documentID来获取ID

答案 2 :(得分:1)

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,
  });

现在您可以获取文档ID:

 docRef.documentID 

答案 3 :(得分:0)

cloud_firestore软件包的v0.14.0起:

已弃用:不建议使用id为id的documentID。

所以而不是

startup.cs

使用

var repository = new InMemorySagaRepository<ApiSaga>();
            services.AddMassTransit(cfg =>
            {
                cfg.AddBus(provider =>
                {
                    return Bus.Factory.CreateMediator(x =>
                    {
                        x.Saga<ProductSaga>(repository);
                    });
                });
            });

检索随机生成的文档ID。

答案 4 :(得分:0)

使用 value.Id 获取部件 documentId

 CollectionReference users = FirebaseFirestore.instance.collection('candidates');
      
      Future<void> registerUser() {
     // Call the user's CollectionReference to add a new user
         return users.add({
          'name': enteredTextName, // John Doe
          'email': enteredTextEmail, // Stokes and Sons
          'profile': dropdownValue ,//
          'date': selectedDate.toLocal().toString() ,//// 42
        })
            .then((value) =>(showDialogNew(value.id)))
            .catchError((error) => print("Failed to add user: $error"));
      }