Sqflite-Flutter Example from Scratch

Manoj kumar
Jan 7 · 3 min read

A basic example for CRUD Operation on Flutter App.

Add necessary libraries given below, In pubspec.yaml file

sqflite: any
path_provider: any

Starting with a basic project, Create a new Class file in whatever name, But I will name here as Employee.dart.

class Employee {String name, mobile, company;
int id;
Employee(this.name, this.mobile, this.company); //without id
Employee.withId(this.id, this.name, this.mobile, this.company);
}

Create a new class for handling the SQL queries, I named this class as DBHandler.dart. Along with it import the libraries.

class DbHandlers {
static Database _db;
Future<Database> get db async {
if (_db != null) {
return _db;
}
_db = await initDB();
return _db;
}
}

In the DbHanlder class, we have to initialize the Database.

initDB() async {Directory documentDirectory = await getApplicationDocumentsDirectory();String path = join(documentDirectory.path + 'Employee.db');// dbnamevar dbInstance = await openDatabase(path, version: 1, onCreate: _onCreate);return dbInstance;}

Now it’s time to create a table in the DB. But it should be done once while OnCreate.

void _onCreate(Database db, int version) async {await db.execute('CREATE TABLE Employee( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, mobile TEXT, company TEXT )');print('Db Created'); //just make sure that DB is created.
}

TO INSERT a record,

void saveEmployees(Employee employee) async {String name, mobile, company;name = employee.name;
mobile = employee.mobile;
company = employee.company;
var dbClient = await db;
await dbClient.transaction((txn) async {
return await txn.rawInsert('INSERT INTO EMPLOYEE(name,mobile,company) VALUES ( ?, ?, ? )', [name, mobile, company]);
});
}

While Retrieving all records, We get more than one records so we make this function to return values in a LIST.

Future<List<Employee>> getEmployees() async {var dbClient = await db;List<Map> employeeList = await dbClient.rawQuery('SELECT * FROM EMPLOYEE');List<Employee> employess = new List();for (var i = 0; i < employeeList.length; i++) {employess.add(new Employee.withId(employeeList[i]["id"], employeeList[i]["name"], employeeList[i]["mobile"], employeeList[i]["company"]));}print(employess.length);return employess;}

To delete a record,

void deleteEmployee(int id) async {var dbClient = await db;await dbClient.transaction((txn) async {return await txn.rawDelete('DELETE FROM EMPLOYEE WHERE id = $id');});
}

Now, We all set to go for the UI part. UI is soo simple just using 3 text fields along with their controllers. I think it is an easy task, so I will skip this UI part, But I will show how to call the DBHandler from the UI.

While Inserting or saving the records.

Place this function below your main function or constructor( executes while creating the instance) function.

This is to fetch all the data as a list

This is the main UI part of displaying all the details of the employee.

Using Future Builder widget

Now it’s time Test,

I think it’s finished now, Try to update the records. If any doubts above Kindly mail me manojvirat457@gmail.com

Be passionate about what you Like.

Build for Billions

We make the technology, understandable for people. We believe that combination of Applied Science, mathematics, computers and Creativity led the world to innovate beyond the limits.

Manoj kumar

Written by

தமிழன், Engineer, programmer, History lover https://manojkumar-me.firebaseapp.com

Build for Billions

We make the technology, understandable for people. We believe that combination of Applied Science, mathematics, computers and Creativity led the world to innovate beyond the limits.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade