我在 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)