Reputation: 491
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
Reputation: 8383
Here is a simple way to do that:
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