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

Last updated on April 2, 2021 Pennywise Loading... 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 published by the Dart team).

Install the path package by adding it to the dependencies section in the pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  path: ^1.8.0

Then run:

flutter pub get

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

  • 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 EXAMPLE_PATH = '/my-secret/some-path/abcxyz/my-book.pdf';

  final File _file = new File(EXAMPLE_PATH);
  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 EXAMPLE_URL = 'https://www.kindacode.com/some-directory/my-photo.jpg';
  final File _file = new File(EXAMPLE_URL);
  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');
}

Output:

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

Conclusion

You’ve learned 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: Flutter StreamBuilder examples, Working with Cupertino Date Picker in Flutter, Flutter and Firestore Database: CRUD example, Remove duplicate items from a list in Dart, Working with dynamic Checkboxes in Flutter.

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