Choosing the right database in a fast-paced environment like Flutter is crucial. That’s where Isar Database comes in. Isar is a NoSQL solution specifically built for Flutter development. This step-by-step guide walks you to implemented Isar Database in Flutter Isar’s smooth integration, Type-Safe models, and Cross-Platform compatibility, providing you with a comprehensive toolkit for effective data management.
Key Features of Isar Database
- Isar Database adopts a NoSQL architecture. This provides the advantage of schema-free data modeling. With Isar Database, developers can store and load data without being limited by pre-defined structures.
- Isar includes an efficient query language designed for both simplicity and performance. Developers can easily run complex queries to retrieve and manipulate data.
- Isar Database introduces type-safe models, taking advantage of Dart’s strong typing capabilities. This feature improves code readability, reduces errors, and simplifies the development process.
- Isar Database supports multiple platforms, ensuring that Flutter developers can use a consistent and powerful database solution for mobile, web, and desktop applications.
You can visit our Flutter app development page for more flutter-related information.
Implementation
1. Setup :
Create new project and add the following dependency into your project
1 2 3 4 5 6 7 8 |
dependencies: isar: ^3.1.0+1 isar_flutter_libs: ^3.1.0+1 path_provider: ^2.1.2 dev_dependencies: build_runner: ^2.4.4 isar_generator: ^3.1.0+1 |
2. Initialize Database :
Firstly, create customer model class and define the properties for the customer (name, email and id) as follows :
1 2 3 4 5 6 7 8 9 10 11 |
import 'package:isar/isar.dart'; part 'user_model.g.dart'; @collection class UserModel { Id id = Isar.autoIncrement; String? name; String? email; UserModel({this.name, this.email}); } |
Annotate customer class with @collection
, define id field (id = Isar.autoIncrement) and Execute the following command to start the build_runner
:
1 |
flutter pub run build_runner build |
3. Open Isar database
Create a method to open Isar database and call this method from initState as shown below :
1 2 3 4 5 6 7 |
Future<Isar> openDatabase() async { final dir = await getApplicationDocumentsDirectory(); return await Isar.open( [UserModelSchema], directory: dir.path, ); } |
dir :- Get the directory information where we need to initialize the isar instance.
Isar.open() :- method to open the database and return instance it takes arguments as List of schemas (UserModelSchema in our example code) and directory path.
4. Add new User in database
Create a method saveUser() to add new user in database as shown below :
1 2 3 4 5 |
Future<void> saveUser(UserModel newUser) async { await database.writeTxn((){ return database.userModels.put(newUser); }); } |
saveUser() :- Method takes instance of new user to save in database.
put() :- put method add new user to the database.
5. Retrieve all the users
For Retrieving all the user from database create method as follows and read the users using findAll method :
1 2 3 4 5 6 |
Future<void> getAllUser() async { List<UserModel> users = await database.userModels.where().findAll(); setState(() { customers = users; }); } |
Complete code
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import 'package:dio_networking/isar_database/user_model.dart'; import 'package:flutter/material.dart'; import 'package:isar/isar.dart'; import 'package:path_provider/path_provider.dart'; class CustomerProfile extends StatefulWidget { const CustomerProfile({Key? key}) : super(key: key); @override State<CustomerProfile> createState() => _CustomerProfileState(); } class _CustomerProfileState extends State<CustomerProfile> { late Isar database; List<UserModel> customers = []; @override void initState() { openDatabase().then((value) => database = value); super.initState(); } //Open database Future<Isar> openDatabase() async { final dir = await getApplicationDocumentsDirectory(); return await Isar.open( [UserModelSchema], directory: dir.path, ); } // Add new User in database Future<void> saveUser(UserModel newUser) async { await database.writeTxn((){ return database.userModels.put(newUser); }); } //Retrieve all users from the database. Future<void> getAllUser() async { List<UserModel> users = await database.userModels.where().findAll(); setState(() { customers = users; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Customers"), ), body: SizedBox( width: MediaQuery.of(context).size.width, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ...customers.map((user) => ListTile( title: Text(user.name ?? ""), subtitle: Text(user.email ?? ""), )).toList(), const SizedBox(height: 20), ElevatedButton(onPressed: (){ saveUser(UserModel(name: "Test1", email: "Test1@example.com")); ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("User Added"))); }, child: const Text("Add User")), ElevatedButton(onPressed: (){ getAllUser(); }, child: const Text("List all Users")), ], ), ), ); } } |
Output of complete code
Isar Database Read and write
Click Add user button to add new user in database and click list all users button to get list of all users show all users with ListTile in UI.
Conclusion
Thanks for reading this article ❤️
I hope this blog will help you to learn about how to implement Isar Database in Flutter and you will be able to implement it. For more updates, make sure to keep following Mobikul Blogs to learn more about mobile app development.
Happy Learning ✍️
Other Blogs you may like..