Flutter & Dart: Get File Name and Extension from Path/URL

Updated: April 22, 2023 By: Pennywise Post a comment

This article shows you how to retrieve the name and extension of a file from a file path or a web URL in Dart (and Flutter as well).

In order to get the job done, we need the dart:io library and the path package (this one is an official plugin published by the Dart team).

Install the latest version of the path package by executing the following command:

flutter pub add path

Then run:

flutter pub get

No special permission is required.

The path package provides 3 useful functions that can help us get the filename or extension with ease:

  • basename(): Returns the file name with the extension
  • extension(): Returns the file extension
  • basenameWithoutExtension(): Returns the file name without extension
Table Of Contents

Example

The code:

// KindaCode.com
// main.dart
import 'dart:io';
import 'package:path/path.dart';
import 'package:flutter/foundation.dart';

void main() {
  // File Path
  const examplePath = '/my-secret/some-path/abcxyz/my-book.pdf';

  final File file = File(examplePath);
  final filename = basename(file.path);
  final fileExtension = extension(file.path);
  final nameWithoutExtension = basenameWithoutExtension(file.path);
  debugPrint('Filename: $filename');
  debugPrint('Filename without extension: $nameWithoutExtension');
  debugPrint('Extension: $fileExtension');
}

Output:

Filename: my-book.pdf
Filename without extension: my-book
Extension: .pdf

You can get the same result with a file from the internet with its URL instead of a local path:

// KindaCode.com
// main.dart
import 'dart:io';
import 'package:path/path.dart';
import 'package:flutter/foundation.dart';

void main() {
  // File URL from the internet
  const exampleUrl = 'https://www.kindacode.com/some-directory/my-photo.jpg';
  final File file = File(exampleUrl);
  final filename = basename(file.path);
  final nameWithoutExtension = basenameWithoutExtension(file.path);
  final fileExtenion = extension(file.path);
  debugPrint('Filename: $filename');
  debugPrint('Filename without extension: $nameWithoutExtension');
  debugPrint('Extension: $fileExtenion');
}

Output:

Filename: my-photo.jpg
Filename without extension: my-photo
Extension: .jpg

Conclusion

You’ve learned how to retrieve the name and extension of a file from a path or web URL. Continue learning more about Flutter and Dart by taking a look at the following articles:

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles