ThitSarNL
ThitSarNL

Reputation: 720

Flutter, How to get all the image file name from images folder?

I want to load all the image file names in images/pets/ to List<String> animals. How can I do that?

Upvotes: 5

Views: 9675

Answers (3)

StarBattle08
StarBattle08

Reputation: 55

Continuing from AdsHan's Answer

final dir = await getApplicationDocumentsDirectory();
final imagesDirectory = Directory(dir.path + "/images/pets/");

List<String> images = [];
final _imagesFile = imagesDirectory.listSync(followLinks: false, recursive: true);
_imagesFile.forEach((img) {
       String imgString = img.toString().substring(
       img.toString().lastIndexOf('/') + 1,
       img.toString().length);
       images.add(imgString); 
});

Upvotes: 0

Filled Stacks
Filled Stacks

Reputation: 4346

Flutter generates a file called AssetManifest.json which you can read up through the default bundle the same way you would read a normal text file from the assets.

var manifestContent = DefaultAssetBundle.of(context).loadString('AssetManifest.json');

Read and parse this file and then create a list from all the properties you need with their paths. Just double check to make sure you have the correct path, this can change in the future. It seems to me like a placeholder.

Pseudo-code for reading AssetManifest.json

var manifestContent = DefaultAssetBundle.of(context).loadString('AssetManifest.json');
var manifestMap = json.decode(manifestContent);

var imagePetPaths = manifestMap.keys.where((key) => key.contains('images/pets/'));

// You can either use the keys and fetch the value from the map, 
or just use the key value since it's the same as the one in the pubspec.yaml

Upvotes: 5

AdsHan
AdsHan

Reputation: 465

path_provider you can get the directory the temp and appDir directory

    final directory = await getApplicationDocumentsDirectory();
    String imagesDirectory = directory + "/images/pets/";

After you can use the listSync method to find files of this Directory

final myDir = new Directory(imagesDirectory);
List<FileSystemEntity> _images;
_images = myDir.listSync(recursive: true, followLinks: false);

I hope that I have helped in some way

Upvotes: 7

Related Questions