> findFiles(" /> > findFiles(" /> > findFiles("/>

How to build a "Recent files" list?

211 views Asked by At

I'm struggling to find a solution to build a widget that displays "Recent Files".

To find the files I have the following

Future<List<File>> findFiles(String prefix) async {
    List<File> files = [];
    await for (var entity
        in directory.list(recursive: true, followLinks: false)) {
      File file = File(entity.path);
      if (p.extension(file.path) == ".json") {
        print("Found in:" + entity.path);
        if (p.basename(file.path).startsWith(prefix)) files.add(file);
      }
    }

    return files;
  }

Then I call it using var files = await FileManager().findFiles("test");

But I am not sure how to build a list view to display the name of each file as it is a Future and needs awaiting.

Any suggestions?

1

There are 1 answers

0
MendelG On BEST ANSWER

To display the result of your function in a ListView, since your function returns a Future, you should use a FutureBuilder:

FutureBuilder(
      future: findFiles("bla"),
      builder: (BuildContext context, AsyncSnapshot<List<File>> snapshot) {
        if (snapshot.hasData) {
          return ListView.builder(
            itemCount: snapshot.data?.length,
            itemBuilder: (BuildContext context, int index) {
              return Text(snapshot.data?[index].path);
            },
          );
        } else if (snapshot.hasError) {
          return Text("Error: ${snapshot.error}");
        }
        return CircularProgressIndicator();
      },
    )

Here is a YouTube video by the Flutter team explaining FutureBuilder