ObjectBox in Flutter is a super-fast database storing Dart objects locally.
Introduction
For storing Dart objects in your cross-platform projects, consider using the ObjectBox Flutter database.
The ObjectBox in the Flutter database was built for great speed and is perfect for mobile and IoT devices.
With minimum CPU, memory, and battery usage, ObjectBox makes your programme both efficient and sustainable.
Installation of ObjectBox in Flutter
The first thing we have to do after creating the app is to add these dependencies in the pubspec.yml file.
1 2 3 4 5 6 7 8 9 10 |
dependencies: objectbox: ^2.1.0 objectbox_flutter_libs: any dev_dependencies: build_runner: ^2.0.0 objectbox_generator: any |
Note: Please add updated dependencies.
ObjectBox is an object-oriented non-relational (NoSQL) database. First, we need to tell the database which entities to store.
Create Entity and Store Class using ObjectBox in Flutter
You may also check our other database Hive DataBase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import 'package:blog_project/objectbox.g.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import 'package:objectbox/objectbox.dart'; @Entity() class UserData { @Id() int id = 0; String? name; @Property(type: PropertyType.date) // Store as int in milliseconds DateTime? date; @Transient() // Ignore this property, not stored in the database. int? computedProperty; } class ObjectBox { late final Store store; ObjectBox._create(this.store) { } static Future<ObjectBox> create() async { final docsDir = await getApplicationDocumentsDirectory(); final store = await openStore(directory: p.join(docsDir.path, "obx-example")); return ObjectBox._create(store); } } |
Box operations
First, you have to open your box:
1 2 |
final store = await openStore(); var userBox = store.box<UserData>(); |
Types of operations:
- Put => insert one element inside the database
- putMany => Insert a list of userData
- get => Get one specific user by Key(ID)
- getMany => Get multiple users by giving a list of Key (ID)
- getAll => Get all the userData
- remove => Remove one user by Key(ID)
- removeMany => Remove many users by giving a list of Key(ID)
- removeAll => Delete all the objects in a box.
- count => Counts the number of objects in a box
1 2 3 4 5 6 7 8 9 10 11 |
final user = UserData(name: 'Webkul'); userBox.put(user); final users = getNewUsers(); userBox.putMany(users); final user = userBox.get(userId); final users = userBox.getMany(userIds); final users = userBox.getAll(); |
Conclusion
In this article, we have explained How to add values in the objectBox database and get values in the database.
You may also check our Flutter app development services
For more understanding please can go through this Link
For more interesting blogs check here.
Thanks for reading this article.