You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Firestore删除文档函数是否抛出未找到异常及返回删除状态?

Flutter Firestore Delete: Exceptions & Return Details

Hey there! Let's tackle your questions about deleting Firestore documents in Flutter—super common stuff, so glad you asked.

1. Does deleting a non-existent document throw a "not found" exception?

Short answer: No, it doesn't. Firestore treats deleting a document that already doesn't exist as a successful operation. The end result (document not present) matches what you intended, so there's no error thrown.

For example, this code will complete without any exceptions, even if the document non-existent-user never existed:

try {
  await FirebaseFirestore.instance
      .collection('users')
      .doc('non-existent-user')
      .delete();
  print("Delete operation completed successfully");
} catch (e) {
  // This block won't run for a non-existent document
  print("Error deleting document: $e");
}

2. Does the delete function return info about missing documents or failed operations?

The delete() method returns a Future<void>, which means it doesn't directly return metadata about whether the document existed or if the deletion "actually" happened.

To get that context, you have two main options:

  • Check document existence first: Fetch the document snapshot before deleting to confirm it exists. This is straightforward for most cases:
    final docRef = FirebaseFirestore.instance.collection('users').doc('user123');
    final snapshot = await docRef.get();
    
    if (snapshot.exists) {
      await docRef.delete();
      print("Document deleted successfully");
    } else {
      print("Document does not exist—no deletion performed");
    }
    
  • Use a transaction for safety: If you're worried about concurrent modifications (e.g., someone deleting the document between your check and delete call), use a transaction to atomically check and delete:
    try {
      await FirebaseFirestore.instance.runTransaction((transaction) async {
        final snapshot = await transaction.get(docRef);
        if (!snapshot.exists) {
          throw Exception("Document not found—cannot delete");
        }
        transaction.delete(docRef);
      });
      print("Document deleted via transaction");
    } catch (e) {
      print("Transaction error: $e");
    }
    

One important note: While non-existent documents don't trigger exceptions, permission errors or other Firebase issues will throw a FirebaseException. Always wrap your delete calls in a try/catch block to handle those edge cases.

内容的提问来源于stack exchange,提问作者ניב

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 08:12:53