First of all, I am new to programming and am trying to learn/motivate myself by approaching programming through projects i.e., I am not learning bottom up and am lacking a lot of skills many of you have…
To the problem: I am trying to get a list of all folders in a folder in my assets directory.
I have tried an answer from How do I list the contents of a directory with Dart?, but have failed to succeed:
import 'dart:io';
void main() async {
final dir = Directory('assets/images/');
final List<FileSystemEntity> entities = await dir.list().toList();
final Iterable<File> files = entities.whereType<File>();
for (var file in files) {
print('File found: ${file.uri.pathSegments.last}');
}
}
I have added the following in the yaml file:
flutter:
assets:
- assets/images/
I get E/flutter (14446): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PathNotFoundException: Directory listing failed, path = 'assets/images/' (OS Error: No such file or directory, errno = 2)
Thank you in advance!
All the best
2
Answers
In Flutter, assets are bundled with the application when compiled. So you can use the rootBundle access files in your assets folder.
Make sure to call
WidgetsFlutterBinding.ensureInitialized();
first line in main.This approach would work while using just dart but not in a flutter app.
For listing all the paths in asset/images you need to show all the paths using
rootBundle
.EXAMPLE: