Dart| Flutter How to get File name and extension with example

The post is about how to get the name of the file in dart programming.

Dart gets filename and extension

There are multiple ways to get the name of the file

  • using path package basename Import path/path.dart package into your code.

Path package provides basename and basenameWithoutExtension properties to get name and extension.

First, Create a file object. Pass file.path to those methods. Here is an example

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

void main() {
  File file = new File("/abc.txt");
  String name = basename(file.path);
  print(name);
  String namewithoutExtension = basenameWithoutExtension(file.path);
  print(namewithoutExtension);
}

Output:

abc.txt
abc

The second way, using File.uri.pathSegments.last

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

void main() {
  File file = new File("/abc.txt");
  String name = file.uri.pathSegments.last;
  print(name);//abc.txt
}

Third-way using Path class from dart:io package Create File object, pass file.path that gets the path of the file to Path class.

Here is an example

import 'dart:io';

void main() {
  File file = new File("/abc.txt");
  Path path = new Path(file.path);
  print(path.filename); // abc.txt
  print(path.directoryPath); // /
}

Conclusion

You can get multiple ways to get filename, extension and directory path in dart and flutter