-1

I'm trying to write some string in a basic txt file and read with a button press. I tried to do it like

Future<String> _getStudents() async {
  String txt;
  try {
    final Directory directory = await getApplicationDocumentsDirectory();
    final File file = File('${directory.path}/students.txt');
    txt = file.readAsStringSync();
  } catch (e) {
    print("Couldn't read file");
  }
  print(txt);
  return txt;
}

_write(String text) async {
  final Directory directory = await getApplicationDocumentsDirectory();
  final File file = File('${directory.path}/my_file.txt');
  print('${directory.path}');
  await file.writeAsString(text);
}

As I researched I couldn't write/read a file from desired directory in project's folder. The example only contains 'directory.path' and I couldn't understand it. Thanks for your help!

Taha Ateş
  • 111
  • 1
  • 3
  • 13

1 Answers1

2

Project level files must be imported and accessed as assets. Keep in mind that an end-user will be accessing files in their directories. You wouldn't want them to have access to your app directories and files, therefore the two are treated differently. This link should help you access the file as an asset: Flutter - Read text file from assets

Lee3
  • 2,882
  • 1
  • 11
  • 19