0

In my project, I want to get the number of files in a directory when a button is pressed or tapped. This functionality seems to work in Dart standalone code, but when called in the onTap function it then throws an error indicating that the path does not exist or is empty. However, the path exists and is not empty and it is listed in the pubspec.yaml file.

This list the number of files available

void main(){
  getNumberOfFiles();
}

Future<int> getNumberOfFiles() async {
  String bookPath = 'assets/books/jude/';

  final dir = Directory(bookPath);
  if (!await dir.exists()) {
    print('Directory does not exist: $bookPath');
    return 0;
  }

  final fileList = await dir.list().toList();
  final fileCount = fileList.whereType<File>().length;

  print('Number of files: $fileCount');
  return fileCount;
}

This one down here throws error

onTap: () async {context.read<BibleTextManager>().getNumberOfFiles();},

I am using the provider because the function was and still in a provider class but I just took the method out to another file to test with the main function.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    `assets` folder is a virtual folder - it does not exist on the physical file system – pskink May 30 '23 at 10:35
  • thanks but I have gotten a solution for that. A method that was not working of which I don't know just worked. And also when you build the app the assets folders or files works in the app making it existing. But my knowledge on that is not deep I would like you to throw more light on it for me. Thanks again! – Stephen Essoun May 30 '23 at 11:10

1 Answers1

0

This problem has not taken me less than a week, but I hesitated to post a question on that and just today that I did post the question a method that was not working just worked now. I am really happy so I decided to share the solution that worked for me to you all maybe some one will find it helpful.

getChapterIndices() async {
  String bookPath = 'assets/books/$book/';
  log(bookPath);
  try {
    final fileCount = json
        .decode(await rootBundle.loadString('AssetManifest.json'))
        .keys
        .where((String key) => key.contains(bookPath))
        .toList();
    _numberOfChapters = fileCount.length;
    log('i am opening $_numberOfChapters');
  } on Exception catch (e) {
    print(e);
  }
  notifyListeners();
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197