76 lines
1.9 KiB
Dart
76 lines
1.9 KiB
Dart
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
|
import 'package:path/path.dart';
|
|
import '../models/product.dart';
|
|
|
|
class DatabaseHelper {
|
|
static final DatabaseHelper _instance = DatabaseHelper._internal();
|
|
static Database? _database;
|
|
|
|
factory DatabaseHelper() {
|
|
return _instance;
|
|
}
|
|
|
|
DatabaseHelper._internal();
|
|
|
|
Future<Database> get database async {
|
|
if (_database != null) {
|
|
return _database!;
|
|
}
|
|
_database = await _initDatabase();
|
|
return _database!;
|
|
}
|
|
|
|
Future<Database> _initDatabase() async {
|
|
String documentsDirectory = await getDatabasesPath();
|
|
String path = join(documentsDirectory, 'product_database.db');
|
|
|
|
return await openDatabase(path, version: 1, onCreate: _onCreate);
|
|
}
|
|
|
|
Future<void> _onCreate(Database db, int version) async {
|
|
await db.execute('''
|
|
CREATE TABLE products(
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name TEXT NOT NULL,
|
|
code TEXT NOT NULL,
|
|
quantity INTEGER NOT NULL,
|
|
price REAL NOT NULL,
|
|
description TEXT
|
|
)
|
|
''');
|
|
}
|
|
|
|
Future<int> insertProduct(Product product) async {
|
|
final db = await database;
|
|
return await db.insert(
|
|
'products',
|
|
product.toMap(),
|
|
conflictAlgorithm: ConflictAlgorithm.replace,
|
|
);
|
|
}
|
|
|
|
Future<List<Product>> getProducts() async {
|
|
final db = await database;
|
|
final List<Map<String, dynamic>> maps = await db.query('products');
|
|
|
|
return List.generate(maps.length, (i) {
|
|
return Product.fromMap(maps[i]);
|
|
});
|
|
}
|
|
|
|
Future<int> updateProduct(Product product) async {
|
|
final db = await database;
|
|
return await db.update(
|
|
'products',
|
|
product.toMap(),
|
|
where: 'id = ?',
|
|
whereArgs: [product.id],
|
|
);
|
|
}
|
|
|
|
Future<int> deleteProduct(int id) async {
|
|
final db = await database;
|
|
return await db.delete('products', where: 'id = ?', whereArgs: [id]);
|
|
}
|
|
}
|