Dart Uri toFilePath()
Syntax & Examples


Uri.toFilePath() method

The `toFilePath` method in Dart returns the file path from a file URI.


Syntax of Uri.toFilePath()

The syntax of Uri.toFilePath() method is:

 String toFilePath({bool windows }) 

This toFilePath() method of Uri returns the file path from a file URI.

Parameters

ParameterOptional/RequiredDescription
windowsoptionalIf true, the path separator used will be that used by Windows. If false, the path separator used will be that used by the operating system of the platform on which the application is running.

Return Type

Uri.toFilePath() returns value of type String.



✐ Examples

1 Getting file path from a file URI

In this example,

  1. We create a file URI using `Uri.parse()`.
  2. We use the `toFilePath()` method to get the file path.
  3. We then print the file path.

Dart Program

void main() {
  Uri fileUri = Uri.parse('file:///path/to/file.txt');
  String filePath = fileUri.toFilePath();
  print('File Path: $filePath');
}

Output

File Path: /path/to/file.txt

2 Getting Windows file path

In this example,

  1. We create a file URI using `Uri.parse()` with a Windows-style path.
  2. We use the `toFilePath(windows: true)` method to get the Windows file path.
  3. We then print the Windows file path.

Dart Program

void main() {
  Uri fileUri = Uri.parse('file:///C:/Users/User/Documents/file.txt');
  String windowsPath = fileUri.toFilePath(windows: true);
  print('Windows Path: $windowsPath');
}

Output

Windows Path: C:\Users\User\Documents\file.txt

3 Getting Posix file path

In this example,

  1. We create a file URI using `Uri.parse()` with a Posix-style path.
  2. We use the `toFilePath(windows: false)` method to get the Posix file path.
  3. We then print the Posix file path.

Dart Program

void main() {
  Uri fileUri = Uri.parse('file:///home/user/Documents/file.txt');
  String posixPath = fileUri.toFilePath(windows: false);
  print('Posix Path: $posixPath');
}

Output

Posix Path: /home/user/Documents/file.txt

Summary

In this Dart tutorial, we learned about toFilePath() method of Uri: the syntax and few working examples with output and detailed explanation for each example.