flutter hive的使用
导包:
hive: ^2.0.6
hive_flutter: ^1.1.0
代码:(敲一遍,你会懂的)
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
Future<void> main() async {
await Hive.initFlutter();
runApp(const MaterialApp(
home: H(),
));
}
class H extends StatefulWidget {
const H({super.key});
@override
State<H> createState() => _HState();
}
class _HState extends State<H> {
List<int> records = [];
int index = 0;
@override
void initState() {
super.initState();
getData();
}
Future<void> getData() async {
var box = await Hive.openBox('demo');
var value = box.get("record");
if (value == null) {
print('啥也没拿到到');
} else {
print('拿到数据了');
records = value.cast<int>();
print(records);
}
}
Future<void> addData() async {
var box = await Hive.openBox('demo');
box.put("record", records);
print('添加数据成功');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("hive demo"),
),
body: const Placeholder(),
floatingActionButton: FloatingActionButton(
child: const Text("add"),
onPressed: () {},
));
}
}