TJMitch95
TJMitch95

Reputation: 491

Flutter - Way to load all asset images at once?

I've been trying to find a solution to this but doesn't seem to be much out there.

I have a subdirectory in my assets folder which contains 3 images. I've updated my pubspec.yaml file to include "-assets/" and my sub folder:

  assets:
    - assets/
    - assets/headline_products

I want to build a list view which contains all 3 images in the sub directory without having to manually list all 3. Is this possible? Thanks

Upvotes: 0

Views: 1974

Answers (1)

Thierry
Thierry

Reputation: 8383

Here is a simple way to do that:

enter image description here

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Assets Loading',
      home: Scaffold(
        appBar: AppBar(title: Text('Assets Loading')),
        body: MyWidget(),
      ),
    ),
  );
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  List<String> imagePaths = [];

  @override
  void initState() {
    _initImages();
    super.initState();
  }

  Future _initImages() async {
    final Map<String, dynamic> assets =
        jsonDecode(await rootBundle.loadString('AssetManifest.json'));

    setState(() {
      imagePaths = assets.keys
          .where((String key) => key.contains('spiders/'))
          .where((String key) => key.contains('.jpg'))
          .toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: imagePaths
            .map(
              (path) => Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16.0,
                  vertical: 8.0,
                ),
                child: Image.asset(path),
              ),
            )
            .toList(),
      ),
    );
  }
}

!!! Make sure that your AssetManifest.json is properly generated by running flutter build.

Upvotes: 1

Related Questions