With certain types of data, a text file can be preferred to other solution such as Shared Preferences, SQLite.
The file we are going to read and write needs to be in a sub-folder of assets folder and defined in pubspec.
Read data from a text file
Future<String> loadEmojiString(String fileName) async {
return await rootBundle.loadString('assets/$fileName.txt');
}
Read multiple files
Future<Map<String, String>> loadAllFiles(List<Category> categories) async {
final Map<String, String> map = Map<String, String>();
for (var category in categories){
String str = await rootBundle.loadString('assets/${category.id}.txt');
map[category.id] = str;
}
return map;
}
Write data to a text file
To write data to a file, we need the help of path_provider package. Install the library and import it with:
import 'package:path_provider/path_provider.dart';
write(String text) async {
final directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/file.txt');
await file.writeAsString(text);
}