如何在Flutter中获取Firestore文档的文档ID?

26
我尝试了以下方法,但是它返回一个在Firestore中不存在的随机字符串。 我成功地使用查询快照获取了父集合的文档ID。
DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();

                    var doc_id2=doc_ref.documentID;

更多代码:我试图访问文档id时出现错误。我尝试使用await,但它会报错。

 Widget build(BuildContext context) {
        return Scaffold(
          appBar: new AppBar(
            title: new Text(
              "National Security Agency",
              style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.normal,
                  fontSize: 24.0),
            ),
            backgroundColor: Colors.redAccent,
            centerTitle: true,
            actions: <Widget>[
              new DropdownButton<String>(
                items: <String>['Sign Out'].map((String value) {
                  return new DropdownMenuItem<String>(
                    value: value,
                    child: new Text(value),
                  );
                }).toList(),
                onChanged: (_) => logout(),
              )
            ],
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
    
            },
            child: Icon(Icons.search),
          ),
    
          body: StreamBuilder (
              stream: cloudfirestoredb,
    
    
                  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) return new Text('Loading...');
    
                    return new ListView(
                      children: snapshot.data.documents.map((document) {
    
    
                        var doc_id=document.documentID;
                        var now= new DateTime.now();
                        var formatter=new DateFormat('MM/dd/yyyy');
                        String formatdate = formatter.format(now);
                        var date_to_be_added=[formatdate];
    
                        DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();
    
                       var doc_id5= await get_data(doc_ref);
    
    
                        print(doc_id);
                        
    
    
                        Firestore.instance.collection("board").document(doc_id).collection("Dates").document(doc_id5).updateData({"Date":FieldValue.arrayUnion(date_to_be_added)});
                        return cardtemplate(document['Name'], document['Nationality'], doc_id);
    
                        }).toList(),
                    );
                  },
           ),
              );
      }
9个回答

25

您需要通过id来检索该文档。

请尝试以下方式

DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();

DocumentSnapshot docSnap = await doc_ref.get();
var doc_id2 = docSnap.reference.documentID;

请确保在标记为async的函数中使用此代码,因为代码使用了await。

编辑: 回答您在评论中提出的问题

Future<String> get_data(DocumentReference doc_ref) async { 
  DocumentSnapshot docSnap = await doc_ref.get(); 
  var doc_id2 = docSnap.reference.documentID; 
  return doc_id2; 
}

//To retrieve the string
String documentID = await get_data();

编辑2:

只需将 async 添加到 map 函数中即可。

snapshot.data.documents.map((document) async {
  var doc_id=document.documentID;
  var now= new DateTime.now();
  var formatter=new DateFormat('MM/dd/yyyy');
  String formatdate = formatter.format(now);
  var date_to_be_added=[formatdate];

  DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();

  var doc_id5= await get_data(doc_ref);

  print(doc_id);

  Firestore.instance.collection("board").document(doc_id).collection("Dates").document(doc_id5).updateData({"Date":FieldValue.arrayUnion(date_to_be_added)});
  return cardtemplate(document['Name'], document['Nationality'], doc_id);
}).toList(),

请告诉我这是否可行。


我已添加了以下函数。但是我该如何从Future String实例中获取字符串?Future<String> get_data(DocumentReference doc_ref) async{ DocumentSnapshot docSnap = await doc_ref.get(); var doc_id2 = docSnap.reference.documentID; return doc_id2; } - Pruthvik Reddy
谢谢。但是我在使用await时遇到了错误。可能是因为我没有使用Future Builder。我正在使用Stream Builder并返回一个列表视图。我该怎么解决? - Pruthvik Reddy
请检查一遍。 - Abdul Malik
我猜这种方法不再适用于我了,至少对我来说是这样(我的意思是,文档ID!) - An Android
请帮我解决这个问题:-https://stackoverflow.com/questions/67941537/how-to-get-a-doc-id-which-is-random-or-unknown-in-flutter-from-firebasefirestore - GAGAN SINGH
显示剩余2条评论

12
更新后,您现在可以使用这行代码访问文档ID:
snapshot.data.docs[index].reference.id

其中,snapshot是一个QuerySnapshot。

这是一个示例。

