Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to get a list of names of all images in 'assets' directory?

Tags:

flutter

dart

I have 100 images that I need to display in a list. I don't want to hard code all names.

How can I get the names of the images?

I want to have code like this:

final List<String> imageNames = await WhatEver.getNamesOfImagesInAssetsDirectory();
final widgets = imageNames.map((fileName) => Image.asset('images/${fileName}.png')).toList()
like image 486
Kostya Vyrodov Avatar asked Jun 11 '19 12:06

Kostya Vyrodov


People also ask

How do you get the image path in Flutter?

In Flutter, displaying an image can be done by using Image widget. Flutter provides a named constructor File. Image which can be used if the image source is from a file. Alternatively, you can also use FileImage .


1 Answers

I've implemented the function below inside of a StatefulWidget

    Future _initImages() async {
      // >> To get paths you need these 2 lines
      final manifestContent = await rootBundle.loadString('AssetManifest.json');
    
      final Map<String, dynamic> manifestMap = json.decode(manifestContent);
      // >> To get paths you need these 2 lines

      final imagePaths = manifestMap.keys
          .where((String key) => key.contains('images/'))
          .where((String key) => key.contains('.svg'))
          .toList();
    
      setState(() {
        someImages = imagePaths;
      });
    }

AssetManifest.json contains all data about all assets that you add in pubspec.yaml

like image 142
Kostya Vyrodov Avatar answered Oct 19 '22 12:10

Kostya Vyrodov