Flutter Database Concepts
Overview
Databases are a collection of data that are essential for storing and managing persistent data. Flutter does not provide built-in databases for storing data but gives excellent integration capabilities with various database solutions. Databases can store lots of data like name, age, unique id, images etc. We can use different databases for different requirements like scalability, offline capabilities, and the backend technologies. The Flutter databases are widely used in variety of app types and using them makes the user experience easy and smooth. Databases play an important role for storing and retrieving data locally or remotely.
Introduction
A database is helpful for storing, managing, and retrieving data in your application. You can access this data even when you have closed or restarted the app and gives the persistent storage of the app's data. It is a centralized repository where you can store any kind of data like user information, someone's full activities, actions, images, and all other important details also. We can perform different queries and operations like search and filter, on the stored data. By using flutter databse, we get number of benefits like data persistence, data management, data synchronization, and advanced querying and filtering. We use third-party packages for using flutter databases based on our requirements like- 'SQLite', 'Firebase Realtime Database', 'Cloud Firestore', 'Hive', and many more. Overall, flutter databases helps in managing and manipulating app's data effectively. Also, helps in making dynamic and data-driven applications with efficient data handling.
What is a Database?
Database is a structured collection of data that is organized and stored for easy retrieval and manipulation. The Flutter database helps in storing and managing the data persistently. A database is a very useful kind of software that helps developers to add, delete, modify, and remove data in the database. These operations are not visible to users in front view but are performed in background of an application and we just get to see the results of operations performed. A collection of data in databases helps in analyzing and observing the data easily using queries on the data.
Types of Database
There are different types of databases available for various requirements, management needs, and use cases. Here are some reasons, why we have different databases available for different purposes-
- Data Model Flexibility -
Different databases offers different data models in storing different data and data structures. - Scalability -
As we know databases vary in scaling horizontally or vertically to handle loaded volumes of data. So, NoSQL and NewSQL databases, are designed to provide high scalability. - Performance Considerations -
To get fast data access and low latency in storing data in memory like in-memory databases. - Evolving Technologies and Trends -
Databases constantly evolve driven by advancements in hardware, software, and data management techniques.
Following are the types of databases which are used in different applications according to the set of requirements-
-
NoSQL Database -
Non-SQL/Not Only SQL databases provide a non-tabular, flexible data model that allows for rapid development and scalability. It is very helpful in full filling modern applications requirements. It has various forms like "Document Databases", "Key-Value Stores", "Columnar Databases", and "Graph Databases". -
Relational Database -
This is based on relational data model, which stores data in tables with rows(tuples) and columns(attributes). They use a predefined schema to define the structure of the data and relationships between tables. Examples are MySQL, PostgreSQL, Oracle Database, and Microsoft SQL Server. -
Hierarchical Databases -
This type of database stores data in the form of parent-children relationship nodes. It stores data in a tree-like structure. Data storage is done in the form of records that are connected via links and each record will have only one parent. -
Network Databases -
This is a hierarchical database, but here child records are given the freedom to associate with multiple parent records. This results in linking multiple threads with each other like administration, Students, Faculty, and Resources linked with each other. -
Cloud Database -
This database stores data in a virtual environment and executes over the cloud computing platform. It provides users with various cloud computing services ( PaaS, SaaS, IaaS, etc.). We have heard of numerous cloud platforms like- "AWS", "Microsoft Azure", "Google Cloud SQL" etc.
We will also discuss about some important databases used in Flutter for various needs like if we want minimum and important data to be stored in mobiles or apps and store it locally, or no data to be shown if the user is offline. So, we will categorize these databases according to our app requirements.
- Local Databases :
These databases are stored and accessed locally on the device where we are running our Flutter application. Local Databases are very useful as they provide offline data storage and enable the app to work without a network connection. Wondering what kind of data we store here? We store user-specific data, application settings, caching, and other locally managed data. SQLite is a popular choice for local databases in Flutter with Flutter packages like "sqflite" or "moor" to integrate SQLite with your Flutter app. - Remote Databases :
These databases are hosted on servers or cloud platforms and are accessed by a network connection. In these databases, data is stored at a centralized location, which is accessible to everyone across multiple devices and allows real-time synchronization and collaboration. "Firebase Realtime Database" and "Cloud Firestore" are cloud-hosted NoSQL database used in Flutter application development. - Hybrid Databases :
Hybrid databases combines both local and remote databases which help in accessing and synchronizing with remote servers. Hybrid databases help to store and manipulate data locally while syncing with a remote database when the device is online. "Hive" and "PouchDB" are the databases for storing data and supporting offline access in Flutter applications.
Popular Databases for Flutter
We have discussed a lot about various types of databases used for different requirements. We have also seen some popular databases which plays a crucial role in storing data and data structures for Fluter applications and now we will see a detailed understanding of each database here. Let's dive deep in each database -
1. SQLite
SQLite is a relational database management system that is used into many programming languages and frameworks, including Flutter. It stores the data locally on the device and provides a file-based storage solution for Flutter applications.
Features
- SQL Support -
SQLite supports the SQL (Structured Query Language) which allows to use SQL queries to perform CRUD(Create, Read, Update and Delete) operations. - Efficient and Fast -
Handles large data with good performance and known for its efficiency and speed. It also provides indexing mechanisms to improve query performance. - Cross-Platform Compatibility -
It works flawless on different operating systems, including Android, iOS, Windows, macOS, and Linux.
Advantages
- Local Data Storage -
SQLite helps users to store data locally within the app and allow users to access and manipulate data even when they are offline or have limited connectivity. - Performance and Efficiency -
This database is well known for its speed and efficiency. It has low resource requirements and we can retrieve data fast with query execution. - Easy Integration -
To integrate this database, you just have to add "sqflite" or "moor" packages for your app.
Disadvantages
- Single-Device Limitation -
This database is designed for local data storage on a single device. It does not provide any medium to sync across multiple devices. - Scalability Constraints -
Not suitable when you have to handle massive concurrent connections or large datasets. It is more used for small to medium-sized applications.
2. Firebase Realtime Database
This is a cloud-hosted NoSQL database provided by Google that helps developers to store and synchronize data in real-time across multiple clients and devices. This flutter database is very useful and one can handle real-time data synchronization and collaboration in the app.
Features
- NoSQL Data Model -
This follows a flexible, schema-less NoSQL data model which allows us to store and retrieve JSON-like data structures. - Offline Support -
This database provides offline support means you can continue with your work even if there is no network connection. Once you get the internet connectivity, your changes are synchronized with the remote server. - Security and Authentication -
You can always defines access rules and permissions to control who can read or write to the database. This way you secure the app data. - Real-time Synchronization -
This feature enables data synchronization which means database changes are propagated to all connected clients.
Advantages
- Cross-platform Compatibility -
This database works with all kinds of platforms like Android, iOS, and web and provides a consistent data synchronization experience across all platforms. - No Server Management -
With Firebase Realtime Database, no need to worry about setup, server management, or scaling issues as Google handles it own his own. - Easy Integration -
You just have to "firebase_database" package for using this in your project and import the package. - Real-time Updates -
This feature is also very important as it gives instant updates and collaboration and once can see real-time changes in the same time.
Disadvantages
- No Advanced Querying -
This database has limited querying capabilities with basic support of filtering and sorting. - Cost Considerations -
This is free for some limit but need to pay some amount as data storage increases. So check all prices and use according your app requirement.
3. Cloud Firestore
This database is flexible, scalable, and serverless NoSQL document database by Google. Very commonly used for Flutter applications like mobile and web. Major benefits of this databse are real-time data synchronization, offline support, and powerful querying capabilities. This is similar to Firebase Realtime Database with some advanced features.
Features
- Real-time Data Synchronization -
This enables changes made to the database are instantly propagated to all connected clients and gives seamless user experiences. - Document-Based Structure -
Data is organized into collections and documents. Each document is a set of key-value pairs, allowing for flexible and nested data structures. - Powerful Querying and Indexing -
You can perform complex queries on your data like filter, sort, and paginate data based on specific criteria.
Advantages
- Easy Integration with Flutter -
You have to integrate "cloud_firestore" package and import it on the screens you are using the database. - Offline Support & Real-time Updates -
You can work with data even without an internet connection and provides instant updates, real-time collaboration, chat features. - Scalability and Performance -
Firestore's distributed infrastructure and indexing mechanisms ensure fast and efficient querying, even with large datasets.
Disadvantages
- Cost Considerations -
As data storage and usage increases, you will need to pay and it won't be free after some storage limit. - No Joins or Server-side Computations -
Firestore does not support server-side computations or complex joins between collections.
Setting up a Database in Flutter
SQFlite
In yaml file , add the following dependency and pub get.
Opening a database
A SQLite database is a file in the file system identified by a path, obtained by getDatabasesPath(), which is the default database directory on Android and the documents directory on iOS/MacOS.
Closing a database
Create and use a database helper
This class allows you to access the database instance from anywhere in your code. It has methods to initialize the database, create a table, insert rows, and query rows.
Cloud Firestore
Create a Firebase Project
- Go to the Firebase Console and create a new project
- Enable Firestore for your project by selecting "Firestore Database" from the left navigation menu and follow the setup instructions.
Add dependencies
Add "firebase_core" and "cloud_firestore" in yaml file and pub get these.
Firebase configration
For Android- Download the google-services.json and paste it in android/app and open android/app/build.gradle file to paste below line-
For iOS - Place the GoogleService-Info.plist file inside the ios/Runner
Use Firestore in your app
Import the below packages and Initialize Firebase in your main() function. This is the basic setup for using Cloud Firestore. We will see a full example of using cloud firestore operations in flutter apps in the last of this article.
Working with a Database
Here we are going to learn about sqflite to store data on mobile devices. We have already learnt and read so much about this database and it's time to integrate it with code.
- Step 1: Add the dependencies
Add the dependencies in your yaml file and pub get these.- sqflite -
To integrate SQLite database functions. - path_provider -
The package to specify the path of the database.
- sqflite -
- Step 2: Create the data model
We will create a model defining the properties and a method to map the data before inserting into the database.
- Step 3: Adding the imports
Add the required imports to the database helper file.
- Step 4: Initialize the database
We declare a function that uses the above imports to open a database connection. This openDatabase() create the database and you can give table name, column titles here.
- Step 5: Insert
We will create a function to get the data model, convert it into a map and insert data into the database using insert() helper method. Also, we need to pass this ConflictAlgorithm.ignore to ignore the conflicts occurs due to duplicate entries.
- Step 6: Read
We can query data using methods like where, groupBy, having, orderBy and columns inside query() helper using sqflite.
- Step 7: Delete
Use the where argument in delete() helper to delete specific rows from the table.
- Step 8: Update
Use update() helper to update any record in the database and use the where argument to update specific records.
Best Practices for Working with a Database in Flutter
There are some practices to be followed to become a good developer. This gives better understanding of code and have efficient and maintainable code.
- Use should handle errors with try-catch blocks for database operations that may occur during database interactions. Give a proper message, if error occours.
- Create a separate helper class for all the database operations like initialization, table creation, CRUD operations, query executions, which makes code organized and easy to manage. This also helps new joiners to understand the code easily without taking much time and you can call methods from one single place to all other screens .
- Try to create a singleton pattern for your helper class that ensures only one instance of the database is created.
- Define model classes to represent your database which ensures type safety and improve code readability.
- Use asynchronous database operations to avoid blocking the UI thread like "async" and "await" keywords to handle database operations that may take time. This will give better user experience.
Example App
This example app is using Cloud FireStore with all operations like create, delete, update, and read the data.
This is the main.dart file and make sure to initialize Firebase here. Also, remember to add "firebase_core" and "cloud_firestore" in yaml file and other files explained in above section of Cloud FireStore database usage.
This is cloudfirestoreoperations file where we are performing all operations like create, update, delete, and read the data. Methods are described for each opeartion in the code. Make sure to replace 'DOCUMENT_ID' with the actual document ID you want to update or delete.
To see more checkout my github repo
Conclusion
- We have studied various databases with their features, advantages, and disadvantages.
- We use SQFLite when we have to store data locally in the device and works when there is no internet connection.
- Cloud Firestore is more advanced than Firebase Realtime Database in terms of performing queries.
- More commonly used flutter databases are "Hive", "Cloud Firestore", "SQFlite" and "Firebase Realtime Database".
- For simple, normal small to medium-sized apps, we can use Firebase CloudFirestore for storing data which works seamlessly if we do not have to use backend technologies.
- You will be subject to the cost for using Firebase databases if you exceed the free data storage limit.