Flutter SQLite Tutorial And Free Code

First of all, Add the SQLite Plugin from Pub.dev and add the dependencies on pubspec.yamal file. (Flutter SQLite Tutorial)

dependencies:
  flutter:
    sdk: flutter
  sqflite:

First Create a Model class to handle inserting and receiving data easily and also create a toMap() which helps to convert the model object to Map with String, Dynamic value.

class Task {
  final int id;
  final String title;
  final String description;
  Task({this.id = 0, this.title = " ", this.description = ""});
  //  Helps us to create the map if the object  {Conversion of object to map}
  Map<String, dynamic> toMap() {
    return {
      "id": id,
      "title": title,
      "description": description,
    };
  }
}

Creating a Database Helper Class (SQLite Database)

Create a separate class that will handle all Database related queries Called databaseHelper.dart or anything. And also create the Model-class which helps to handle data.

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';


class DatabaseHelper {

   //DataBase Healper Class

}

Add the import statements of SQLite and Path.

Creatin table in database and Receiving database

Create First Function which will find the path of the database if exist and create a new database, even run the first query to make a table in our database.

Future<Database> dataBase() async {
    return openDatabase(
      join(await getDatabasesPath(), "todo_db.db"),
      onCreate: (db, version) async {
        // Run the CREATE TABLE statement on the database.
        await db.execute(
          "CREATE TABLE tasks(id INTEGER PRIMARY KEY, title TEXT, description TEXT)",
        );
      },
      version: 1,
    );
  }

here Above line create a table in the database if not exist and Return the database to use later for further queries.

Insert Function which will insert the values in the table

Future<int> insertTask(Task task) async {
    int taskId = 0;
    Database _db = await dataBase();
    await _db
        .insert(
      "tasks",
      task.toMap(),
    )
        .then((value) {
      taskId = value;
    });
    return taskId;
  }

here we are using the Task model class to add the details to the table, Task Model Class we created at the beginning of this post. And even getting the Id.

Get Function which will get the values in the table (From Flutter SQLite Database)

we added values to our tables. Now time to receive those values for further use.

  Future<List<Task>> getTasks() async {
    Database _db = await dataBase();
    List<Map<String, dynamic>> taskMap = await _db.query("tasks");
    return List.generate(taskMap.length, (index) {
      return Task(
          id: taskMap[index]["id"],
          title: taskMap[index]["title"],
          description: taskMap[index]["description"]);
    });
  }

The above Function helps to get data from our Flutter SQLite Database. This line _db.query(“tasks”); receive Data as List of Maps with String is the key and Dynamic type of values. And we are using List. generate to get all values and assign them to a proper variable.

Delete Function which will delete the values in the table

This function will take care of deleting any row in our database table.

  Future<void> deleteTask(int? id) async {
    Database _db = await dataBase();
   await _db.rawDelete("DELETE FROM tasks WHERE id = '$id'");

  }

This Takes ID which tells this function to delete a particular row according to that provided ID.

Update Function which will update the values in the table

When we want to update something in our table some particular value needs to be updated this function will take care of it.

 Future<void> updateIsDone(int id, int isDone) async {
    Database _db = await dataBase();
    _db.rawUpdate("UPDATE todo SET isDone = '$isDone' WHERE id = '$id'");
  }

it takes two parameters one is ID again which tells where to change and another one is the Value that needs to be changed or updated.

well, these all functions will help to use the SQLite plugin in Flutter and Use them in your app. This the end of this Tutorial

Flutter SQLite Tutorial


For more Flutter tutorials, Tips, Tricks, Free code, Questions, and Error Solving.

Remember FlutterDecode.com

Leave a Comment