clearPersistence method
Clears the persistent storage of this instance: the local SQLite database with the cached documents and the pending writes. Does nothing when the instance uses memory persistence.
Must be called after terminate. While the instance is running the returned future fails with a FirestoreException with code FirestoreErrorCode.failedPrecondition. Create a new instance with the same app and database to start again with an empty cache.
Note: clearPersistence is primarily intended to help write reliable tests that use Cloud Firestore. It uses an efficient mechanism for dropping existing data but does not attempt to securely overwrite or otherwise make cached data unrecoverable. For applications that are sensitive to the disclosure of cached data in between user sessions, we strongly recommend not enabling persistence at all.
It also fails with FirestoreErrorCode.failedPrecondition when a newer instance of the same app and database is already running on that cache.
await firestore.terminate();
await firestore.clearPersistence();
Implementation
Future<void> clearPersistence() async {
if (_terminatedBeforeStart && _clientOrNull == null) {
// Terminated before its first use: start a client only to find and delete the cache files.
final FirestoreClient started = _clientOrNull = _start!(_settings);
await started.shutdown();
}
final FirebaseApp? app = _app;
if (client.isTerminated &&
app != null &&
FirestoreMultiDbComponent.hasInstance(app.name, databaseId)) {
// This instance was terminated and a newer one has the same cache open: deleting the files under it would
// detach it from its cache without any error.
throw FirestoreException(
message:
'Persistence cannot be cleared while another firestore instance of the same app and database is running.',
errorCode: FirestoreErrorCode.failedPrecondition,
);
}
await client.clearPersistence();
}