skip to Main Content

I do not know how many images I will have, whether there are any methods such as "assets.length" or other ways

ListView.builder(
                      itemCount: // here I have to specify how many images I have in my resource file
                      scrollDirection: Axis.horizontal,
                      shrinkWrap: true,
                      itemBuilder: (BuildContext context, int index) {
                        return Container(
                          width: 100,
                          margin: EdgeInsets.only(right: 25),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            image: DecorationImage(
                              fit: BoxFit.cover,
                              image: AssetImage(
                                'assets/four_season/hotel${index}.jpg',
                              ),
                            ),
                          ),
                        );
                      },
                    ),

enter image description here

I will create many hotels, and it is unknown how many images there will be

3

Answers


  1. You can try this code block to work with,

      Future<int> countFiles([
        String path = 'assets/images/',
      ]) async {
        final manifestContent = await rootBundle.loadString('AssetManifest.json');
        final Map<String, dynamic> manifestMap = json.decode(manifestContent);
    
        final assetPaths =
            manifestMap.keys.where((String key) => key.startsWith(path)).toList();
    
        ColoredLogger.Red.log(
            'Number of files in the assets folder: ${assetPaths.length}');
        return assetPaths.length;
      }
    

    Just call the function with proper path, if you select path for your case,
    assets then the file count will be 10 (four_season’s 4 & marriot_hotel’s 6 files).

    or if you select path assets/four_season then the count will be 4.

    Login or Signup to reply.
  2. create a Class for assets:

    class Assets {
      static const hotelList = [0, 1, 2, 3, 4, 5, 6, 7];
    
      static getHotelImagePath(int num) => 'assets/four_season/hotel$num.jpg';
    }
    

    and use as following:

    ListView.builder(
        itemCount: Assets.hotelList.length,
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            width: 100,
            margin: EdgeInsets.only(right: 25),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              image: DecorationImage(
                fit: BoxFit.cover,
                image: AssetImage(
                  Assets.getHotelImagePath(index),
                ),
              ),
            ),
          );
        },
      )
    

    make sure to update the assets list when you add new images.

    Login or Signup to reply.
  3. If you need to inspect what assets are available to your app at run time, the listAssets API is probably what you’re looking for.

    You can call this API, filter the resulting list however you please, and then inspect the length on the list.

    Full sample application that lists all available assets:

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() {
      runApp(const MainApp());
    }
    
    class MainApp extends StatelessWidget {
      const MainApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: FutureBuilder(
                future: AssetManifest.loadFromAssetBundle(rootBundle),
                builder: (context, snapshot) => snapshot.hasData
                    ? Column(
                        children: snapshot.data!
                            .listAssets()
                            .map((e) => Text(e))
                            .toList(),
                      )
                    : const Text('Loading assets list...'),
              ),
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search