hive icon indicating copy to clipboard operation
hive copied to clipboard

doesn't persists custom objects after restart

Open mahbubsabuj opened this issue 3 years ago • 0 comments

i'm sotring custom List<object> this way put(k, v) in a hive box. after putting the data i'm able to access it. but when i restart the app data disappears.

custom object class:

@HiveType(typeId: 3)
class FakePerson {
  @HiveField(0)
  final String firstName;
  @HiveField(1)
  final String lastName;
  @HiveField(2)
  final String email;
  @HiveField(3)
  final String gender;
  @HiveField(4)
  final String phoneNumber;
  FakePerson({
    required this.firstName,
    required this.lastName,
    required this.email,
    required this.gender,
    required this.phoneNumber,
  });

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'first_name': firstName,
      'last_name': lastName,
      'email': email,
      'gender': gender,
      'phone_number': phoneNumber,
    };
  }

  factory FakePerson.fromMap(Map<String, dynamic> map) {
    return FakePerson(
      firstName: map['first_name'] as String,
      lastName: map['last_name'] as String,
      email: map['email'] as String,
      gender: map['gender'] as String,
      phoneNumber: map['phone_number'] as String,
    );
  }

  String toJson() => json.encode(toMap());

  factory FakePerson.fromJson(String source) =>
      FakePerson.fromMap(json.decode(source) as Map<String, dynamic>);
}

in main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final directory = await getApplicationSupportDirectory();
  Hive.initFlutter(directory.path);
  Hive.registerAdapter(FakePersonAdapter());
  await Hive.openBox<List<FakePerson>>('fake_person_list',
      path: directory.path, crashRecovery: true);
  // await BoxCollection.open('APP_DB', {'FAKE_PERSON_LIST'},
  //     path: directory.path);
  runApp(
    const MyApp(),
  );
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late final fakePersonBox;
  Future<List<FakePerson>> getFakePersonList() async {
    final String response = await rootBundle.loadString('assets/users.json');
    final data = await json.decode(response);
    return List<FakePerson>.from(
      data.map<FakePerson>(
        (dynamic person) => FakePerson.fromMap(person),
      ),
    );
  }

  void insert() async {
    List<FakePerson> fakePersonList = await getFakePersonList();
    fakePersonBox.put('latest', fakePersonList);
    debugPrint(fakePersonBox.get('latest')[0].firstName);
    debugPrint(fakePersonBox.toMap().toString());
  }

  @override
  void initState() {
    debugPrint("Initstate Called");
    fakePersonBox = Hive.box<List<FakePerson>>('fake_person_list');
    insert();
    super.initState();
  }

  @override
  void dispose() {
    fakePersonBox.close();
    super.dispose();
  }
}

after reboot if i comment out first 2 line inside insert() function i get the following exception, Exception has occurred._CastError (type 'List<dynamic>' is not a subtype of type 'List<FakePerson>?' in type cast)

mahbubsabuj avatar Sep 06 '22 12:09 mahbubsabuj