0

How can I get the file names and directory names in a directory using Dart? This question shows how to get the absolute paths but I only want the actual file/directory names. This code gives absolute paths:

Directory('/').list().map((entry) => entry.path).toList();

Is there a way other than parsing entry.path to just get the last component of the path? I would have thought the FileSystemEntity had a name field but it doesn't. Am I missing something?

Timmmm
  • 88,195
  • 71
  • 364
  • 509

1 Answers1

1

You can map the entry.uri and then get the last segment of it:

  final files = Directory('/')
      .listSync()
      .map((e) => e.uri.pathSegments.last)
      .toList();
  print(files);
Mattia
  • 5,909
  • 3
  • 26
  • 41
  • Hmm interesting idea. I went with `p.basename(e.path)` from the `path` package, which despite being an external package seems to be the official solution. – Timmmm Dec 24 '20 at 15:30