2

错误:Unhandled Exception: HiveError: You need to initialize Hive or provide a path to store the box.

基本上我的依赖项中有这些,所以一切都应该很好。

  hive: ^1.4.4+1
  hive_flutter: ^0.3.1
  path_provider: ^1.6.27

我也有import 'package:hive/hive.dart';import 'package:path_provider/path_provider.dart';在文件中

所以我只有

void doSomething() async {
    final documentDirectory = await getApplicationDocumentsDirectory();
    Hive.init(documentDirectory.path);
  }

叫。

我不明白。我想我做的一切都是正确的。让我知道您是否需要其他东西。

4

4 回答 4

1

Hive在 Android 或 iOS 上运行时需要初始化,因此您可以使用如下函数:

Future<Box> openHiveBox(String boxName) async {
    if (!kIsWeb && !Hive.isBoxOpen(boxName)) 
      Hive.init((await getApplicationDocumentsDirectory()).path);
    
    return await Hive.openBox(boxName);
}

您需要导入path_provider才能访问getApplicationDocumentsDirectory()

于 2021-11-19T13:08:54.917 回答
0

在你的颤振应用程序的主要功能上尝试以下代码:

import 'package:path_provider/path_provider.dart';
import 'package:hive/hive.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final appDocumentDirectory = await getApplicationDocumentsDirectory();
  Hive.init(appDocumentDirectory.path);
}
于 2022-02-03T05:32:56.057 回答
0

目前,path_provider 不支持 WEB。你可以在这里看到它:path_provider

您必须为 WEB 使用另一个目录。如果您使用 BLOC 作为状态管理,您可以执行以下操作:

if (!kIsWeb) {
    // if android or tablet
    HydratedBloc.storage = await HydratedStorage.build(
        storageDirectory: await getApplicationDocumentsDirectory(),
    );
} else {
    // if web
    HydratedBloc.storage = await HydratedStorage.build(
        storageDirectory: HydratedStorage.webStorageDirectory,
    );
}
于 2021-06-21T03:20:20.543 回答
-1

实际上,您不需要使用 HydratedStorage 在 web 上初始化 Hive:

import 'package:hive/src/hive_impl.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

initializeHive()async{
  //Use HiveImpl() to ensure you don't have conflicting Hive boxes.
  HiveInterface _hive = HiveImpl();
  if (kIsWeb) {
    await _hive.openBox('yourBoxName');
  } else {
    var dir = await getApplicationDocumentsDirectory();
    _hive.init(dir.path);
    await _hive.openBox('yourBoxName');
  }
}

如果你在 web 上使用 Flutter,你不需要初始化 Hive,也不需要提供 box 的路径,只有当你在移动设备上使用它时。

于 2021-09-14T18:34:14.250 回答