Flutter Integration with Hive(No-Sql)
Past couple of weeks I have studied flutter development. What I feel Flutter is more cooler than any other mobile development frameworks. So When I deep learn the widgets & API integration I thought to build offline first mobile application.
Setup
Download following dependencies to flutter project.
hive: ^1.4.4+1
path_provider: ^1.6.24
hive_flutter: ^0.3.1
And need to Add These Two As Dev Dependencies.
hive_generator: ^0.7.0+2
build_runner: ^1.8.0
Initialize the Hive database in Application Main Method.
void main() async {
await Hive.initFlutter();
runApp(MyApp());
}
What We are going to do is save User Object to Hive Database. First need to Create Object class.
import 'package:hive/hive.dart';
part 'user-model.g.dart';
@HiveType(typeId: 1)
class User {
@HiveField(0)
final String id;
@HiveField(1)
final String name;
@HiveField(1)
final int age;
User({this.id, this.name, this.age});
}
Note : When Working with Hive database We have to write Adapter class for Each Object to do operations in hive database. But It is very tedious process & hard to write Adapters. For That one We have to use hive_generator . When we put part ‘user-model.g.dart’; & run following command It will Generate Adapter class for User Object. This will generate Adapter class name as “user-model.g.dart”
flutter pub run build_runner build
And We have to Register Generated Adapter in Main Method.
void main() async {
await Hive.initFlutter();
Hive.registerAdapter(UserAdapter());
runApp(MyApp());
}
CRUD Operations
First need to Open Box for Adding Items
Future openBox() async {
var directory = await getApplicationDocumentsDirectory();
Hive.init(directory.path);
box = await Hive.openBox('users');
return;
}
1.Save Data
Future addData(List<User> allLocations) async {
await box.clear();
for (Location u in allLocations) {
box.put(u.id, u);
}
}
2. Retrieve Data
Future<List> _getAllUsers() async {
await openBox();
return box.toMap().values.toList();
}
And That is all . It is simple & fast . Our Next article we will cover how to write offline first Application with hive & REST API.