Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart accessing the name of a File or Directory

Tags:

dart

How do I read the name of a File or a Directory?

There is a property 'path' but that returns the entire file path.

Would be nice to have a property like 'name' that just returns the last part of the path.

In Java there is a method called File.name();

like image 922
richard Avatar asked Nov 19 '13 08:11

richard


People also ask

How do I find a file path by name?

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).

How do I get all the files in a directory dart?

How to list the contents of a directory in Dart. final dir = Directory('path/to/directory'); final List<FileSystemEntity> entities = await dir. list(). toList();


2 Answers

You can use the path package to do that :

import 'package:path/path.dart' as path;
main() {
  path.basename('path/to/foo.dart'); // -> 'foo.dart'
  path.basename('path/to');          // -> 'to'
}

See the path package documentation for more explanations.

like image 184
Alexandre Ardhuin Avatar answered Sep 28 '22 08:09

Alexandre Ardhuin


Since Dart Version 2.6 has been announced and it's available for flutter version 1.12 and higher, You can use extension methods. It will provide a more readable and global solution to this problem.

file_extensions.dart :

import 'dart:io';

extension FileExtention on FileSystemEntity{
  String get name {
    return this?.path?.split("/")?.last;
  }
}

and name getter is added to all the file objects. You can simply just call name on any file.

main() {
  File file = new File("/dev/dart/work/hello/app.dart");
  print(file.name);
}

Read the document for more information.

Note: Since extension is a new feature, it's not fully integrated into IDEs yet and it may not be recognized automatically. You have to import your extension manually wherever you need that. Just make sure the extension file is imported:

import 'package:<your_extention_path>/file_extentions.dart';
like image 32
Saman Salehi Avatar answered Sep 28 '22 07:09

Saman Salehi