Implementing Isar Database in Your Flutter Project: A Comprehensive Guide

Implementing Isar Database in Your Flutter Project: A Comprehensive Guide

Beginners guide to Isar Database using Flutter

Introduction to Isar Database

Isar is a high-performance, easy-to-use NoSQL embedded database for Flutter applications. It is designed to work seamlessly with Flutter, offering a reactive API and advanced features such as indexes, relationships, and migrations. With Isar, developers can efficiently manage local data persistence in their Flutter projects.

In this article, we'll explore the process of integrating Isar into a Flutter project and implementing basic CRUD (Create, Read, Update, Delete) operations using the Isar database.

Setting Up a Flutter Project with Isar

To get started, create a new Flutter project or use an existing one. Once the project is set up, follow these steps to integrate Isar:

1. Open pubspec.yaml and add the Isar dependencies:

dependencies:
  isar: ^3.1.0
  isar_flutter_libs: ^3.1.0

dev_dependencies:
  isar_generator: ^3.1.0
  build_runner: any

Ensure that the version numbers match the desired Isar version.

2. Run the following command to get the dependencies:

flutter pub get

3. Set up Isar in your Flutter app:

Create a new Dart file, such as isar_setup.dart, and initialize Isar within it:

import 'package:isar/isar.dart';

final isar = await openIsar();

Make sure to import the necessary packages and use the openIsar function to initialize Isar. This step sets up the Isar database for your Flutter project.

Implementing CRUD Operations with Isar

Now that Isar is integrated into your Flutter project, let's proceed with implementing CRUD operations.

1. Creating Data Model

Define a data model for your entities. For example, let's create a Task model:

@Collection()
class Task {
  int? id;

  late String name;
  late DateTime createdAt;

  Task(this.name) : createdAt = DateTime.now();
}

2. Adding CRUD Methods

In a separate Dart file, create methods for CRUD operations. For brevity, we'll include simplified implementations:

import 'package:isar/isar.dart';

class TaskRepository {
  final IsarCollection<Task> _tasks;

  TaskRepository(this._tasks);

  Future<void> addTask(String name) async {
    await _tasks.writeTxn((isar) async {
      await isar.write(Task(name));
    });
  }

  Future<List<Task>> getAllTasks() async {
    return await _tasks.where().findAll();
  }

  Future<void> updateTask(Task task) async {
    await _tasks.writeTxn((isar) async {
      await isar.write(task);
    });
  }

  Future<void> deleteTask(Task task) async {
    await _tasks.writeTxn((isar) async {
      await isar.delete(task);
    });
  }
}

3. Using CRUD Methods in Flutter UI

Now, integrate these CRUD methods into your Flutter UI to interact with the Isar database. For example, you can use a button to add a task and display a list of tasks:

import 'package:flutter/material.dart';

void main() async {
  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(isar.writeTxn);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Isar CRUD Example'),
      ),
      body: FutureBuilder<List<Task>>(
        future: _taskRepository.getAllTasks(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return CircularProgressIndicator();
          } else if (snapshot.hasError) {
            return 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(() {});
  }
}

This example demonstrates a simple Flutter app that displays a list of tasks and allows users to add new tasks and delete existing ones using the Isar database.

Isar is a versatile and feature-rich database for Flutter applications, offering several functionalities and capabilities beyond basic CRUD operations. Let's explore some of the advanced features and capabilities that Isar provides:

1. Reactive Queries:

Isar supports reactive queries, allowing your UI to automatically update in response to changes in the database. This means that if the data in the Isar collection changes (e.g., due to additions, updates, or deletions), the UI will automatically reflect those changes without manual intervention.

// Reactive query example
final reactiveTasks = _tasks.where().watchLazy();

2. Indexes:

You can define indexes on specific properties of your models to optimize query performance. Indexing is crucial for speeding up read operations, especially when dealing with large datasets.

@Collection()
class Task {
  @Link(to: 'task_id', index: true)
  final subTasks = IsarLinks<Task>();
}

3. Relations:

Isar supports relationships between different models. You can create links between collections, enabling you to model complex data structures more effectively.

@Collection()
class Project {
  late String name;

  @Link(to: 'project')
  final tasks = IsarLinks<Task>();
}

4. Custom Queries:

Isar provides a powerful query API that allows you to perform complex queries with ease. You can filter, sort, and paginate your data efficiently.

// Custom query example
final highPriorityTasks = _tasks
    .where()
    .filter()
    .and()
    .greaterThanOrEqualTo(_tasks.isarField<Task>('priority'), 3)
    .findAll();

5. Migrations:

Isar supports schema migrations, allowing you to evolve your data model over time. You can define migration steps to handle changes to the schema as your application evolves.

final isar = await openIsar(
  schemaBuilderCallback: (schemaBuilder) {
    schemaBuilder
        .link<Task>('project')
        .backward(linkName: 'tasks', index: true);
  },
  onSchemaVersionChanged: (isar, oldVersion, newVersion) async {
    if (oldVersion == 1) {
      // Perform migration steps for version 1 to version 2
    }
  },
);

6. Transactions:

Isar supports transactions, allowing you to execute a series of operations atomically. This is essential for maintaining data integrity, especially in scenarios where multiple operations need to be executed as a single unit.

await _tasks.writeTxn((isar) async {
  await isar.write(Task('New Task'));
  await isar.write(Task('Another Task'));
});

7. Batch Operations:

Isar allows you to perform batch operations efficiently. You can insert, update, or delete multiple items in a single transaction, reducing the overhead of multiple transactions.

await _tasks.writeTxn((isar) async {
  await isar.writeMany([
    Task('Task 1'),
    Task('Task 2'),
    Task('Task 3'),
  ]);
});

These features make Isar a robust choice for managing local data in Flutter applications. Whether you're building a small app or a complex mobile solution, Isar provides the tools and flexibility needed to handle diverse data scenarios efficiently.

To delve more into Isar consider exploring its official docs using https://pub.dev/packages/isar or https://isar.dev/

Did you find this article valuable?

Support Atuoha Anthony by becoming a sponsor. Any amount is appreciated!