Display all images in a directory to a list in Flutter

Issue

I was wondering if there is a way i can display all images or files in a particular directory located in user’s mobile device to a list/array in flutter so i can use in a ListView.

Thanks any help is welcomed.

PS: i wanted to try with path_provider but didn’t know how to.

Solution

I was able to find a solution.

I had to work with MethodChannels in other to achieve this.

After writing the java code for getting the file list, i passed in into flutter through a channel

Java Method for getting files

private List<String> getImages(){
        String path = Environment.getExternalStorageDirectory().toString();

        List<String> imgs = new ArrayList<String>();
        File directory = new File(path);
        List<String> files = Arrays.asList(directory.list());

        imgs = files;

        return imgs;
    }

Java MethodChannel

new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
              (call, result) -> {
                  if (call.method.equals("getImages")) {
                      List<String> imgs = getImages();
                      if (imgs.size() <= 0) {
                          result.error("Empty", "No Images.", null);
                      } else {
                          result.success(imgs);                      }
                  } else {
                      result.notImplemented();
                  }

              });

Dart Code

 Future<void> _getImages() async {
    List images;
    try {
      final List result = await platform.invokeMethod('getImages');
      images = result;
    } on PlatformException catch (e) {
      print("Error");
    }

    setState(() {
      imgs = images;
    });
  }

Full Source Code available on Github

Answered By – JideGuru

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.