我是一个新手在Flutter和Hive,只是学习。这里有一些问题
我使用的是value listenable builden,当我按“person age up”person1 age不更新但按setstate然后更新时,如何自动更新?
hive是一个数据库,我按它添加的“add person”,当我按“print person lenght”时会看到,但当重新加载应用程序时,person length再次更改为1,所有添加和删除:
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'departmentClass.dart';
import 'person.dart';
void main() async {
await Hive.initFlutter('test');
Hive.registerAdapter(DepartmentAdapter());
Hive.registerAdapter(PersonAdapter());
await Hive.openBox<Department>('testBox');
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final Box testBox = Hive.box<Department>('testBox');
@override
Widget build(BuildContext context) {
if (testBox.isEmpty) {
final List<Person> personsAll = [];
final person1 = new Person(23, "Maria");
personsAll.add(person1);
var mydepartment = new Department(34, "newD", personsAll);
Hive.box<Department>('testBox').put("01", mydepartment);
}
return ValueListenableBuilder(
valueListenable: testBox.listenable(),
builder: (context, box, widget) {
return MaterialApp(
home: SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("Hive Test"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Hive Sample"),
RaisedButton(
child: Text("Clear Box"),
onPressed: () {
Hive.box<Department>('testBox').clear();
},
),
Text("Person1 Age Now: " + box.get("01").persons[0].age.toString()),
RaisedButton(
child: Text("Person age UP"),
onPressed: () {
box.get("01").persons[0].age++;
print(box.get("01").persons[0].age);
},
),
RaisedButton(
child: Text("Set State"),
onPressed: () {
setState(() {});
},
),
RaisedButton(
child: Text("Add person "),
onPressed: () {
final person2 = new Person(23, "Maria");
box.get("01").persons.add(person2);
},
),
RaisedButton(
child: Text("Print person lenght "),
onPressed: () {
print("Persons: " + Hive.box<Department>('testBox').get("01").persons.length.toString());
},
)
],
)),
),
),
);
},
);
}
}
1条答案
按热度按时间qvtsj1bj1#
首先,当你打开一个盒子时,最好用泛型声明它的类型;
final Box<Department> testBox = Hive.box<Department>('testBox');
第二,如果你想通知盒子你正在通过ValueListenableBuilder
,每次更改值时都需要将值放入框中;