import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:sqflite/sqflite.dart'; import 'package:cpd/database/db.dart'; import 'package:cpd/database/habit.dart'; class TodoDB { final tableName = 'todos'; Future createTable(Database database) async { await database.execute("""CREATE TABLE IF NOT EXISTS $tableName ( id INTEGER PRIMARY KEY AUTOINCREMENT, isComplete INTEGER NOT NULL, title TEXT NOT NULL, subtitle TEXT, icon TEXT )"""); } Future create({required String title, required String subtitle, required IconData icon}) async { final database = await HabitDatabase().database; final result = await database.rawInsert( '''insert into $tableName (isComplete, title, subtitle, icon) values (?,?,?,?)''', [0 ,title, subtitle, _iconDataToString(icon)], ); if (result != null) { return result; } else { print('Database insert operation failed'); return 0; // oder eine andere Standardaktion } } IconData _stringToIconData(String iconString) { final decoded = jsonDecode(iconString); return IconData( decoded['codePoint'], fontFamily: decoded['fontFamily'], fontPackage: decoded['fontPackage'], matchTextDirection: decoded['matchTextDirection'], ); } String _iconDataToString(IconData icon) { return jsonEncode({ 'codePoint': icon.codePoint, 'fontFamily': icon.fontFamily, 'fontPackage': icon.fontPackage, 'matchTextDirection': icon.matchTextDirection, }); } Future> fetchAll() async { final database = await HabitDatabase().database; final todos = await database.query(tableName); return todos.map((todo) { final habit = Habit.fromSqfliteDatabase(todo); habit.icon = _stringToIconData(todo['icon'] as String); return habit; }).toList(); } Future fetchById(int id) async { final database = await HabitDatabase().database; final todo = await database.query(tableName, where: 'id = ?', whereArgs: [id]); if (todo.isNotEmpty) { // Überprüfen, ob todo nicht null ist und nicht leer ist final habit = Habit.fromSqfliteDatabase(todo.first); habit.icon = _stringToIconData(todo.first['icon'] as String); return habit; } else { return null; // Wenn kein Eintrag gefunden wurde, geben Sie null zurück } } Future update({required int id, required String title, required String subtitle, required IconData icon}) async { final database = await HabitDatabase().database; return await database.update(tableName,{ 'title': title, 'subtitle': subtitle, 'icon': _iconDataToString(icon), }, where: 'id = ?', conflictAlgorithm: ConflictAlgorithm.rollback, whereArgs: [id], ); } Future delete(int id) async { final database = await HabitDatabase().database; await database.delete(tableName, where: 'id = ?', whereArgs: [id]); } Future? updateCompletionStatus(int id, bool isCompleted) async { final database = await HabitDatabase().database; return await database.update(tableName,{ 'isComplete': isCompleted, }, where: 'id = ?', conflictAlgorithm: ConflictAlgorithm.rollback, whereArgs: [id], ); } }