build static method

Future<HydratedStorage> build({
  1. required Directory storageDirectory,
  2. HydratedCipher? encryptionCipher,
})

Returns an instance of HydratedStorage. storageDirectory is required.

For web, use webStorageDirectory as the storageDirectory

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:path_provider/path_provider.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  HydratedBloc.storage = await HydratedStorage.build(
    storageDirectory: kIsWeb
        ? HydratedStorage.webStorageDirectory
        : await getTemporaryDirectory(),
  );
  runApp(App());
}

With encryptionCipher you can provide custom encryption. Following snippet shows how to make default one:

import 'package:crypto/crypto.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';

const password = 'hydration';
final byteskey = sha256.convert(utf8.encode(password)).bytes;
return HydratedAesCipher(byteskey);

Implementation

static Future<HydratedStorage> build({
  required Directory storageDirectory,
  HydratedCipher? encryptionCipher,
}) {
  return _lock.synchronized(() async {
    if (_instance != null) return _instance!;
    // Use HiveImpl directly to avoid conflicts with existing Hive.init
    // https://github.com/hivedb/hive/issues/336
    hive = HiveImpl();
    Box<dynamic> box;

    if (storageDirectory == webStorageDirectory) {
      box = await hive.openBox<dynamic>(
        'hydrated_box',
        encryptionCipher: encryptionCipher,
      );
    } else {
      hive.init(storageDirectory.path);
      box = await hive.openBox<dynamic>(
        'hydrated_box',
        encryptionCipher: encryptionCipher,
      );
      await _migrate(storageDirectory, box);
    }

    return _instance = HydratedStorage(box);
  });
}