skip to Main Content

Wanna make function which will save the information after clicking the buttom (Save)

But Hive gives error…Screen of VS

Error is in this line:

static Box notes = Hive.box(HiveKeys.notesKey);

Exception has occurred.
HiveError (HiveError: The box "notes" is already open and of type Box.)

2

Answers


  1. First of all you can not directly type hive data into a specific model. You need to get data from the box as dynamic and then cast that data to desired type, and the second thing is it seems that you have already opened this box somewhere in your code. It would be nice if you can share the code where you have opened hive box

    Login or Signup to reply.
  2. If you want to store data in list form then please follow below step

    • Step 1: put in main.dart file

    await Hive.openBox<List>("hiveTable");

    • Step 2: make a model class that contains the adapter of the hive

       part 'hive_clean_entity.freezed.dart';
       part 'hive_clean_entity.g.dart';
       @freezed
       @HiveType(typeId: 6, adapterName: "ContactCleanHiveAdapter")
       @freezed
       class HiveCleanEntity with _$HiveCleanEntity {
         const factory HiveCleanEntity({
           @HiveField(0) @Default("") String contactId,
           @HiveField(1) @Default("") String displayName,
           @HiveField(2) @Default("") String givenName,
           @HiveField(3) @Default("") String phoneNumber,
         }) = _HiveCleanEntity;
      
         factory HiveCleanEntity.initial() => const HiveCleanEntity(
               contactId: "",
               displayName: "",
               givenName: "",
               phoneNumber: "",
             );
       }
      

    like this – you can pass typeId of your choice

    • Step 3: run the build_runner command so they generate 2 file of model dto

      flutter pub run build_runner watch –delete-conflicting-outputs

    • Step 4: Now open box where you want to store data :

      ListHiveCleanEntity putlist = [];

            HiveCleanEntity hiveCleanEntity = 
             HiveCleanEntity(
                       contactId: “1”,
                       displayName: "2",
                       givenName: "xyz",
                       phoneNumber:”+91”);
      
               putlist.add(hiveCleanEntity);
      
             final cleanContactBox = Hive.box<List>("hiveTable");
             cleanContactBox.put("subTable",putlist);
      
    • Step 5: getting data into local storage

      final list = cleanContactBox.get("subTable")?.cast<HiveCleanEntity>() ?? [];

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search