When you build an application of clashes, local data must be effectively managed. You want a database that is lightweight, fast and easy to be conducted, especially if your app will work offline. Asar is such a database. It is a high performance, easy to use Nosql embedded database is designed to flutter. With features such as reaction questions, indexes, relationships, migration, and transactions, ISAR makes local data stronger and developed friendly.
In this article, you will learn that how to integrate Asar into a fluttering project, set the data model, and perform a full range of Crud (creation, read, update, delete). To make it practically, you’ll, you will create an easy -to -do app that allows users to create, watch, update and delete tasks.
The table of content
Provisions
Before starting, make sure you have the following:
SDK Install (recommended version 3.0 or above).
Check your version:flutter --versionDUT Knowage: Familiar with dart syntax, classes, and Async programming.
Fluttering: You should know how to set up a fluttering project, to make and use widgets
FutureBuilderOrsetStateFor State Management.Code Editor: VS Code or Android Studio recommended.
If they are in place, we are ready to start.
What are we making
We will create a Task Manager app that allows users:
Finally, you will have a full -fledged crude app with filter and Asar.
How to establish Asar in a fluttering project
Step 1: Add dependent
Open your own pubspec.yaml File and add below:
dependencies:
flutter:
sdk: flutter
isar: ^3.1.0
isar_flutter_libs: ^3.1.0
dev_dependencies:
isar_generator: ^3.1.0
build_runner: any
isar: Basic Asar Package.isar_flutter_libs: It is necessary for the integration of flurry.isar_generator: Used to prepare the code for your models.build_runner: The code runs the generator.
Drive:
flutter pub get
Step 2: Make ISAR and start
Create a file that has a name isar_setup.dart. It will handle the opening of the ISAR database.
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';
import 'task.dart';
late final Isar isar;
Future<void> initializeIsar() async {
final dir = await getApplicationDocumentsDirectory();
isar = await Isar.open(
(TaskSchema),
directory: dir.path,
);
}
Clarification:
getApplicationDocumentsDirectory()Provides storage location for the database file.Isar.open()Starts the database and makes our entryTaskScheme.late final Isar isar;This ensures that we can access the database example globally after the beginning.
Method to create a task model
Now explain your data model for work. Create a file that has a name task.dart.
import 'package:isar/isar.dart';
part 'task.g.dart';
@Collection()
class Task {
Id id = Isar.autoIncrement;
late String name;
late DateTime createdAt;
Task(this.name) : createdAt = DateTime.now();
}
Clarification:
@Collection()Asar tells that this class represents a database reserve.Id id = Isar.autoIncrement;Automatically creates a unique identifier.late String name;Stores work name.late DateTime createdAt;The creation stores the time stamp.part 'task.g.dart';Links for the generated code, which will be created after running the code generator.
Prepare the code:
flutter pub run build_runner build
That is born of task.g.dartWhich contains the necessary scheme code.
How to Store for CRUD Operations
Create a new file that says task_repository.dart. It will have ways to communicate with the database.
import 'package:isar/isar.dart';
import 'task.dart';
import 'isar_setup.dart';
class TaskRepository {
Future<void> addTask(String name) async {
final task = Task(name);
await isar.writeTxn(() async {
await isar.tasks.put(task);
});
}
Future<List> getAllTasks() async {
return await isar.tasks.where().findAll();
}
Future<void> updateTask(Task task) async {
await isar.writeTxn(() async {
await isar.tasks.put(task);
});
}
Future<void> deleteTask(Task task) async {
await isar.writeTxn(() async {
await isar.tasks.delete(task.id);
});
}
}
Clarification:
addTask: Creates a new job and saves it.getAllTasks: Reads all the tasks from the database.updateTask: Calling updates an existing job.put()Once againdeleteTask: Removes a job by itsid.isar.writeTxn: Safety and consistency ensures running within a transaction.
How to integrate the crude in the UI
Now, let’s fold everything from the inside main.dart.
import 'package:flutter/material.dart';
import 'isar_setup.dart';
import 'task_repository.dart';
import 'task.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await initializeIsar();
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();
late Future<List> _tasksFuture;
@override
void initState() {
super.initState();
_tasksFuture = _taskRepository.getAllTasks();
}
Future<void> _addTask() async {
await _taskRepository.addTask('New Task');
setState(() {
_tasksFuture = _taskRepository.getAllTasks();
});
}
Future<void> _deleteTask(Task task) async {
await _taskRepository.deleteTask(task);
setState(() {
_tasksFuture = _taskRepository.getAllTasks();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Isar CRUD Example')),
body: FutureBuilder<List>(
future: _tasksFuture,
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 ?? ();
if (tasks.isEmpty) {
return Center(child: Text('No tasks yet.'));
}
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),
),
);
}
}
Clarification:
initializeIsar(): It ensures that the database is ready before the app runs._tasksFuture: The future of the tasks is the future._addTask: Adds a new job and refreshes the list._deleteTask: Deletes something and refreshes the list.FutureBuilder: UI automatically rebuilds when the future is completed.ListView.builder: All work is dynamically displayed.
This gives you an easy but full crude app using ISAR.
Beyond CRUD: Advanced features of ISAR
Once you are pleased with the CRUD, ISAR provides modern tools to improve and enhance your application:
Reaction questions:
To use instead ofFutureBuilderYou can hear direct changes.final stream = isar.tasks.where().watch(fireImmediately: true);Index:
Improve the performance of the inquiry through indexing fields.@Collection() class Task { Id id = Isar.autoIncrement; @Index() late String name; }Relationship:
Connect one combination to another (eg,ProjectWith a lot of peopleTasks,Customs questions:
Perform complex filtering, sorting, and pages.Migration:
As the app grows, prepare your scheme safely.Batch Operations:
Insert or update many records in a transaction.
Conclusion
We have created a simple fluttering app with ISAR that supports to create, read, update and delete tasks. On the way, we learned how:
Add isar dependence.
Explain a model with interpretations.
Prepare a scheme code.
Enforce CRUD operations in a reservoir.
Connect the Asar with the UI.
With its performance, developer -friendly API, and advanced features, isar is a great choice for local perseverance in applications.
To learn more, consult the official documents: