1 | initial version |
Hive can be integrated with Flutter by using the hive_flutter package. This package provides a Hive implementation that can be used in Flutter applications. Here are the steps to integrate Hive with Flutter:
Add the hive_flutter package to the dependencies section in pubspec.yaml file:
dependencies:
hive_flutter: ^1.0.0
Initialize Hive in the main function of your Flutter application:
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
void main() async {
await Hive.initFlutter();
await Hive.openBox('myBox');
runApp(MyApp());
}
Use the Hive box in your Flutter widgets:
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive/hive.dart';
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ValueListenableBuilder(
valueListenable: Hive.box('myBox').listenable(),
builder: (context, Box box, _) {
return Center(
child: Text(box.get('myKey', defaultValue: 'No value')),
);
}),
);
}
}
Use Hive to store and retrieve data:
import 'package:hive/hive.dart';
void saveData() async {
final box = await Hive.openBox('myBox');
await box.put('myKey', 'Hello World');
}
void retrieveData() async {
final box = await Hive.openBox('myBox');
final value = box.get('myKey', defaultValue: '');
print(value); // 'Hello World'
}
By using the hive_flutter package, you can easily integrate Hive in your Flutter application to store and retrieve data.