file_storage.dart 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import 'dart:async' show Future;
  2. import 'dart:io' show File;
  3. import 'package:pb_authenticator_state/file_storage_base.dart';
  4. import 'package:path_provider/path_provider.dart'
  5. show getApplicationDocumentsDirectory;
  6. /// Loads/stores file to application storage directory
  7. ///
  8. /// From:
  9. /// * https://flutter.io/docs/cookbook/persistence/reading-writing-files
  10. class FileStorage extends FileStorageBase {
  11. /// Instantiates instance of FileStorage
  12. FileStorage();
  13. /// Gets path of Application Documents Directory.
  14. @override
  15. Future<String> getDataPath() async {
  16. final directory = await getApplicationDocumentsDirectory();
  17. return directory.path;
  18. }
  19. Future<File> _filePath(String filename) async {
  20. var path = await getDataPath();
  21. return File('$path/$filename');
  22. }
  23. /// Whether file is present.
  24. @override
  25. Future<bool> hasFile(String filename) async {
  26. final file = await _filePath(filename);
  27. return file.exists();
  28. }
  29. /// Reads from file into String.
  30. @override
  31. Future<String?> readFile(String filename) async {
  32. final file = await _filePath(filename);
  33. if (!await file.exists()) {
  34. return null;
  35. }
  36. return file.readAsString();
  37. }
  38. /// Writes to file.
  39. @override
  40. Future writeFile(String filename, String contents) async {
  41. final file = await _filePath(filename);
  42. await file.writeAsString(contents, flush: true);
  43. }
  44. }