{

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


get File name and extension dart or flutter

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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart Example - Program to check Leap year or not