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

ParameterOptional/RequiredDescription
schemeoptionalThe new scheme for the Uri.
userInfooptionalThe new user information for the Uri.
hostoptionalThe new host for the Uri.
portoptionalThe new port for the Uri.
pathoptionalThe new path for the Uri.
pathSegmentsoptionalThe new path segments for the Uri.
queryoptionalThe new query parameters for the Uri.
fragmentoptionalThe new fragment for the Uri.

Return Type

Uri.replace() returns value of type Uri.



✐ Examples

1 Replacing scheme and path segments

In this example,

  1. We parse an existing Uri with a scheme, host, path, query, and fragment.
  2. We use the `replace` method to create a new Uri with a different scheme, host, and path segments.
  3. 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,

  1. We parse an existing Uri with a fragment.
  2. We use the `replace` method to create a new Uri with a different fragment.
  3. 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.