For SQL storage in the device we need to first package from pub.dev named sqflite and path package which are required for setting up DB and to create the path for the device respectively.
We can use below code for the DB connection setup inside Dbhelper class(name can be changed)
static Future<sql.Database> dbConnection() async {
final dbPath = await sql.getDatabasesPath();
return await sql.openDatabase(
path.join(dbPath, 'users.db'),
onCreate: (db, version) {
return db.execute(
'CREATE TABLE users_tx (id TEXT PRIMARY KEY,usage TEXT,txAmount REAL,
txDate TEXT,category TEXT,currencyid INTEGER)');
},
version: 5,
);
}
in this openDatabase function will check if DB is present at the path given and if found it will return it and else it will execute oncreate partt and create the Db and executing it and returning the Database
for this we will need to have imports
import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart' as pathProvider;
Now this databse can be used wuth other methods in the same class which can be used from other widgets directly without initializing the class as we are making these methods as static
static Future<List<Map<String, dynamic>>> selectData(String table) async {
final db = await DBHelper.dbConnection();
return await db.query(table);
}
These all will be Future as these are async functions, below are the some other moths which can also be used
static Future<int> updateData(String table, TransactionData td) async {
final db = await DBHelper.dbConnection();
return await db.update(table, {
'id': td.id,
'usage': td.usedFor,
'txAmount': td.txAmount,
'txDate': td.txDate.toIso8601String(),
'category': td.category,
'currencyid': td.currencyid,
});
}
static Future<int> deleteData(String table, String id) async {
final db = await DBHelper.dbConnection();
return await db.delete(table, where: 'id==?', whereArgs: [id]);
}