Dart Uri replace()
Syntax & Examples
Uri.replace() method
The `replace` method in Dart returns a new Uri based on the current one but with specified parts replaced.
Syntax of Uri.replace()
The syntax of Uri.replace() method is:
Uri replace({String scheme, String userInfo, String host, int port, String path Iterable<String> pathSegments, String query Map<String, dynamic> queryParameters, String fragment })
This replace() method of Uri returns a new Uri
based on this one, but with some parts replaced.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
scheme | optional | The new scheme for the Uri. |
userInfo | optional | The new user information for the Uri. |
host | optional | The new host for the Uri. |
port | optional | The new port for the Uri. |
path | optional | The new path for the Uri. |
pathSegments | optional | The new path segments for the Uri. |
query | optional | The new query parameters for the Uri. |
fragment | optional | The new fragment for the Uri. |
Return Type
Uri.replace() returns value of type Uri
.
✐ Examples
1 Replacing scheme and path segments
In this example,
- We parse an existing Uri with a scheme, host, path, query, and fragment.
- We use the `replace` method to create a new Uri with a different scheme, host, and path segments.
- We print the new Uri.
Dart Program
void main() {
var uri = Uri.parse('https://example.com/path?query=string#fragment');
var newUri = uri.replace(scheme: 'http', host: 'newhost', pathSegments: ['new', 'path']);
print(newUri);
}
Output
http://newhost/new/path?query=string#fragment
2 Replacing fragment
In this example,
- We parse an existing Uri with a fragment.
- We use the `replace` method to create a new Uri with a different fragment.
- We print the new Uri.
Dart Program
void main() {
var uri = Uri.parse('https://example.com/path?query=string#fragment');
var newUri = uri.replace(fragment: 'newfragment');
print(newUri);
}
Output
https://example.com/path?query=string#newfragment
Summary
In this Dart tutorial, we learned about replace() method of Uri: the syntax and few working examples with output and detailed explanation for each example.