Flutter is an object-oriented programming language primarily used for mobile development. We need to connect with a database to create a working mobile application and implement the essential
The required dependencies are as follows:
dependencies:flutter:sdk: fluttersqflite:path:
The required imports to establish a connection with the SQLite database are as follows:
import 'dart:async'import 'package:path/path.dart'import 'package:sqflite/sqflite.dart'import 'package:flutter/widgets.dart'
In the above code:
Line 1: The async
import is required to use 'await' calls in the code.
Line 2: The path
package defines the disk location that stores our database.
Line 3: The sqflite
package provides functions and classes to communicate with the database. It is an SQLite plugin for flutter.
Line 4: The flutter/widgets.dart
import provides the widget library to our application.
The communication between database and data occurs in the form of objects. So, we need to define what we want to insert into the database.
Suppose we are developing a student management system. Let's start with how to implement CRUD operations of the Student
class.
Firstly, we need to define the Student
class:
class Student{final String email;final String name;final int age;final String rollNo;//constructorStudent({required this.email,required this.name,required this.age,required this.rollNo,});}
The final
keyword declares a variable at runtime, and a value is assigned to it only once.
The required
keyword represents that a value is necessary for the following variable.
The this
keyword represents the current class and its variables.
To use the CRUD operations, we need to establish a connection to the database first:
WidgetsFlutterBinding.ensureInitialized();final db = openDatabase(join(await getDatabasesPath(),'studentDB'),);
Line 1: The WidgetsFlutterBinding.ensureInitialized()
function declares an instance that interacts with the flutter engine.
Line 2: The openDatabase()
function establish a link of the database into a variable, and the join()
function sets the path of the database.
We open a channel to the database named studentDB
.
Note: To learn about
await
functionality, click here.
Following is the implementation of the CRUD operations in a flutter:
After defining the database, create the Student
table by the following code:
WidgetsFlutterBinding.ensureInitialized();final db = openDatabase(join(await getDatabasesPath(),'studentDB'),onCreate:(db,ver){return db.execute('CREATE TABLE Student(email TEXT PRIMARY KEY, name TEXT, age INTEGER, rollNo TEXT)',);},//version is used to execute onCreate and make database upgrades and downgrades.version:1,);
Lines 4 to 6: The onCreate
determines what the database should do once a link is established. Here, the db.execute()
function is executed that contains the SQL query we need to use.
Use the following code to insert a student
object into the database:
class Student{final String email;final String name;final int age;final String rollNo;//constructorStudent({required this.email,required this.name,required this.age,required this.rollNo,});Map<String, dynamic> mapStudent() {return {'email': email,'name': name,'age': age,'rollNo':rollNo,};}}
Note: mapStudent() function is required to convert a student object into a map object that can be stored in the database.
//the 'future' keyword defines a function that works asynchronouslyFuture<void> insertStudent(Student student) async{//local database variablefinal curDB = await db//insert functionawait curDB.insert(//first parameter is Table name'Student',//second parameter is data to be insertedstudent.mapStudent(),//replace if two same entries are insertedconflictAlgorithm: ConflictAlgorithm.replace,);}
we are using insert()
function to insert data in to student table.This will get two parameters
Table name
Data to be inserted
var studentOne = Student(email:'studentOne@gmail.com',name:'XYZ', age:20, rollNo:'2P-23');await insertStudent(studentOne);
Use the following code to retrieve students from the database:
Future<List<Student>> getStudents() async {final curDB = await db;//query to get all students into a Map listfinal List<Map<String, dynamic>> studentMaps = await curDB.query('Student');//converting the map list to student listreturn List.generate(studentMaps.length, (i) {//loop to traverse the list and return student objectreturn Student(email: studentMaps[i]['email'],name: studentMaps[i]['name'],age: studentMaps[i]['age'],rollNo: studentMaps[i]['rollNo'],);});}
To read data from table we are using generate function this will return the student object.
print(await getStudents());
Use the following code to update the data of a specific student:
Future<void> updateStudent(Student student) async {final curDB = await db;//update a specific studentawait curDB.update(//table name'Student',//convert student object to a mapstudent.mapStudent(),//ensure that the student has a matching emailwhere: 'email = ?',//argument of where statement(the email we want to search in our case)whereArgs: [student.email],);}
var studentUpdate = Student(email: studentOne.email,name: studentOne.name,age: studentOne.age + 7,rollNo: studentOne.rollNo,);await updateStudent(studentUpdate);// Print the updated results.print(await getStudents());
Use the following code for deletion:
Future<void> deleteStudent(String email) async {final curDB = await db;// Delete operationawait curDB.delete(//table name'Student',//'where statement to identify a specific student'where: 'email = ?',//arguments to the where statement(email passed as parameter in our case)whereArgs: [email],);}
To delete some recoed we can use delete()
function which will get two parameters first is table name and second one is any query parameter which is used to select a record.
deleteStudent("studentOne@gmail.com")
The main.dart file should look like the following code:
import 'dart:async';import 'package:path/path.dart';import 'package:sqflite/sqflite.dart';import 'package:flutter/widgets.dart';//db variablevar db;//main functionvoid main() async{WidgetsFlutterBinding.ensureInitialized();//connection and creationdb = openDatabase(join(await getDatabasesPath(),'studentDB'),onCreate:(db,ver){return db.execute('CREATE TABLE Student(email TEXT PRIMARY KEY, name TEXT, age INTEGER, rollNo TEXT)',);},//version is used to execute onCreate and make database upgrades and downgrades.version:1,);//insertionvar studentOne = Student(email:'studentOne@gmail.com',name:'XYZ', age:20, rollNo:'2P-23');await insertStudent(studentOne);//readprint(await getStudents());//updationvar studentUpdate = Student(email: studentOne.email,name: studentOne.name,age: studentOne.age + 7,rollNo: studentOne.rollNo,);await updateStudent(studentUpdate);// Print the updated results.print(await getStudents());//deletiondeleteStudent("studentOne@gmail.com");}//Classclass Student{final String email;final String name;final int age;final String rollNo;//constructorStudent({required this.email,required this.name,required this.age,required this.rollNo,});Map<String, dynamic> mapStudent() {return {'email': email,'name': name,'age': age,'rollNo':rollNo,};}}//Insert//the 'future' keyword defines a function that works asynchronouslyFuture<void> insertStudent(Student student) async{//local database variablefinal curDB = await db;//insert functionawait curDB.insert(//first parameter is Table name'Student',//second parameter is data to be insertedstudent.mapStudent(),//replace if two same entries are insertedconflictAlgorithm: ConflictAlgorithm.replace,);}//ReadFuture<List<Student>> getStudents() async {final curDB = await db;//query to get all students into a Map listfinal List<Map<String, dynamic>> studentMaps = await curDB.query('Student');//converting the map list to student listreturn List.generate(studentMaps.length, (i) {//loop to traverse the list and return student objectreturn Student(email: studentMaps[i]['email'],name: studentMaps[i]['name'],age: studentMaps[i]['age'],rollNo: studentMaps[i]['rollNo'],);});}//UpdateFuture<void> updateStudent(Student student) async {final curDB = await db;//update a specific studentawait curDB.update(//table name'Student',//convert student object to a mapstudent.mapStudent(),//ensure that the student has a matching emailwhere: 'email = ?',//argument of where statement(the email we want to search in our case)whereArgs: [student.email],);}//DeleteFuture<void> deleteStudent(String email) async {final curDB = await db;// Delete operationawait curDB.delete(//table name'Student',//'where statement to identify a specific student'where: 'email = ?',//arguments to the where statement(email passed as parameter in our case)whereArgs: [email],);}
Line 11 – 18: We create and connect to a database named studentDB
and create a table named Student
.
Line 21 – 22: We insert a student in our table named Student
using the insert
keyword.
Line 24: We read a table named student
using the getStudents()
function.
Line 26 – 32 : We update the existing record of the student using the updateStudent()
function.
Line 36 : We delete the record containing the given email using the deleteStudent()
function.
Line 39 – 59 : We create a model of student class named Student
.
Line 62 – 72 : We create a function for the insertion of student data named as insertStudent
using the insert()
function in which first parameter is table_name
and the second parameter is the data
to be inserted.
Line 76 – 90 : We create a function for reading student data from the table named as getStudents
.
Line 95 – 105 : We create a function for updating student data in the Student
table named as updateStudent
.
Line 107 – 118 : We create a function named as deleteStudent
to delete a record from student table. here we are using Where
clause to identify a specific student to which we want to delete.
Note : Here we are using
future
key word while creating the function this will create an asynchronous function.
Free Resources