CodeBlanks Logo Icon CodeBlanks

Box and put/get

Learn put and get on a Hive box.

put and get

You store a value with box.put('key', value) and read it with box.get('key'). The key is always a string; the value can be anything from primitive types to lists and maps. put is an asynchronous operation.

await box.put('theme', 'dark');
final theme = box.get('theme');

Default value

If the key is not in the box, get returns null. You handle this safely with the defaultValue parameter. This is useful when settings have not been saved yet on first app launch.

final theme = box.get('theme', defaultValue: 'light');

Practice Store and read a value

Open a box named 'settings'. Put 'dark' under the key 'theme'. Read the value with the same key and print it.

Starter code

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

void main() async {
  Hive.init('hive_data');
  final box = await Hive.openBox('settings');
  // 'theme' anahtarına 'dark' değerini koy
  // 'theme' değerini yazdır
  await box.close();
}

Sample solution

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

void main() async {
  Hive.init('hive_data');
  final box = await Hive.openBox('settings');
  await box.put('theme', 'dark');
  print(box.get('theme'));
  await box.close();
}

Expected output

dark

Questions and answers

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

1 What does box.get('theme') return if the key is not in the box?

  • 0
  • Empty string
  • Throws an error
  • null Correct answer

Explanation: If the key is missing, get returns null by default; if defaultValue is provided, it returns that.

2 Store a value

Question
await box.____;
Answer
await box.put('theme', 'dark');

Explanation: To store a value you use put; the first parameter is the key, the second is the value.

3 put and get parts

Term Meaning
put Stores a value
get Reads a value
defaultValue Returned when key is missing
delete Deletes a value

All lessons in Advanced