3

I have added a new key/value pair inside my Hive box :

 await Hive.box("myBox").put("myKey", "myValue");

And I have a specific method, let's call it specificMethod(), that I want to execute every time I change the value of that key or to get notified when it's deleted from the box.

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35

1 Answers1

2

You can listen/watch specific key changes as a Stream with the watch() like this:

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  void initState() {
    Hive.box("myBox").watch(key: "myKey").listen((event) {
      print("BoxEvent | key: ${event.key}, value: ${event.value}, deleted: ${event.deleted},");
      specificMethod(event.value);
    });
    super.initState();
  }

like the example, you can get the actual key, value, deleted ( returns a bool).

And every time it's changed the specificMethod() method will execute.

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35