Line data Source code
1 : import 'dart:io'; 2 : 3 : import 'package:path_provider/path_provider.dart'; 4 : 5 : abstract class StorageManager { 6 : Future store(String value); 7 : 8 : Future<String> read(); 9 : 10 : Future deleteFile(); 11 : } 12 : 13 : /// use this implementation for a mock test 14 : class MockStorageManager implements StorageManager { 15 : String _value = ''; 16 : 17 0 : @override 18 0 : Future<String> read() => Future.value(this._value); 19 : 20 0 : @override 21 : Future store(String value) { 22 0 : return Future(() { 23 0 : this._value = value; 24 : }); 25 : } 26 : 27 0 : @override 28 : Future deleteFile() { 29 0 : throw Future.value(); 30 : } 31 : } 32 : 33 : /// store a file on local app storage folder 34 : class LocalStorageManager implements StorageManager { 35 : final String _filename; 36 : 37 2 : LocalStorageManager(this._filename); 38 : 39 : @override 40 0 : Future store(String value) async { 41 0 : await deleteFile() 42 0 : .then((res) => getLocalFile()) 43 0 : .then((file) => file.writeAsString(value, flush: true)); 44 : } 45 : 46 1 : @override 47 : Future<String> read() { 48 2 : return getLocalFile().then((file) => file.readAsStringSync()); 49 : } 50 : 51 1 : Future<File> getLocalFile() async { 52 2 : return getApplicationDocumentsDirectory().then((path) { 53 0 : String finalPath = path.path + '/' + this._filename; 54 0 : return File(finalPath).exists().then((bool) { 55 : if (bool) { 56 0 : return File(finalPath); 57 : } else { 58 0 : return File(finalPath).create().then((file) { 59 : return file; 60 : }); 61 : } 62 : }); 63 : }); 64 : } 65 : 66 0 : Future deleteFile() async { 67 : try { 68 0 : File file = await getLocalFile(); 69 0 : var exists = await file.exists(); 70 : if (exists) { 71 0 : await file.delete(); 72 : } 73 : } catch (e) { 74 0 : print("error while delete file : $e "); 75 : } 76 : } 77 : }