flutter 앱은 pub.dev에서 제공되는 플러그인 sqflite
을 통해 SQLite 데이터베이스를 활용할 수 있다.
sqflite
는 SQLite 데이터베이스와 상호 작용하는 클래스와 함수를 제공dependencies:
sqflite: ^2.3.0
path
는 디스크에 데이터베이스를 저장할 위치를 정의하는 기능을 제공dependencies:
path: ^1.8.3
데이터베이스에서 데이터를 읽고 쓰기전에 데이터베이스에 대한 연결을 연다.
1. sqflite의 getDatabasesPath()
와 path의 join
함수를 사용하여 데이터베이스 파일 경로 정의
2. sqflite의 openDatabase()
함수를 이용하여 데이터베이스 열기
Database? db;
Future init() async{
db = openDatabase(
join(await getDatabasesPath(), 'food_database.db'),
);
}
Future<void> onCreateDB(Database db, int version) {
return db.execute('''create table $tableFood (
$columnId integer primary key autoincrement,
$columnName text not null,
$columnPurchaseDate text not null,
$columnExpirationDate text not null,
$columnQuantity text not null,
$columnUnit text not null)''');
}
Future init() async {
db = await openDatabase(
join(await getDatabasesPath(), 'food_database.db'),
onCreate: onCreateDB,
version: 1,
);
}
Future<Database> get database async {
if (db != null) return db!;
await init();
return db!;
}
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'purchaseDate': purchaseDate,
'expirationDate': expirationDate,
'quantity': quantity,
'unit': unit,
};
}
Future<void> insert(Food food) async {
final db = await database;
await db.insert(tableFood, food.toMap());
}
List<Map>
returnList<Map>
을 List<Food>
로 변환.Future<List<Food>> foods() async {
List<Food> foods = [];
final db = await database;
final List<Map<String, dynamic>> maps = await db.query(tableFood);
for (var map in maps) {
foods.add(Food.fromJson(map));
}
return foods;
}
Future<void> update(Food food) async {
final db = await database;
await db.update(
tableFood,
food.toMap(),
where: 'id = ?',
whereArgs: [food.id],
);
}
delete()을 사용하여 제거
Future<void> delete(int id) async {
final db = await database;
await db.delete(
tableFood,
where: 'id = ?',
whereArgs: [id],
);
}
참조
flutter.dev