FirebaseFirestore.instanceFor constructor

FirebaseFirestore.instanceFor({
  1. required FirebaseApp app,
  2. String databaseId = DatabaseId.defaultDatabaseId,
  3. Settings? settings,
})

Returns the instance of app for databaseId, creating it at the first call. Nothing is sent or opened until the instance is used.

settings apply when the instance is created. Asking again for the same instance with different settings throws a StateError: terminate the instance first to get one with other settings.

Implementation

factory FirebaseFirestore.instanceFor({
  required FirebaseApp app,
  String databaseId = DatabaseId.defaultDatabaseId,
  Settings? settings,
}) {
  final String? projectId = app.options.projectId;
  if (projectId == null) {
    throw ArgumentError(
      'FirebaseOptions.projectId must be set to use Firestore',
    );
  }
  final String key = _keyFor(app.name, databaseId);
  final FirebaseFirestore? existing = _instances[key];
  if (existing != null && identical(existing.app, app)) {
    if (settings != null && settings != existing.settings) {
      throw StateError(
        'FirebaseFirestore.instanceFor() has already been called with different '
        'settings for this app and database. Call it without settings to '
        'get the existing instance, or terminate() that instance first.',
      );
    }
    return existing;
  }
  // An instance of another FirebaseApp object with the same name: that app
  // was deleted (names are unique among live apps) and its delete event,
  // which is delivered asynchronously, has not terminated the instance yet.
  existing?._terminateQuietly();

  final FirebaseFirestore firestore = FirebaseFirestore._(
    app,
    DatabaseId.forDatabase(projectId, databaseId),
    settings ?? Settings(),
  );
  _instances[key] = firestore;
  firestore._deleteSubscription = app.onDeleteApp.listen(
    (_) => firestore._terminateQuietly(),
  );
  return firestore;
}