3

How to create hive object that includes an id field with auto increment integer value?

This is my hive object class and id always is -1. How should I fix it?


import 'package:hive_flutter/adapters.dart';
part  'reminder.g.dart';

@HiveType(typeId : 2 )
class Reminder extends HiveObject {
  int id = -1;
  @HiveField(0)
  String title = '';
  @HiveField(1)
  String body = '';
  @HiveField(2)
  String dateFancyString = '' ;
  @HiveField(3)
  String timeFancyString = '' ;
  @HiveField(4)
  DateTime dateTime = DateTime.now();
}
padaleiana
  • 955
  • 1
  • 14
  • 23
Ghazal
  • 123
  • 2
  • 9

1 Answers1

1

According to Hive documentation:

add(E value) → Future<int> Saves the value with an auto-increment key.

So you don't need the 'id' field, because the hive 'add' method has a built-in auto-increment mechanism and every hive object that is added to the box with the 'add' method has a unique id itself.

@HiveType(typeId : 2 )
class Reminder extends HiveObject {
  @HiveField(0)
  String title = '';
  @HiveField(1)
  String body = '';
  @HiveField(2)
  String dateFancyString = '' ;
  @HiveField(3)
  String timeFancyString = '' ;
  @HiveField(4)
  DateTime dateTime = DateTime.now();
}

then if you need the id of an object (as we know them as 'key' in Hive) you should use key properties of your Hive object.

If you want to read more please check Flutter documentation:

Hive Box: https://pub.dev/documentation/hive/latest/hive/Box-class.html

Hive Object: https://pub.dev/documentation/hive/latest/hive/HiveObject-class.html

Amir Arani
  • 11
  • 5