尝试在颤振中访问 Hive 数据库时,“联系人”框已打开且类型为 Box<Contact>

abo*_*rak 5 database flutter flutter-hive

我在 main 中初始化了 box 数据库如下

void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
    Hive.init(appDocumentDirectory.path);
    Hive.registerAdapter(ContactAdapter());
    runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)

然后我使用 FutureBuilder 插件在材料应用程序中打开框,如下所示:

  FutureBuilder(
      future: Hive.openBox<Contact>('contacts'),
      builder: (context, snapshot) {
        if(snapshot.connectionState == ConnectionState.done){
          if(snapshot.hasError){
            return Text(snapshot.error.toString() );
          }
          return ContactPage();
        } else {
          return Scaffold();
        }
      }
    ),
Run Code Online (Sandbox Code Playgroud)

和里面 ContactPage()

我创建了这个:-

  ValueListenableBuilder(
                valueListenable: Hive.box<Contact>('contacts').listenable(),
                builder: (context,Box<Contact> box,_){
                  if(box.values.isEmpty){
                    return Text('data is empty');
                  } else {
                    return ListView.builder(
                      itemCount: box.values.length,
                      itemBuilder: (context,index){
                        var contact = box.getAt(index);
                        return ListTile(
                          title: Text(contact.name),
                          subtitle: Text(contact.age.toString()),
                        );
                      },
                    );
                  }
                },
               )
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,出现以下错误

The following HiveError was thrown while handling a gesture:
The box "contacts" is already open and of type Box<Contact>.
Run Code Online (Sandbox Code Playgroud)

当我尝试使用盒子而不打开它时,我收到错误意味着盒子没有打开。

我是否必须在不打开 ValueListenableBuilder 的情况下使用它?但是后来我必须在不同的小部件中再次打开同一个框才能在其上添加数据。

Z-X*_*-KH 5

实际上它是一个简单的解释: \n1.\xc2\xa0 仅当您的盒子具有像 \n \n2.\xc2\xa0
这样的泛型类型时才会发生,因此一旦您在未指定泛型类型的情况下调用,就会发生此错误。\n这就是一切
Hive.openBox<User>('users')

Hive.box('users')

\n

解决方案
\nHive.box<User>('users')每次调用:)

\n


Sel*_*ğlu 0

这可能是因为您正在尝试打开里面的盒子FutureBuilder。如果它试图以某种方式重建自身,它会尝试打开已经打开的盒子。您可以在注册适配器后尝试打开盒子吗,例如:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
  Hive.init(appDocumentDirectory.path);
  Hive.registerAdapter(ContactAdapter());
  await Hive.openBox<Contact>('contacts');
  runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)

而不是仅仅FutureBuilder返回ContactPage