I am currently using Hive for a flutter app. Im getting an error of "The following HiveError was thrown building SaveBtn(dirty, state: _SaveBtnState#f8e25): There is already a TypeAdapter for typeId 0."
I have tried reinstalling the app on the emulator multiple times and did flutter clean too.
Main.dart
Future<void> main() async {
await Hive.initFlutter();
// if (!Hive.isAdapterRegistered(0)) {
Hive.registerAdapter(ProductAdapter());
// }
boxProducts = await Hive.openBox<Product>('productsBox');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
home: CodeEntryPage(),
);
}
}
Product.dart
import 'package:hive/hive.dart';
part 'Product.g.dart';
@HiveType(typeId: 1)
class Product {
@HiveField(0)
final int productCode;
@HiveField(1)
final String productPrice;
@HiveField(2)
final String customerName;
@HiveField(3)
final String customerNumber;
Product({
required this.productCode,
required this.productPrice,
required this.customerName,
required this.customerNumber,
});
Map<String, dynamic> toMap() {
return {
'productCode': productCode,
'productPrice': productPrice,
'customerName': customerName,
'customerNumber': customerNumber,
};
}
// Implement toString to make it easier to see information about
// each dog when using the print statement.
@override
String toString() {
return 'Dog{productCode: $productCode, productPrice: $productPrice, customerName: $customerName},customerNumber: $customerNumber}';
}
}
Product.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'Product.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class ProductAdapter extends TypeAdapter<Product> {
@override
final int typeId = 0;
@override
Product read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Product(
productCode: fields[0] as int,
productPrice: fields[1] as String,
customerName: fields[2] as String,
customerNumber: fields[3] as String,
);
}
@override
void write(BinaryWriter writer, Product obj) {
writer
..writeByte(4)
..writeByte(0)
..write(obj.productCode)
..writeByte(1)
..write(obj.productPrice)
..writeByte(2)
..write(obj.customerName)
..writeByte(3)
..write(obj.customerNumber);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ProductAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
Here is the error log:
HiveError: There is already a TypeAdapter for typeld 0.
See also: https://flutter.dev/docs/testing/errors