Irshad KP
Irshad KP

Reputation: 33

delete(key) function in hive flutter not working

dlete frome hive local database in flutter is not working. delete(key) is not working but deleteAt(index) is working fine

this is my code where database operations located

and i want to delete a data with the id of the data. i dont get any error its not working and if i click delete button its correctly printing id but not deleting with that id im a beginner in dart and flutter

import 'package:money_manager/functions/lists.dart';
import 'package:money_manager/models/transactions.dart';
import 'package:path_provider/path_provider.dart';

Future<void> addData(Transactions data) async {
  var dir = await getApplicationDocumentsDirectory();

   Hive.init(dir.path);

  final db = await Hive.openBox<Transactions>('transaction_db');

  await db.add(data);

  print(data);

  transactions.value.add(data);

  transactions.notifyListeners();
}

Future<void> getAllTransactions() async {
    var dir = await getApplicationDocumentsDirectory();

   Hive.init(dir.path);

  final db = await Hive.openBox<Transactions>('transaction_db');

  //await db.clear();

  transactions.value.clear();

  transactions.value.addAll(db.values);

  transactions.notifyListeners();
}

Future<void> deleteData(int index) async {

  var dir = await getApplicationDocumentsDirectory();

  Hive.init(dir.path);

  final db = await Hive.openBox<Transactions>('transaction_db');

  await db.delete(index);

  print(index);

  getAllTransactions();


}


My database model is

import 'package:hive_flutter/hive_flutter.dart';
part 'transactions.g.dart';

@HiveType(typeId: 1)
class Transactions {
  @HiveField(0)
  final int id;

  @HiveField(1)
  final String title;

  @HiveField(2)
  final int amount;

  @HiveField(4)
  final DateTime dateTime;

  @HiveField(5)
  bool isIncome;

  Transactions(
      {required this.id,
      required this.title,
      required this.amount,
      required this.dateTime,
      required this.isIncome });
}

i want to delete with @HiveField(0) final int id;

Upvotes: 1

Views: 2161

Answers (1)

nvoigt
nvoigt

Reputation: 77354

await db.add(data);

This will auto-generate a key for you. If you want to use your key, you actually have to do so:

await db.put(data.id, data);

Upvotes: 1

Related Questions