I have created a simple app for storing data using hive and getx as state management
I have followed all the steps but even thought its showing an error like
After coding when I played ...it worked fine...but when I restart the app...it stops showing white background and an error in console....
have u forgotten register adapter...
I have registered adapter in main...eventhough getting this error
error is
Unhandled Exception: HiveError: Cannot read, unknown typeId: 32. Did you forget to register an adapter?
class TransactionController extends GetxController
{
List<TransactionModel> _transactions=[];
Box<TransactionModel> transactionbox=Hive.box('a');
List<TransactionModel> get transactions{
return _transactions;
}
TransactionController(){
_transactions=[];
for(int x=0;x<transactionbox.values.length;x )
{
var trns=transactionbox.getAt(x);
if(trns!=null)
_transactions.add(trns);
}
}
int get countlength{
return _transactions.length;
}
void addTransaction(TransactionModel transaction)
{
_transactions.add(transaction);
transactionbox.add(transaction);
update();
}
}
this is model class
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive/hive.dart';
part 'transactionmodel.g.dart';
@HiveType(typeId: 0)
class TransactionModel
{
@HiveField(0)
String id;
@HiveField(1)
String detail;
@HiveField(2)
bool isExpense;
TransactionModel({
required this.id,
required this.detail,
required this.isExpense,
});
}
this is void main
void main() async
{
WidgetsFlutterBinding.ensureInitialized();
Directory dir=await getApplicationDocumentsDirectory();
await Hive.initFlutter(dir.path);
await Hive.openBox<TransactionModel>('a');
Hive.registerAdapter<TransactionModel>(TransactionModelAdapter());
runApp(MyApp());
}
CodePudding user response:
I see a wrong thing in your code, you're trying to open the Hive box before registering the adapter, you're calling Hive.registerAdapter
after you already opened the box, change it with this:
void main() async
{
WidgetsFlutterBinding.ensureInitialized();
Directory dir=await getApplicationDocumentsDirectory();
await Hive.initFlutter(dir.path);
Hive.registerAdapter<TransactionModel>(TransactionModelAdapter()); // this should be first
await Hive.openBox<TransactionModel>('a'); // then this
runApp(MyApp());
}