Last active
November 13, 2018 15:05
-
-
Save rjlutz/bc4a57e305785a50ca50adc79adc9ab0 to your computer and use it in GitHub Desktop.
helpful artifacts for the flutter student picker app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// thanks - https://flutter.io/docs/cookbook/persistence/reading-writing-files | |
import 'dart:async'; | |
import 'dart:io'; | |
import 'package:path_provider/path_provider.dart'; | |
import 'student.dart'; | |
class Storage { | |
Future<String> get _localPath async { | |
final directory = await getApplicationDocumentsDirectory(); | |
return directory.path; | |
} | |
Future<File> get _localFile async { | |
final path = await _localPath; | |
return File('$path/names.txt'); | |
} | |
Future<List<Student>> readStudents() async { | |
List<Student> names; | |
try { | |
final file = await _localFile; | |
names = List<Student>(); | |
await file.readAsLines().then((List<String> lines) { | |
for (int i = 0; i < lines.length; i++) { | |
List<String> tokens = lines[i].split(','); | |
bool vis = tokens[1] == 'true' ? true : false; | |
names.add(new Student(tokens[0], vis)); | |
} | |
}); | |
// Read the file | |
} catch (e) { | |
print('Whoa Nellie: ' + e.toString()); | |
return null; | |
} | |
return names; | |
} | |
Future<File> writeStudents(List<Student> names) async { | |
final file = await _localFile; // Write the file | |
var sink = file.openWrite(mode: FileMode.write); | |
for (int i = 0; i < names.length; i++) { | |
var line = names[i].name + ',' + (names[i].hidden ? 'true' : 'false') + | |
'\n'; | |
sink.write(line); | |
} | |
await sink.flush(); | |
await sink.close(); | |
return file; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Student { | |
final String name; | |
bool hidden; | |
Student(this.name, this.hidden); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment