The introduction of
> > < span class = "font-size: 14px! Important; line-height: 20px! Important; ^0.7.0+2 // Annotation parser, automatically generated Adapter build_runner: ^1.10.0Copy the code
Initialize the
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
Hive.initFlutter('hive_db'); // ApplicationDocumentDir is a subdirectory in the flutter project, and the path to the generated boxes file is simple to useCopy the code
// 1. Create a box. Box is the equivalent of a database table concept. Each box is kept in a separate file. Var boxName = 'test"; OpenBox <String>(boxName); Var box = hive. box(boxName); / / get the boxif(box. IsOpen){// Check whether the box is enabled // add box.'key'.'value'); // Store key-value pairs Map<String, String> entries = {'a':'aaa'.'b':'bbb'}; box.putAll(entries); PutAt (0,'ccc'); // Associate [value] with the NTH key. If the key does not exist, raise the exception box.add('ddd'); // Save [values] List<String> values = []; box.addAll(values); // Store arrays with auto-increment keysprint('box.length = ${box.length}'); Var v1 = box. Get ();'key', defaultValue: ' '); Var v2 = box. GetAt (2); Var list= box. Values; Var keys= box. Keys; Var lists= box. ValuesBetween (startKey: 1, endKey: 3); // Delete box. Delete ('key'); // Delete a single box.deleteall (keys.tolist ().sublist(3)); // Delete multiple boxes. DeleteAt (0); // Delete box. Clear () in the specified position; / / to empty box. The close (); / / close}Copy the code
Custom type data
1. Define the class
import 'package:hive/hive.dart';
part 'test_info.g.dart';
@HiveType(typeId: 0)
class TestInfo extends HiveObject{
@HiveField(0)
String name;
TestInfo(this.name);
}Copy the code
2. Run $flutter packages pub run build_runner build to generate an adapter
Register 3.
Hive.registerAdapter(TestInfoAdapter()); When accessing a custom data type, you need to register the corresponding Aapter firstCopy the code
Use 4.
var box = Hive.box(boxName); Box box. Add (TestInfo()'aaa');
Copy the code