skip to Main Content

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


  1. In Flutter, assets are bundled with the application when compiled. So you can use the rootBundle access files in your assets folder.

    void main() {
      WidgetsFlutterBinding.ensureInitialized();
      getImagePaths();
    }
    
    void getImagePaths() async {
      final manifestContent = await rootBundle.loadString('AssetManifest.json');
      final Map<String, dynamic> manifest = json.decode(manifestContent);
      final imagePaths = manifest.keys
          .where((String key) => key.startsWith('assets/images/'))
          .toList();
    
      for (var path in imagePaths) {
        print('File found: $path');
      }
    }
    

    Make sure to call WidgetsFlutterBinding.ensureInitialized(); first line in main.

    Login or Signup to reply.
  2. 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:

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main(){
      WidgetsFlutterBinding.ensureInitialized();
      printAssets();
    }
    
    void printAssets() async{
      final manifestContent = await rootBundle.loadString('AssetManifest.json');
    
      final Map<String, dynamic> manifestMap = json.decode(manifestContent);
    
      final imagePaths = manifestMap.keys
          .where((String key) => key.contains('images/'))
          .toList();
    
      for(var path in imagePaths){
        print('File found: $path');
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search