box<E> static method

Box<E> box<E>({
  1. String name = defaultName,
  2. String? directory,
  3. String? encryptionKey,
  4. int maxSizeMiB = 5,
})

Get or open the box with name in the given directory. If no directory is specified, the default directory is used.

If the box is already open, the same instance is returned.

The encryptionKey is used to encrypt the box. If the box was already opened with a different encryption key, an error is thrown.

The maxSizeMiB is the maximum size of the box in MiB. If the box grows bigger than this, an exception is thrown. It is recommended to set this value to a small value if possible.

Implementation

static Box<E> box<E>({
  String name = defaultName,
  String? directory,
  String? encryptionKey,
  int maxSizeMiB = 5,
}) {
  final box = _openBoxes[name];
  if (box != null) {
    if (box is Box<E>) {
      return box;
    } else {
      throw ArgumentError('Box was already opened with a different type. '
          'Expected Box<${box.runtimeType}> but got Box<$E>.');
    }
  }

  final dir = directory ?? defaultDirectory;
  if (dir == null) {
    throw ArgumentError(
      'No directory specified and no default directory set.',
      'directory',
    );
  }

  final isar = Isar.open(
    name: name,
    schemas: [FrameSchema],
    directory: dir,
    engine: encryptionKey != null ? IsarEngine.sqlite : IsarEngine.isar,
    maxSizeMiB: maxSizeMiB,
    encryptionKey: encryptionKey,
    inspector: false,
  );
  final newBox = _BoxImpl<E>(isar);
  _openBoxes[name] = newBox;
  return newBox;
}