Home > Software engineering >  Flutter how to get multiple files from path
Flutter how to get multiple files from path

Time:10-06

I am using this code to get one image from path. But I want to get all images and save them to a list instead. The images are named 'media1' 'media2'. But sometimes it can be more images like 'media3'.

File loadedImage;
List<File> _imageFileList;

Future<File> loadFiles() async {
    try {
      final Directory directory = await getApplicationDocumentsDirectory();

      final File file = File('${directory.path}/media1.jpg');
      loadedImage = file;
    } catch (e) {
      print("Couldn't read file");
    }
    return loadedImage;
  }

This function only loads one image. I need to edit it to get all images. Does anyone know how to get all images with a name starting with 'media' and save them to _imageFileList instead?

CodePudding user response:

// add dependancy in pubspec.yaml path_provider:

import 'dart:io' as io; import 'package:path_provider/path_provider.dart';

//Declare Globaly
  String directory;
  List file = new List();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _listofFiles();
  }

// Make New Function
void _listofFiles() async {
    directory = (await getApplicationDocumentsDirectory()).path;
    setState(() {
      file = io.Directory("$directory/resume/").listSync();  //use your folder name insted of resume.
    });
  }

// Build Part
@override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey,
      title: 'List of Files',
      home: Scaffold(
        appBar: AppBar(
          title: Text("Get List of Files with whole Path"),
        ),
        body: Container(
          child: Column(
            children: <Widget>[
              // your Content if there
              Expanded(
                child: ListView.builder(
                    itemCount: file.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Text(file[index].toString());
                    }),
              )
            ],
          ),
        ),
      ),
    );
  }

CodePudding user response:

List content of a directory, filter out directories and finally filter according to a name. Something like this.

final mediaFiles = directory.listSync()
  .where((e) => e is File)
  .where((file) => file.path.split('/').last.startsWith('media'));
  • Related