Impementing the logic

Installing needed packages

To make our project works we need some dependency, so let's jump to pubspec.yaml file and install those 3 packages.

sqflite:
path:
path_provider:

Now it's time to do some logic, we will separate our UI from the logic that's why we have created the models and services folders.

Creating product model

Let's go to product.dart file in the the /models folder and create some attributes and methods there.

First thing let's create a class called Product with some attributes

class Poduct {
  int _id;
  String _name;
  String _description;
  double _price;
}

because we have declared those attributes as private attribute we need create some getters.

  ///geters
  int get id => _id;
  String get name => _name;
  String get description => _description;
  double get price => _price;

We also need to create a constructor that takes an object as a parameter and stock each value in it's own property.

  Product(dynamic obj) {
    _id = obj['id'];
    _name = obj['name'];
    _description = obj['description'];
    _price = obj['price'];
  }

And the same, we are going to create named constructor that will take a Map as a parameter.

  Product.fromMap(Map<String, dynamic> data) {
    _id = data['id'];
    _name = data['name'];
    _description = data['description'];
    _price = data['price'];
  }

So the last thing in this file we need to add is a method that will do the opposite of the constructor that will transform an object to json or map.

  Map<String, dynamic> toJson() {
    return {
      'id': _id,
      'name': _name,
      'description': _description,
      'price': _price,
    };
  }

That's all for product.dart file, now it's time to jump to the services folder and do some stuffs there.

Creating database connection service

Now we need to implement the logic behind connecting and all the other crud operations related to sqlite database. So let's go to services and open the dbhelper.dart. in this file we'll add a bunch of methods.

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

class DbHelper {
  //create a singleton class
  static final DbHelper _singleton = DbHelper._internal();
  factory DbHelper() => _singleton;
  DbHelper._internal();

  //creating an object of type Database
  static Database _database;

  //initializing the database and ceating a database named mydb.db
  //creating a products table with neccessary fields.
  Future<Database> initDatabase() async {
    //if this class was never instaciated we will execute this method
    if (_database != null) return _database;
    String path = join(await getDatabasesPath(), 'mydb.db');
    _database = await openDatabase(
      path,
      version: 1,
      onCreate: (Database db, int v) {
        db.execute(
            'create table products(id integer primary key autoincrement, name varchar(50), description varchar(255), price double)');
      },
    );
    return _database;
  }

  //select all products
  Future<List> getProducts() async {
    Database db = await initDatabase();
    return await db.query('products');
  }

  //create new product
  Future<int> createProduct(Product product) async {
    Database db = await initDatabase();
    return await db.insert('products', product.toJson());
  }

  //update a product
  Future<int> updateProduct(Product product) async {
    Database db = await initDatabase();
    return await db.update('products', product.toJson(),
        where: 'id=?', whereArgs: [product.id]);
  }

  //delete a product
  Future<int> deleteProduct(int productId) async {
    Database db = await initDatabase();
    return await db.delete('products', where: 'id=?', whereArgs: [productId]);
  }
}