Home > database >  Flutter - How to add and retrieve data to/from hive?
Flutter - How to add and retrieve data to/from hive?

Time:11-25

I know it sounds simple and I went through the example given in the documentation. Yet somehow I am unable to get it right.

This is what I have:

 void main() async {
  await Hive.initFlutter();
  //Hive.openBox('workoutBox');
  runApp(const MyApp());
}
...

Next Screen:

var box;
...

Trying to add to the box

Future<void> _save() async{
// save doc id somewhere
final Id = doc.id;

//box = await Hive.openBox('workoutBox');
box.put("Id", Id);
}

Trying to retrieve in another function:

var someId = box.get("Id");

Current error: get was called on null

My confusion is, where/how do you declare, open and retrieve from the box in this situation?

CodePudding user response:

It seems you are forgetting to initialize a Box param and assign the value returned by the openBox function to it.

After Hive initialization you should have something like this:

Box<myValue> boxValue = await Hive.openBox("myKey");

Important: the retrieval method will dependend based on what you need to do and, more importantly, how you saved your data in the first place.

Let's say you saved data like this:

await boxValue.add(value);

By adding data like this, the key assigned to the value will be an auto-incremented one, so that trying to retrieve it with a specific key that never was assigned in the first place will fail.

If you did add the data like this:

await boxValue.put("myKey", value);

then you will be able to successfully fetch it using the intended key.

CodePudding user response:

You can do the following:

void main() async {
  await Hive.initFlutter();
  await Hive.openBox('workoutBox'); //<- make sure you await this
  runApp(const MyApp());
}

...

_save() { // <- can be a synchronous function
  final box = Hive.box('workoutBox'); //<- get an already opened box, no await necessary here
  // save doc id somewhere
  final Id = doc.id;
  box.put("Id", Id);
}

  • Related