Dart Uri.file()
Syntax & Examples


Uri.file constructor

The `Uri.file` constructor in Dart is used to create a new file URI from an absolute or relative file path. This constructor provides an option to specify whether the file path is for a Windows environment.


Syntax of Uri.file

The syntax of Uri.Uri.file constructor is:

Uri.file(String path, { bool windows })

This Uri.file constructor of Uri creates a new file URI from an absolute or relative file path.

Parameters

ParameterOptional/RequiredDescription
pathrequiredThe file path, which can be absolute or relative.
windowsoptionalA boolean flag indicating whether the path should be treated as a Windows path. Defaults to false.


✐ Examples

1 Creating a file URI for a Unix-like file path

In this example,

  1. We create a `String` variable `filePath` containing the Unix-like file path '/path/to/file.txt'.
  2. We use the `Uri.file` constructor to create a file URI from the file path.
  3. We print the file URI to standard output.

Dart Program

void main() {
  String filePath = '/path/to/file.txt';
  Uri fileUri = Uri.file(filePath);
  print(fileUri);
}

Output

file:///path/to/file.txt

2 Creating a file URI for a Windows file path

In this example,

  1. We create a `String` variable `windowsFilePath` containing the Windows file path 'C:\Users\User\Documents\file.txt'.
  2. We use the `Uri.file` constructor with the `windows` flag set to true to create a file URI from the Windows file path.
  3. We print the file URI to standard output.

Dart Program

void main() {
  String windowsFilePath = 'C:\\Users\\User\\Documents\\file.txt';
  Uri windowsFileUri = Uri.file(windowsFilePath, windows: true);
  print(windowsFileUri);
}

Output

file:///C:/Users/User/Documents/file.txt

Summary

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