Creating Singleton SQLite Database Connection in Flutter
hello friends today i will tell you how you can use SQLite
database in your flutter app using singleton pattern.
as you know singleton pattern only creates one instance of database connection.
first add SQLite
dependencies in your flutter app by editing pubspec.yaml
file.
dependencies:
sqflite: any
path: any
.....
be careful while editing yaml
file as they are very strict with spaces any extra space will lead to error.
then install dependencies using below command in your flutter app root directory
$ flutter pub get
if everything goes well create new package directory into lib folder of your project and on dart file named db.dart
and add the below code to that file
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class DB {
static final DB _db = new DB._internal();
DB._internal();
static DB get instance => _db;
static Database _database;
Future<Database> get database async {
if(_database != null)
return _database;
_database = await _init();
return _database;
}
Future<Database> _init() async{
return await openDatabase(
join(await getDatabasesPath(), 'database_name.db'),
onCreate: (db, version) {
db.execute(
"CREATE TABLE favourite(id INTEGER PRIMARY KEY, storeId TEXT, storeName Text, address TEXT, city TEXT, town TEXT);",
);
db.execute(
"CREATE TABLE cart(id INTEGER PRIMARY KEY, itemId INTEGER, itemDesc Text, mrp Text, qnty INTEGER);",
);
// more create statements....
},
version: 5,
);
}
}
and any where in your project you can use database like below
var db = await DB.instance.database;
be sure to use async
function if you are using await in your database instance access.
now use your query like below
var db = await DB.instance.database;
var result = await db.rawQuery("select * from cart;");
// result will store List<Map> data which you can parse to model object
I will show you how you can show list of data into your ListView
from database in other posts