Flutter Database ConceptsA database is an organized collection of data, which supports the storage and manipulation of data and accessed electronically from a computer system. We can organize data into rows, columns, tables, and indexes. It makes data management easy. We can store many things in the database, like name, age, picture, image, file, pdf, etc. Flutter provides many packages to work with the database. The most used and popular packages are:
SQLite DatabaseSQLite is a popular database software library that provides a relational database management system for local/client storage. It is a light-weight and time-tested database engine and contains features like self-contained, server-less, zero-configuration, transactional SQL database engine. Flutter SDK does not support SQLite directly. Instead, it provides a plugin sqflite, which performs all operations on the database as similar to the SQLite library. The sqflite provides most of the core functionalities related to the database are as follows:
Let us see step by step how we can store and fetch data in the Flutter. Step 1: First, create a new project in Android Studio and add the dependencies in pubspec.yaml file.
Step 2: Create a model class. In this step, we have to define the data that needs to be stored before creating a table to store information. The following code explains it easily. Step 3: Open the database. Here, we need to open the connection to the database. It requires two steps:
Step 4: Create the table. In this step, we have to create a table that stores information about the books. Here, we are going to create a table named books, which contains the id, title, and price of the books. They are represented as three columns in the book table. Step 5: Insert a Book into the database. Here, you have to store information on the table about the various books. Inserting a book into the table involves two steps:
The following code explains it more clearly. Step 6: Retrieve the list of books. Now, we have stored the book into the database, and you can use a query to retrieve a particular book or list of all books. It involves two steps:
You can see the following code to understand it easily. Step 7: Update a Book in the database. You can use an update() method to update the book that you want. It involves two steps:
You can see the following code to understand it. Step 8: Delete a Book from the database. You can use the delete() method to delete the database. For this, you need to make a function that takes an id and delete the database of the matching id. Let us see the complete code to understand how we can create a database file with sqflite plugin. For this, create a new Flutter project and the sqflite and path package into the pubspec.yaml file. Next, create a new file into the lib folder and insert the following code in this file. Now, connect the database with your UI and run the code. Next TopicFlutter Testing |