Skip to content

Instantly share code, notes, and snippets.

@aniekan12
Created October 18, 2021 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aniekan12/7e4dfee6011fad4949a729fd002ec4e0 to your computer and use it in GitHub Desktop.
Save aniekan12/7e4dfee6011fad4949a729fd002ec4e0 to your computer and use it in GitHub Desktop.
// class name
class SqfliteDatabaseHelper {
//instantiate an object that can be called anywhere in the app
static final SqfliteDatabaseHelper instance = SqfliteDatabaseHelper._init();
//table name stored in a string
final String demandNoticeTable = 'demandNoticeTable';
//database initialization
SqfliteDatabaseHelper._init();
//Database object
static Database _db;
//Database creation
Future<Database> get db async {
if (_db != null) {
return _db;
}
_db = await initDb('ekirss.db');
return _db;
}
//Method to create database
Future<Database> initDb(String filePath) async {
final dbPath = await getDatabasesPath();
final path = join(dbPath, filePath);
print(dbPath);
var openDb = await openDatabase(
path,
version: 2,
onCreate: _createDb,
);
return openDb;
}
//method to create table
Future _createDb(Database db, int version) async {
final idType = 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL';
final textType = 'TEXT';
await db.execute('''
CREATE TABLE $demandNoticeTable(
${DemandFields.id} $idType,
${DemandFields.propertyId} $textType,
)''');
}
//Method to add data to the table
Future<DemandNoticeModel> addDemand(DemandNoticeModel demandNotice) async {
final db = await instance.db;
final id = await db.insert(demandNoticeTable, demandNotice.toJson());
return demandNotice.copy(id: id);
}
//Method to fetch data from the table
Future<List<dynamic>> fetchAllDemand() async {
final db = await instance.db;
List<dynamic> demandList= [];
try {
final maps =
await db.query(SqfliteDatabaseHelper.instance.demandNoticeTable);
for (var item in maps) {
contactList.add(DemandNoticeModel.fromJson(item));
}
} catch (e) {
print(e.toString());
}
return demandList;
}
//Method to close database
Future close() async {
final dab = await instance.db;
dab.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment