我正在使用 Hive 来制作简单的 CRUD;在Hive Doc about open box 中,我们可以这样声明:
var box = await Hive.openBox<E>('testBox');
Run Code Online (Sandbox Code Playgroud)
我的问题:是否可以制作多个 openBox?我想要这样的东西:
Future _openBox() async {
var dir = await getApplicationDocumentsDirectory();
Hive.init(dir.path);
var box_session = await Hive.openBox("box_session");
var box_comment = await Hive.openBox("box_comment");
return await box_session,box_comment;
}
Run Code Online (Sandbox Code Playgroud) 该框是自动递增的。
假设我有一个像这样的对象:
@HiveType(...)
class Dummy {
@HiveField(0)
int id;
@HiveField(1)
String name;
}
Run Code Online (Sandbox Code Playgroud)
Dummy我希望 Hive 反序列化将对象的键映射到id字段。
Hive在 上使用键值数据库有非常简单的方法StatefulWidgets,例如:
class HookDemo extends StatefulWidget {
@override
_HookDemoState createState() => _HookDemoState();
}
class _HookDemoState extends State<HookDemo> {
Box user;
@override
void initState() {
super.initState();
user = Hive.box<User>('user');
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
final _u = User()
..nameFamily = 'myname'
..mobileNumber = '123456789';
_user!.add(_u);
_u.save();
},
child: Icon(Icons.add),
),
...
);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里我们定义了Box user属性,并在内部initState实现了用户的内容,例如user = Hive.box<User>('user');
之后我们就可以使用user没有任何问题和already opened错误
现在在我们使用的当前应用程序中, …
我正在使用 Flutter 开发应用程序;它会在本地存储一些数据,所以我决定使用 Hive 包,这是一个非常棒的包来存储数据。所以现在我将在用户按下同步按钮时将所有数据存储在本地。之后,如果用户再次单击同步,我必须删除所有框并存储可能具有或可能不具有相同框名称的数据。
如果单击同步按钮,我不想增加应用程序存储空间,我想删除所有框,然后再次创建框。
样本
deleteItem(int index) {
final box = Hive.box<Delivery>("deliveries");
box.deleteAt(index);
}
Run Code Online (Sandbox Code Playgroud)
我想将索引参数更改为我的对象的 id),就像这样
deleteItem(int id) {
final box = Hive.box<Delivery>("deliveries");
// box.deleteAt(index);
// box delete by id here
}
Run Code Online (Sandbox Code Playgroud)
这是我的 TypeAdapter 类:
@HiveType(typeId: 0)
class Delivery {
@HiveField(0)
final int id;
Delivery(this.id);
}
Run Code Online (Sandbox Code Playgroud) 我的应用程序默认打开welcome屏幕,在该屏幕中我放置了代码来检查用户是否已登录。如果记录重定向到主页,否则留在欢迎屏幕,但现在它返回此错误:
setState() or markNeedsBuild() called during build.
Run Code Online (Sandbox Code Playgroud)
welcome.dart
late Box userBox;
@override
void initState() {
super.initState();
userBox = Hive.box<Usermodel>('user'); // get user box
// see if user data exist in storage or not?
if(userBox.values.isNotEmpty && userBox.get(0).name.toString().isNotEmpty) {
Navigator.pushReplacementNamed(context, '/home'); // if exist redirect to home screen
}
}
Run Code Online (Sandbox Code Playgroud)
知道如何解决这个错误吗?
如果我的用户已经登录,Vinoth Vino答案工作正常,但如果我的用户未登录,则会抛出此错误:
Null check operator used on a null value
Run Code Online (Sandbox Code Playgroud)
哪个来自 userBox.get(0)!.name
如果我!在我之后删除get(0)然后它说
The getter 'name' was called on null.
Receiver: null …Run Code Online (Sandbox Code Playgroud)