The Object Box is a high performance, lightweight, nosql embedded database specifically made for blowing and dart applications. It provides reacting APIs, indexes, relationships and migration, all designed to make local data management smooth and efficient.
In this guide, we will integrate the object box into a fluttering project and implement the basic CRUD operations (created, read, update, delete) by explaining each step in detail.
The table of content
Provisions
Before starting with the Object Box in the clash, you need the appropriate development environment. Make sure you have a flurry installed 3.x or above, as well as the Dart SD that bundles it with, and confirm the installation flutter --version.
You will also need an IDE such as VS code, Android Studio, or intelligence and a dart plugin. Testing can be done on an emulator or simulator, but an actual device is recommended as some object box features perform well there. If you intend to store the database in specific directories related to the platform, make sure that your app has the necessary allowing file storage, though the standard app directory usually handles it automatically.
In terms of fluttering and dart knowledge, you should be comfortable with the basic things that are already sprouting StatelessWidgetFor, for, for,. StatefulWidgetFor, for, for,. setState()And like ordinary widgets ListView.builderFor, for, for,. ColumnFor, for, for,. RowFor, for, for,. ScaffoldAnd AppBar. Including familiarity with UI components FloatingActionButtonFor, for, for,. TextFieldFor, for, for,. ButtonFor, for, for,. IconButtonAnd ExpansionTile Also important. On the side side, you should understand class, conductors, fields, designated parameters, late With variables, and with unprecedented programming Future And Stream. Know how to use FutureBuilder And StreamBuilder The integration in the clash will make the merger more smooth.
Finally, you will need to understand the basic concepts of the object box. This includes entity (described with dart classes @Entity() Map of Map Database Tables), Basic keys (usually a number of numbers id), And boxes (BoxThose who represent tables and handle crude operations put()For, for, for,. getAll()And remove()) To understand the relationship ToOne And ToManyTo work with the reaction questions using query().watch()And run with nuclear actions with store.runInTransaction() It will be necessary. Indicators with @Index() As long as you inquire from the fields, it can also help improve performance. Despite being optional, solid grip of streams in the flurry, async/wait in the dart, and its familiarity are beneficial path_provider Package for management of database storage locations.
How to configure the fluttering project with the Object Box
First, make sure you have a fluttering project. You can create a new one with:
flutter create objectbox_demo
Once your project is ready, open pubspec.yaml And add the Object Box dependent:
dependencies:
objectbox: ^4.3.1
objectbox The basic database package. Version number ^2.4.0 This ensures that you get a compatible release.
Bring dependency from running:
flutter pub get
It downloads the Object Box and makes it available for your project.
How to start the Object Box
You need to use the Object Box, you need to make a store.
For example, create a new dart file objectbox_setup.dart:
import 'package:objectbox/objectbox.dart';
late final Store store;
Future<void> initObjectBox() async {
store = await openStore();
}
Explanation:
StoreThe basic class that represents the database.openStore()Opens the database and manufactures it for CRUD operations.late final Store store;This ensures that the store has been started once and can be achieved globally.
Tip: You can also customize the directory or enable migration openStore() If your scheme is ready.
How to create a data model
The data in the object box is represented as an institution. Each institution is equivalent to a dart class that has been interpreted with @Entity(). Let’s make a Task History:
import 'package:objectbox/objectbox.dart';
@Entity()
class Task {
int? id;
late String name;
late DateTime createdAt;
Task(this.name) : createdAt = DateTime.now();
}
Explanation:
@Entity()The class marks as an object box entity.idThe basic key. The Object Box produces auto if it is invalid.lateFields must start before use.createdAtTime Stamp automatically stores when ATaskBorn
How to enforce CRUD operations
Lip of Clear Code Wee, we adapt to database operations in a storage class:
import 'package:objectbox/objectbox.dart';
import 'task.dart';
class TaskRepository {
final Store _store;
late final Box _tasks;
TaskRepository(this._store) : _tasks = _store.box();
Future<void> addTask(String name) async {
await _store.runInTransaction(() async {
await _tasks.put(Task(name));
});
}
Future<List> getAllTasks() async {
return _tasks.getAll();
}
Future<void> updateTask(Task task) async {
await _store.runInTransaction(() async {
await _tasks.put(task);
});
}
Future<void> deleteTask(Task task) async {
await _store.runInTransaction(() async {
await _tasks.remove(task.id!);
});
}
}
Detailed Error:
Box: A container for all of the types ofT. Think of it as a table in a relative database.put(): Inserts a new item or updates an existing item ifidExists.getAll(): Bring all the items in the box.remove(id): Delete an item through its identity.runInTransaction(): It ensures that all the actions inside the block are atoms – either all successful or all fail.
How to connect CRUD operations with a flurry ui
Now, the Interactive CRUD operates the Object Box for operations.
import 'package:flutter/material.dart';
import 'objectbox_setup.dart';
import 'task_repository.dart';
import 'task.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await initObjectBox();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: TaskListScreen(),
);
}
}
class TaskListScreen extends StatefulWidget {
@override
_TaskListScreenState createState() => _TaskListScreenState();
}
class _TaskListScreenState extends State<TaskListScreen> {
final TaskRepository _taskRepository = TaskRepository(store);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('ObjectBox CRUD Example')),
body: FutureBuilder<List>(
future: _taskRepository.getAllTasks(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
final tasks = snapshot.data ?? ();
return ListView.builder(
itemCount: tasks.length,
itemBuilder: (context, index) {
final task = tasks(index);
return ListTile(
title: Text(task.name),
subtitle: Text('Created at: ${task.createdAt}'),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () => _deleteTask(task),
),
);
},
);
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: _addTask,
child: Icon(Icons.add),
),
);
}
Future<void> _addTask() async {
await _taskRepository.addTask('New Task');
setState(() {});
}
Future<void> _deleteTask(Task task) async {
await _taskRepository.deleteTask(task);
setState(() {});
}
}
Explanation:
FutureBuilder: Object box handles handling tasks.ListView.builder: Effectively offers a list of tasks._addTask& & & & & & &_deleteTask: Call the repository methods and refresh the UIsetState().
Features of Advanced Object Box
Reaction questions
The Object Box can automatically update the UI whenever the database changes:
final reactiveTasks = _tasks.query().watch().listen((query) {
});
Indexing
Execution of Questioning Performance Performance:
@Entity()
class Task {
@Id(assignable: true)
int? id;
@Index()
late String name;
late DateTime createdAt;
}
Relationship
The Object Box supports the relationship, activates complex models:
@Entity()
class Project {
int? id;
late String name;
@Backlink(to: 'project')
final tasks = ToMany();
}
Customs questions
Filters, sorting, and perform complex questions with pages:
final highPriorityTasks = _tasks.query()
.greater(Task_.priority, 3)
.order(Task_.createdAt)
.build()
.find();
greater()For, for, for,.less()For, for, for,.equal(): Filter records.order(): Sort by a property.
Migration
Object box handles scheme changes:
final store = await openStore(
directory: getApplicationDocumentsDirectory().path,
model: getObjectBoxModel(),
onVersionChanged: (store, oldVersion, newVersion) {
if (oldVersion == 1) {
}
},
);
onVersionChanged: Follow the logic of transfer for scheme refresions.
Transactions and batch operations
Perform multiple operations from the atom:
await _store.runInTransaction(() async {
await _tasks.putMany((
Task('Task 1'),
Task('Task 2'),
Task('Task 3'),
));
});
Conclusion
The Object Box provides a sharp, reaction and easy local database for use. Beyond CRUD operations, it supports indexing, relationships, reaction questions, migration and batch transactions. It makes the perfect Perfect of fluttering apps, which requires strong local storage and high performance.
Official documents and to learn more: