Dart Uri pathSegments
Syntax & Examples
Uri.pathSegments property
The `pathSegments` property in Dart's Uri class returns the URI path split into its segments.
Syntax of Uri.pathSegments
The syntax of Uri.pathSegments property is:
List<String> pathSegments
This pathSegments property of Uri returns the URI path split into its segments. Each of the segments in the returned list have been decoded. If the path is empty the empty list will be returned. A leading slash /
does not affect the segments returned.
Return Type
Uri.pathSegments returns value of type List<String>
.
✐ Examples
1 HTTP URI with multiple segments
In this example,
- We create a Uri object
uri1
by parsing the string 'http://example.com/path/to/resource'. - We use the
pathSegments
property to get the segments of the URI path. - We then print the result to standard output.
Dart Program
void main() {
Uri uri1 = Uri.parse('http://example.com/path/to/resource');
List<String> segments1 = uri1.pathSegments;
print('Path segments of URI 1: $segments1');
}
Output
Path segments of URI 1: [path, to, resource]
2 File URI with single segment
In this example,
- We create a Uri object
uri2
by parsing the string 'file:///home/user/documents/report.txt'. - We use the
pathSegments
property to get the segments of the URI path. - We then print the result to standard output.
Dart Program
void main() {
Uri uri2 = Uri.parse('file:///home/user/documents/report.txt');
List<String> segments2 = uri2.pathSegments;
print('Path segments of URI 2: $segments2');
}
Output
Path segments of URI 2: [home, user, documents, report.txt]
3 HTTPS URI with root path
In this example,
- We create a Uri object
uri3
by parsing the string 'https://example.com/'. - We use the
pathSegments
property to get the segments of the URI path, which is an empty list as the path is empty. - We then print the result to standard output.
Dart Program
void main() {
Uri uri3 = Uri.parse('https://example.com/');
List<String> segments3 = uri3.pathSegments;
print('Path segments of URI 3: $segments3');
}
Output
Path segments of URI 3: []
Summary
In this Dart tutorial, we learned about pathSegments property of Uri: the syntax and few working examples with output and detailed explanation for each example.