Jake Rener
Jake Rener

Reputation: 1

Getting a list of files in android directory and updating it if a file is added or deleted in flutter

I need to get a list of all the files in a particular directory in /sdcard/ and display them on my app. The list needs to be updated when a new file is added or deleted from the folder. I have tried using the Directory method Directory.list() to get a stream of files and used the stream in a StreamBuilder widget but I only get one file repeatedly in the stream. Here's the code:

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}


class _HomeScreenState extends State<HomeScreen> {
  final booksDir = new Directory('/sdcard/Genesis Reader');
  bool isDirectoryExistent = false;
  //List<String> bookPaths = [];
  Stream fileStream;


  final RegExp re = RegExp(r'(?<=Reader\/)(.*)(?=\.epub)');


  @override
  void initState() {
    super.initState();
    getDirStatus();
  }


  void getDirStatus() async {
    await booksDir.exists().then((isThere) {
      if (isThere) {
        setState(() {
          isDirectoryExistent = true;
        });
        fileStream = booksDir.list();
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    // print(bookPaths);
    return BaseScaffold(
      subHeading: 'Downloaded Books',
      searchWidget: SearchBar(),
      mainWidget: isDirectoryExistent
          ? StreamBuilder(
              stream: fileStream,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  print('from print: ${snapshot.data}');
                  // return Text(snapshot.data.path);
                }
                return CircularProgressIndicator();
              })
          : NoBooks(),
    );
  }
}

I have tried using the watcher package and Directory.watch but it errors with

FileSystemException (FileSystemException: File system watching is not supported on this platform, path = '')

What I need is to be able get a stream of files and then use StreamBuilder to list all the files in that directory.

Upvotes: 0

Views: 2944

Answers (1)

Yadu
Yadu

Reputation: 3305

For Listing

String path = 'path/to/your/directory';
Directory dir = Directory(path);
var listOfAllFolderAndFiles = dir.list(recursive: false).toList();

Here you could use recursive:true to include all the subdirectories and files.

For watching for addition and deletion:

flutter has FileSystemEntity and Directory which could be very useful in this type of scenario where you could watch for all type of file system events (create,delete,modify etc) check FileSystemEvent class.

String path = 'path/to/your/directory';
Directory dir = Directory(path);    
var stream = dir.watch(events: FileSystemEvent.create);
stream.listen((data){
  //data has things you could use
});

You could use

FileSystemEvent.all

Upvotes: 1

Related Questions