rahul  Kushwaha
rahul Kushwaha

Reputation: 2819

How to delete all the boxes in the hive in flutter?

I am using Hive to store the data locally, but the boxes are created dynamically throughout the apps and don't know how many boxes are there in total.

I want to delete all the boxes, whether open or closed, when the user presses the reset button.

So far, I could delete all open boxes or the particular box but not all.

Is there is a way to do that? Or is there any way to open all the boxes at once?

Upvotes: 1

Views: 6287

Answers (3)

I created this extension:

import 'dart:async';
import 'dart:io';

import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;

extension on HiveInterface {
  /// Get a name list of existing boxes
  FutureOr<List<String>> getNamesOfBoxes() async {
    final appDir = await getApplicationDocumentsDirectory();
    var files = appDir.listSync();
    var _list = <String>[];

    files.forEach((file) {
      if (file.statSync().type == FileSystemEntityType.file 
        && p.extension(file.path).toLowerCase() == '.hive') {
        _list.add(p.basenameWithoutExtension(file.path));
      }
    });
    print('Current boxes: $_list');
    return _list;
  }
  /* ---------------------------------------------------------------------------- */
  /// Delete existing boxes from disk
  void deleteBoxes() async {
    final _boxes = await this.getNamesOfBoxes();
    if (_boxes.isNotEmpty) _boxes.forEach((name) => this.deleteBoxFromDisk(name));
  }
}

Upvotes: 5

rahul  Kushwaha
rahul Kushwaha

Reputation: 2819

As of now, I have to keep track of the boxes by again creating the box to store all the box information, and delete the box by reading the number of boxes stored and then resetting the box info also.

Upvotes: 0

If you want to close all open boxes

Hive.close();

If you want to delete all currently open boxes from disk

Hive.deleteFromDisk();

Upvotes: 4

Related Questions