I have these errors and i don't know what's the problem, it's a newly created hive data and doesn't contain any value yet. I'm trying to load it and if value = null return defaultValue
here's the code for hive load :
hiveOperation() async {
GlobalPosition globalPosition;
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
await Hive.openBox('box');
Hive.registerAdapter(GlobalPositionAdapter());
globalPosition = box.get('globalPosition');
lat = globalPosition.latitude;
lon = globalPosition.longitude;
}
this is the hive constructor :
import 'package:hive/hive.dart';
part 'storage.g.dart';
@HiveType(typeId: 1)
class GlobalPosition {
GlobalPosition({required this.latitude, required this.longitude});
@HiveField(0, defaultValue: 1.0)
double latitude;
@HiveField(1, defaultValue: 1.0)
double longitude;
}
The error when load is : [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'GlobalPosition'
I don't know how to fix it, please help me, Thank you!
CodePudding user response:
You should use defaultValue
in get
method:
globalPosition = box.get('globalPosition',defaultValue: GlobalPosition(latitude:1.0 ,longitude:1.0);