FutureBuilder(
    future: FirebaseFirestore.instance
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .collection('addresses')
        .get(),
    builder: (context, AsyncSnapshot snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(child: CircularProgressIndicator());
      }else{return Text(snapshot.data.docs[0].reference.id.toString());}

2
最简单的解决方案 - Wisnu Wijokangko

9
  • To get the document ID in a collection:

    var collection = FirebaseFirestore.instance.collection('collection');
    var querySnapshots = await collection.get();
    for (var snapshot in querySnapshots.docs) {
      var documentID = snapshot.id; // <-- Document ID
    }
    
  • To get the document ID of a newly added data:

    var collection = FirebaseFirestore.instance.collection('collection');
    var docRef = await collection.add(someData);
    var documentId = docRef.id; // <-- Document ID
    

8

在添加文档的方式后,您可以使用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"));
  }

在这里value.id 给出了 documentId


4

document() 当你不传入任何路径调用此方法时,它会为你创建一个随机的id。

从文档中可以看到:

如果没有提供[path],则使用自动生成的ID。生成的唯一键以客户端生成的时间戳为前缀, 因此生成的列表将按时间顺序排序。

因此,如果您想获取 documentID,请执行以下操作:

var doc_ref = await Firestore.instance.collection("board").document(doc_id).collection("Dates").getDocuments();
doc_ref.documents.forEach((result) {
  print(result.documentID);
});

谢谢。我尝试在异步函数中实现它,但是在尝试返回时收到错误。我尝试使用“await”...但没有帮助。请检查我在问题中添加的代码。 - Pruthvik Reddy
这对我有用,但我能在ListView Builder中列出它们吗? - Tripping

3

你还可以进行以下操作

Firestore.instance
    .collection('driverListedRides')
    .where("status", isEqualTo: "active")
    .getDocuments()
    .then(
      (QuerySnapshot snapshot) => {
        driverPolylineCordinates.clear(),
        snapshot.documents.forEach((f) {
        
          print("documentID---- " + f.reference.documentID);
         
        }),
      },
    );

2

你好,来自2022年的我带来了 cloud_firestore: ^3.1.0,你可以通过以下方式获取uid:

首先请注意,我们不会为id存储新字段,这有点重复。相反,我们想要获取自动生成的uid,它代表唯一标识符。

模型层。

class Product {
  late final String _id;
  String get id => _id;
  set id(String value) {
    _id = value;
  }

  final String title;
  final String description;

  Product({
    required this.title,
    required this.description,
  });

  factory Product.fromJson(Map<String, dynamic> jsonObject) {
    return Product(
      title: jsonObject['title'] as String,
      description: jsonObject['description'] as String,
    );
  }
}

一个非常常见的模型,唯一特别的是id属性。

数据层。这里是获取数据的地方。

class ProductData {
  //create an instance of Firestore.
  final _firestore = FirebaseFirestore.instance;
  
  // A simple Future which will return the fetched Product in form of Object.
  Future<List<Product>> getProducts() async {
    final querySnapshot = await _firestore.collection('products').get();
    final products = querySnapshot.docs.map((e) {
      // Now here is where the magic happens.
      // We transform the data in to Product object.
      final model = Product.fromJson(e.data());
      // Setting the id value of the product object.
      model.id = e.id;
      return model;
    }).toList();
    return products;
  }
}

这就是全部内容了,希望我表达清楚了。祝编码愉快!

为了确保你理解了这个想法,我们获取下划线id。 输入图像描述


我看不出有什么真正的理由来封装 _id 字段的 getter 和 setter。Dart 并不鼓励这种做法,因为它不受 Java/C# 的限制。只需使用 late final String id。 - undefined
当然,对于这个来说,使用late变量已经足够了,但我喜欢使用IntelliJ来标注这一证据,因为它会显示不同的颜色。 - undefined
使用setter方法,您可以添加自己的自定义逻辑。 - undefined

0
  QuerySnapshot docRef = await  FirebaseFirestore.instance.collection("wedding cards").get();

print(docRef.docs[index].id);


目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

0

这是我们可以做到的其中一种方式。

QuerySnapshot snap = await FirebaseFirestore.instance
    .collection("TechnovationHomeScreen")
    .doc('List')
    .collection('Demo')
    .get();
snap.docs.forEach((document) {
  print(document.id);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接