CodeBlanks Logo Icon CodeBlanks

Summary - Hive

Combine Box, put and TypeAdapter to make a settings store.

Settings store

When building a settings store, you combine box, put and TypeAdapter. First you register an adapter for the Settings class, then open a box and store the settings object. When the app reopens, you read from the box to restore the settings.

Hive.registerAdapter(SettingsAdapter());
final box = await Hive.openBox('app_settings');
await box.put('current', Settings('light'));

Practice Build a settings store

Define a Settings class (final String theme). Write a SettingsAdapter with typeId 1 and read/write methods. Register the adapter, initialize Hive, open a box named 'app_settings', put Settings('light') under key 'current', retrieve it and print the theme.

Starter code

main.dart
import 'package:hive/hive.dart';

// Settings sınıfı: final String theme

// SettingsAdapter: typeId = 1
// read ve write metodları

void main() async {
  // adapter kaydet
  // Hive'ı başlat
  // 'app_settings' box'ını aç
  // 'current' anahtarına Settings('light') koy
  // değeri al ve theme'i yazdır
}

Sample solution

main.dart
import 'package:hive/hive.dart';

class Settings {
  final String theme;
  Settings(this.theme);
}

class SettingsAdapter extends TypeAdapter<Settings> {
  @override
  final int typeId = 1;

  @override
  Settings read(BinaryReader reader) {
    return Settings(reader.readString());
  }

  @override
  void write(BinaryWriter writer, Settings obj) {
    writer.writeString(obj.theme);
  }
}

void main() async {
  Hive.registerAdapter(SettingsAdapter());
  Hive.init('hive_data');
  final box = await Hive.openBox('app_settings');
  await box.put('current', Settings('light'));
  final settings = box.get('current') as Settings;
  print(settings.theme);
  await box.close();
}

Expected output

light

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When should a TypeAdapter be registered?

  • Only on error
  • Before opening a box that contains the custom type Correct answer
  • After the box is closed
  • At the end of the main function

Explanation: The adapter must be registered before opening a box that uses the type; otherwise Hive does not recognize the type.

2 Adapter read method

Question
Settings read(BinaryReader reader) {
  return Settings(reader.____());
}
Answer
Settings read(BinaryReader reader) {
  return Settings(reader.readString());
}

Explanation: The readString method of BinaryReader reads string values; it is used in the adapter's read method.

3 Settings store parts

Term Meaning
Settings Settings model
SettingsAdapter Type converter
'app_settings' Box name
settings.theme Stored value

All lessons in Advanced