Shafi Munshi
Shafi Munshi

Reputation: 323

How to use hive with workmanager in flutter?

In application background state, I want to fetch some data from API then store them into Hive database. for running task in background, I use workmanager package and added necessary code to fetch data from API and save that into Hive database. But it returns me error everytime.

LateInitializationError: Field '_my_hive_Box@66472566' has not been initialized.

this saying my hive box is not initialized. But I initialize them in the main()

is there any way to solve this hive box initialization?

class MyHive {
  // prevent making instance
  MyHive._();

  // hive box to store Client user  data
  static late Box<SellClientSyncModel> _clientBox;

  // store current user as (key => value)
  static const String _currentUserKey = 'local_user';

  /// initialize local db (HIVE)
  /// pass testPath only if you are testing hive
  static Future<void> init(
      {Function(HiveInterface)? registerAdapters, String? testPath}) async {
    if (testPath != null) {
      Hive.init(testPath);
    } else {
      await Hive.initFlutter();
    }
    await registerAdapters?.call(Hive);
    await initUserBox();
  }

  /// initialize user box
  static Future<void> initUserBox() async {
    _clientBox = await Hive.openBox(AppConstant.clientBoxHive);
  }

  /// Client Methods
  static Future<bool> saveClientToHive(SellClientSyncModel user) async {
    try {
      await _clientBox.put(_currentUserKey, user);
      return true;
    } catch (error) {
      print(error);
      return false;
    }
  }
}

in main()

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // initialize hive for whole app
  await MyHive.init(registerAdapters: (hive) {
    hive.registerAdapter(SellClientAdapter());
  });

  runApp(child: MyApp());

}

Upvotes: 0

Views: 114

Answers (1)

Shafi Munshi
Shafi Munshi

Reputation: 323

Check this two link:
solution 1
solution 2

if you can't understant Send and Receive port. A very easy way is to load incoming API response and save them into a response.txt file. Then you can extract those local response into Object.

This is how you can save in local .txt file

void saveResponseToJsonFile(dynamic data) async {
    // Define the file path (ensure the path exists)
    Directory directory = await getApplicationDocumentsDirectory();
    String filePath = '${directory.path}/response.txt';

    File file = File(filePath);

    // Write the JSON string to the file
    await file.writeAsString(data.toString());
    
  }

must use path_provider package..

Upvotes: 0

Related Questions