6 C
New York
Monday, December 11, 2023

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

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 published by the Dart team).Advertisements

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.

Advertisements

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

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

Example

The code:

// main.dart
import 'dart:io';
import 'package:path/path.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 _extension = extension(_file.path);
  final _nameWithoutExtension = basenameWithoutExtension(_file.path);
  print('Filename: $_filename');
  print('Filename without extension: $_nameWithoutExtension');
  print('Extension: $_extension');
}

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:

import 'dart:io';
import 'package:path/path.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 _extenion = extension(_file.path);
  print('Filename: $_filename');
  print('Filename without extension: $_nameWithoutExtension');
  print('Extension: $_extenion');
}
Advertisements

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.

Related Articles

Latest Articles