cpd_2022_zi/lib/service/database_service.dart

52 lines
1.4 KiB
Dart

import 'dart:async';
import 'package:path/path.dart';
import 'package:smoke_cess_app/models/mood.dart';
import 'package:sqflite/sqflite.dart';
// ignore: depend_on_referenced_packages
import 'package:path_provider/path_provider.dart';
import 'dart:io';
class DatabaseService {
DatabaseService._privateConstructor();
static final DatabaseService instance = DatabaseService._privateConstructor();
static Database? _database;
Future<Database> get database async => _database ??= await _initDatabase();
Future<Database> _initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'database.db');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE mood(
id INTEGER PRIMARY KEY,
value INTEGER,
date TEXT,
comment TEXT
)
''');
}
Future<List<Mood>> getMoodRecords() async {
Database db = await instance.database;
var moodRecords = await db.query('mood');
List<Mood> moodList = moodRecords.isNotEmpty
? moodRecords.map((e) => Mood(1, 'comment', DateTime.now())).toList()
: [];
return moodList;
}
Future<int> addMood(Mood mood) async {
Database db = await instance.database;
return await db.insert('mood', mood.toMap());
}
}