0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flutter】FirebaseFirestoreにデータを削除する

0
Posted at
  • コレクション名: items
  • 購入済み(isChecked = true)のアイテムを一括削除する

1件削除

ドキュメントIDがわかっている場合:

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> deleteItem(String id) async {
  await FirebaseFirestore.instance
      .collection('items')
      .doc(id)
      .delete();
}

条件に合うドキュメントを一括削除
購入済みアイテムをまとめて削除する実装例

Future<void> clearCheckedItems() async {
  // 1. 条件に合うドキュメントを取得
  final checkedItems = await FirebaseFirestore.instance
      .collection('items')
      .where('isChecked', isEqualTo: true)
      .get();
  // 2. 1件ずつ削除
  for (final doc in checkedItems.docs) {
    await doc.reference.delete();
  }
}

UI から呼び出す例

void _clearChecked() {
  clearCheckedItems();
}

削除後の UI 更新
snapshots() で監視している場合、削除後は自動的にUIが更新されます。手動でsetStateする必要はありません。

stream: FirebaseFirestore.instance
    .collection('items')
    .snapshots(),

Batch Write — 大量削除時は WriteBatch を使うと効率的

final batch = FirebaseFirestore.instance.batch();
for (final doc in checkedItems.docs) {
  batch.delete(doc.reference);
}
await batch.commit();

セキュリティルール — Firestore Rules で delete 権限を設定する

// firestore.rules
match /items/{itemId} {
  allow delete: if request.auth != null;
}

まとめ
1件削除: .doc(id).delete()
条件付き削除: .where(...).get() → ループで .delete()
StreamBuilder監視中なら削除後のUI更新は自動

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?