import 'dart:io'; import 'dart:convert'; class Todolist { String filename = ''; Todolist([String filename = 'todolist.json']) { this.filename = filename; bool fileExist = File(this.filename).existsSync() && FileSystemEntity.isFileSync(this.filename); if (!fileExist) { File(this.filename).createSync(); File(this.filename).writeAsStringSync('[]'); }; } List getAll() { String contentFile = File(this.filename).readAsStringSync().trim(); List object = jsonDecode(contentFile); return object; } Map? getByNoUrut(int noUrut) { int indek = noUrut - 1; Map? result; List todos = this.getAll(); if (todos.asMap().containsKey(indek)) { result = todos[indek]; }; return result; } bool add({required int nrp, required String name, required String todo, bool is_active = true, bool is_done = false}) { bool result = false; Map newTodo = { 'nrp' : nrp, 'name' : name, 'todo' : todo, 'is_active': is_active, 'is_done' : is_done, }; List allTodo = this.getAll(); int todoLength = allTodo.length; allTodo.insert(todoLength, newTodo); if(allTodo.asMap().containsKey(todoLength)){ File(this.filename).writeAsStringSync(jsonEncode(allTodo)); result = true; }; return result; } bool edit(int noUrut, {int? nrp, String? name, String? todo, bool? is_active, bool? is_done}) { bool result = false; int indek = noUrut - 1; List allTodo = this.getAll(); if(allTodo.asMap().containsKey(indek)) { Map todoData = allTodo[indek]; todoData['nrp'] = nrp == null ? todoData['nrp'] : nrp; todoData['name'] = name == null ? todoData['name'] : name; todoData['todo'] = todo == null ? todoData['todo'] : todo; todoData['is_active'] = is_active == null ? todoData['is_active'] : is_active; todoData['is_done'] = is_done == null ? todoData['is_done'] : is_done; allTodo[indek] = todoData; File(this.filename).writeAsStringSync(jsonEncode(allTodo)); result = true; }; return result; } bool deleteByNoUrut(int noUrut) { bool result = false; int indek = noUrut - 1; List allTodo = this.getAll(); if(allTodo.asMap().containsKey(indek)) { allTodo.removeAt(indek); File(this.filename).writeAsStringSync(jsonEncode(allTodo)); result = true; }; return result; } }