hive icon indicating copy to clipboard operation
hive copied to clipboard

data in hive boxes are deleted after a hot restart or close the app

Open kivocsa99 opened this issue 2 years ago • 4 comments

Steps to Reproduce

the problem is that Hive acting unexpectedly , and when the app closes or i restart it all the data in the box are cleared .

I don't know if I am doing something wrong but I followed the docs as they say :

1- registered the adapter

2- opened the box

3- called it in a widget

Code sample

main.dart :


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
  await Firebase.initializeApp();
  await Hive.initFlutter();
  Hive.registerAdapter(CredentialsModelAdapter());
  Hive.registerAdapter(DoctorModelAdapter());
  Hive.registerAdapter(DuserModelAdapter());
  Hive.registerAdapter(DoctorAppointmentsAdapter());
  Hive.registerAdapter(AppointmentStatusesAdapter());
  Hive.registerAdapter(AccountTypeAdapter());
  Hive.registerAdapter(UserAdapter());

  await Hive.openBox<CredentialsModel>("cred");
  await Hive.openBox<DuserModel>("doctor");
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);
  final _appRouter = app_router.AppRouter();
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: "x",
      debugShowCheckedModeBanner: false,
      routerDelegate: _appRouter.delegate(),
      routeInformationParser: _appRouter.defaultRouteParser(),
    );
  }
}

here is where I fetch the data from the api and store it in box :

@override
  Future<Either<ApiFailures, dynamic>> signInWithEmailAndPassword(
      {required String email, required String password}) async {
    late Box<CredentialsModel> credentials;
    var result;
    try {
      final response = await http.get(Uri.parse(
          "xxxxxxxx"));
      if (response.statusCode == 200) {
        result = await json.decode(response.body);

        if (result["AZSVR"] == "FAILED") {
          return const Left(ApiFailures.authFailed());
        } else {
          var content = CredentialsModel.fromJson(result);
          credentials = Hive.box("cred");
          credentials.put('cred', content);
          return right(result["api_token"]);
        }
      }
    } on SocketException catch (e) {
      return const Left(ApiFailures.noConnection());
    } on HttpException {
      return const Left(ApiFailures.notfound());
    } catch (_) {
      return const Left(ApiFailures.notfound());
    }
    return Right(result["api_token"]);
  }

where i call the box :

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:vwelfare/application/provider/doctor.repository.provider.dart';
import 'package:vwelfare/domain/models/doctor/duser.dart';
import '../../domain/models/credentials/credentials.dart';

class MyWidget extends HookConsumerWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final Box<CredentialsModel> credBox = Hive.box("cred");
    final Box<DuserModel> doctorBox = Hive.box("doctor");
    final controller = useTextEditingController();
    final uid = useState(0);
    final cred = useState(const CredentialsModel());
    return Scaffold(
      body: ValueListenableBuilder(
        valueListenable: credBox.listenable(),
        builder: (context, Box<CredentialsModel> box, _) {
          final cred = box.get("cred");
          print(cred!.api_token);
          final doctor = ref.watch(getDoctor(cred.api_token!));
          return doctor.when(
              data: (data) => data.fold(
                  (l) => ValueListenableBuilder(
                      valueListenable: doctorBox.listenable(),
                      builder: (context, Box<DuserModel> box, _) {
                        final model = box.get("doctor");
                        final doctor = model!.User;

                        if (doctor != null) {
                          return Center(
                            child: Text("${doctor.address}"),
                          );
                        } else {
                          return const Center(
                            child: Text("CONTACT US"),
                          );
                        }
                      }),
                  (r) => Center(child: Text("${r.User!.name}"))),
              loading: () => const CircularProgressIndicator(),
              error: (error, stackTrace) {
                print(error);
                return Center(
                  child: Text("$error hello"),
                );
              });
        },
      ),
    );
  }
}

Version

  • Platform: iOS, Android
  • Flutter version: [latest]
  • Hive version: [latest]

kivocsa99 avatar Sep 24 '22 23:09 kivocsa99

I have the same issue. Did you find any way to solve it?

Sania-Developer avatar Oct 09 '22 04:10 Sania-Developer

@Sania-Developer sadly no , wbu ?

kivocsa99 avatar Oct 28 '22 11:10 kivocsa99

Exactly the same is happening to me with version hive: ^2.2.3. I am also using a ValueListenableBuilder . My other box without TypeAdapter or ValueListenableBuilder is working fine. I am going to revert to version and see if that helps. If not, I will have to save object as string.

GraSim avatar Mar 11 '23 19:03 GraSim

@GraSim Did you have any more issues since? I am also using some boxes with TypeAdapter that I actively observe during the entire time the app is alive (using box.watch() in my case). I get many reports of the user data just vanishing and I assume it's related to this. I have some other boxes that are not watched and no one ever complained about any issues.

AlexDochioiu avatar Aug 15 '23 13:08 AlexDochioiu