Home > Mobile >  Problem with Hive while saving the information
Problem with Hive while saving the information

Time:01-04

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.)

CodePudding user response:

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

CodePudding user response:

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 :

    List<HiveCleanEntity> 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>() ?? [];

  • Related