How can we get permission to access storage/emulated/0/Android/data folder for a flutter application?

Viewed 1937

I'm coding a video player application using flutter. I'm recursively trying to go through every folder to fetch all the files-> then create an exclusive list of video files -> then build a listView of all video files.

But the compiler is not able to iterate and go inside the 'storage/emulated/0/Android/data' folder and therefore it is throwing a 'Permission denied' error.

How can I, either, skip such unaccessible folders/files and continue the iteration, or How to get permission to access such folders(storage/emulated/0/Android/data)?

I was expecting to get the list of all the files on my phone.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:mark_player/custom%20widgets/app_bar.dart';


class newHomeScreen extends StatefulWidget {
  const newHomeScreen({ Key? key }) : super(key: key);

  @override
  State<newHomeScreen> createState() => _newHomeScreenState();
}

class _newHomeScreenState extends State<newHomeScreen> {

  Directory dir = Directory('/storage/emulated/0');

@override
  void initState() {

   List <FileSystemEntity> filesBaby = dir.listSync(recursive: true);
   filesKittan(filesBaby);
    super.initState();
  }

  filesKittan(List <FileSystemEntity> files){
    for (var i = 0; i < files.length; i++) {
      if (files[i].absolute.toString()=='/storage/emulated/0/Android/data') {
        continue;
    }print(files[i].absolute);
  }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}
1 Answers

You can use the permission_handler plugin to request storage permissions.

// Request storage permission and check if granted
if (await Permission.storage.request().isGranted) {
  // Either the permission was already granted before or the user just granted it.
  // Access path
} 
Related