Files
GitJournal/lib/file_storage.dart
Vishesh Handa 0cb36b2981 Make the state global and connect the add note screen
This is a huge work in progress, but it finally seems to kinda work.
2018-05-21 16:51:29 +02:00

53 lines
1.2 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import './note.dart';
class FileStorage {
final Future<Directory> Function() getDirectory;
FileStorage({@required this.getDirectory});
Future<List<Note>> loadNotes() async {
final dir = await getDirectory();
var notes = new List<Note>();
var lister = dir.list(recursive: false);
await for (var fileEntity in lister) {
Note note = await _loadNote(fileEntity);
notes.add(note);
}
return notes;
}
Future<Note> _loadNote(FileSystemEntity entity) async {
if (entity is! File) {
return null;
}
var file = entity as File;
final string = await file.readAsString();
final json = JsonDecoder().convert(string);
return new Note.fromJson(json);
}
Future<Directory> saveNotes(List<Note> notes) async {
final dir = await getDirectory();
//await dir.delete(recursive: true);
for (var note in notes) {
var filePath = p.join(dir.path, note.id);
var file = new File(filePath);
var contents = JsonEncoder().convert(note.toJson());
await file.writeAsString(contents);
}
return dir;
}
}