2024-10-29 13:13:10 +01:00
|
|
|
import 'dart:convert';
|
|
|
|
import 'dart:io';
|
|
|
|
|
|
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
import 'package:todo/buisness/ToDoItem.dart';
|
|
|
|
import 'package:todo/database/DatabaseInterface.dart';
|
|
|
|
|
2024-10-29 19:06:41 +01:00
|
|
|
class PathProvider implements DatabaseInterface {
|
2024-10-29 13:13:10 +01:00
|
|
|
Future<String> get _localPath async {
|
|
|
|
final directory = await getApplicationDocumentsDirectory();
|
|
|
|
return directory.path;
|
|
|
|
}
|
|
|
|
Future<File> get _localFile async {
|
|
|
|
final path = await _localPath;
|
2024-10-30 23:41:56 +01:00
|
|
|
print(path);
|
2024-10-29 13:13:10 +01:00
|
|
|
File file = File('$path/dataSeq.txt');
|
|
|
|
if (!file.existsSync()) {
|
|
|
|
file = await file.create();
|
|
|
|
await file.writeAsString('[]');
|
|
|
|
}
|
|
|
|
return file;
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<List<ToDoItem>> getToDoItems() async {
|
|
|
|
final file = await _localFile;
|
|
|
|
final contents = await file.readAsString();
|
2024-10-30 23:41:56 +01:00
|
|
|
final contentJson = jsonDecode(contents);
|
2024-10-29 13:13:10 +01:00
|
|
|
|
2024-10-30 23:41:56 +01:00
|
|
|
List<dynamic> contentList = contentJson is List ? contentJson : [contentJson];
|
|
|
|
|
|
|
|
List<ToDoItem> toDoList = contentList.map((item) => ToDoItem.fromJson(item)).toList();
|
2024-10-29 19:06:41 +01:00
|
|
|
return toDoList;
|
2024-10-29 13:13:10 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<File> insertToDoItem(ToDoItem item) async {
|
|
|
|
item.id = DateTime.now().millisecondsSinceEpoch;
|
|
|
|
List<ToDoItem> l = await getToDoItems();
|
|
|
|
l.add(item);
|
|
|
|
final file = await _localFile;
|
2024-10-30 23:41:56 +01:00
|
|
|
return file.writeAsString(jsonEncode(l.map((item) => item.toJson()).toList()));
|
2024-10-29 13:13:10 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<File> updateToDoItem(ToDoItem item) async {
|
|
|
|
final file = await _localFile;
|
2024-10-30 23:41:56 +01:00
|
|
|
return file.writeAsString(jsonEncode(item.toJson()));
|
2024-10-29 13:13:10 +01:00
|
|
|
}
|
|
|
|
|
2024-10-29 19:06:41 +01:00
|
|
|
@override
|
|
|
|
Future<File> deleteToDoItem(int id) async {
|
|
|
|
final file = await _localFile;
|
|
|
|
List<ToDoItem> l = await getToDoItems();
|
2024-10-30 23:41:56 +01:00
|
|
|
l.remove(l.firstWhere((item) => item.id == id));
|
|
|
|
return file.writeAsString(jsonEncode(l.map((item) => item.toJson()).toList()));
|
2024-10-29 19:06:41 +01:00
|
|
|
}
|
|
|
|
|
2024-10-29 13:13:10 +01:00
|
|
|
}
|