androidflutterdartflutter-hive

How to Backup and Restore Flutter Hive Data using JSON format?


I want to create a password manager using Hive and have an option to backup the data or send the backup file to another device to copy the data to a new device. I was able to backup my data to a JSON file successfully.

My model class:

import 'package:hive/hive.dart';
part 'password.g.dart';

@HiveType(typeId: 0)
class Password extends HiveObject {
  @HiveField(0)
  late String website;
  @HiveField(1)
  late String email;
  @HiveField(2)
  late String pd;

Map<String, String> toJson() => {
    'website': website,
    'email': email,
    'pd': pd,
  };
}

To create a backup I used:

Future<void> createBackup() async {
    if (Hive.box<Password>('passwords').isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('No Password Stored.')),
      );
      return;
    }
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Creating backup...')),
    );
    Map<String, dynamic> map = Hive.box<Password>('passwords')
        .toMap()
        .map((key, value) => MapEntry(key.toString(), value));
    String json = jsonEncode(map);
    Directory dir = await _getDirectory();
    String formattedDate = DateTime.now()
        .toString()
        .replaceAll('.', '-')
        .replaceAll(' ', '-')
        .replaceAll(':', '-');
    String path = '${dir.path}$formattedDate.json';
    File backupFile = File(path);
    await backupFile.writeAsString(json);
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Backup saved in folder Passman')),
    );
  }

  Future<Directory> _getDirectory() async {
    const String pathExt = '/Passman/';
    Directory newDirectory = Directory('/storage/emulated/0/' + pathExt);
    if (await newDirectory.exists() == false) {
      return newDirectory.create(recursive: true);
    }
    return newDirectory;
  }

Running this code gave me a .json backup file in a /Passman/ folder in root but now I have no idea how to use that file to restore the data back to the Hive.


Solution

  • I was able to restore from the backup I created using the code below. I used this package.

    Future<void> restoreBackup() async {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Restoring backup...')),
    );
    FilePickerResult? file = await FilePicker.platform.pickFiles(
      type: FileType.any,
    );
    if (file != null) {
      File files = File(file.files.single.path.toString());
      Hive.box<Password>('passwords').clear();
      Map<String, dynamic> map = jsonDecode(await files.readAsString());
      for (var i = 0; i < map.length; i++) {
        Password password = Password.fromJson(i.toString(), map);
        Hive.box<Password>('passwords').add(password);
      }
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Restored Successfully...')),
      );}
    }