Read and Write a Text File or Multiple Files in Flutter

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);
}

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close