Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the name of a file in Dart?

Tags:

file

dart

I found I can't get the name of a file in a simple way :(

Dart code:

File file = new File("/dev/dart/work/hello/app.dart");

How to get the file name app.dart?

I don't find an API for this, so what I do is:

var path = file.path;
var filename = path.split("/").last;

Is there any simpler solution?

like image 966
Freewind Avatar asked Jul 09 '13 14:07

Freewind


People also ask

How do I view a dart file?

To read File as a String in Dart, you can use File. readAsString() method or File. readAsStringSync(). File.

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 :

import 'dart:io';
import 'package:path/path.dart';

main() {
  File file = new File("/dev/dart/work/hello/app.dart");
  String filename = basename(file.path);
}
like image 159
Alexandre Ardhuin Avatar answered Oct 24 '22 03:10

Alexandre Ardhuin


If you don't want to use the path pub package, you can use the Uri class from dart:io that returns the filename and its extension:

String fileName = File(localFilePath).uri.pathSegments.last;
like image 34
Vilmir Avatar answered Oct 24 '22 03:10

Vilmir