How to encode and decode a URI in dart

The URI Uniform Resource Identifier can only be sent over the internet using the ASCII character set, but the URI often contains characters outside the ASCII character set. We need to encode the URI characters so that they can be transmitted over the internet. In this Answer, we'll learn to encode and decode a URI in Dart language.

We'll use the method encodeComponent to encode the URI and decodeComponent to decode the URI provided by the class Uri.

Syntax

// syntax to encode uri
Uri.encodeComponent(provide your uri here)
//syntax to decode uri
Uri.decodeComponent(provide your encoded uri here to decode)

Code example

Let's go through an example below:

void main(){
//given uri
var uri = 'https://testurl.com/api?message=Hello World !!!';
//encode uri
var encodedUri = Uri.encodeComponent(uri);
print(" ----- URI after Encoding ----- ");
print(encodedUri);
//decode uri
var decodedUri = Uri.decodeComponent(encodedUri);
print(" ----- URI after Decoding ----- ");
print(decodedUri);
}

Code explanation

In the code snippet above:

  • Line 4: We declare and assign a variable uri with a test URI as a value.

  • Line 7: We encode the URI using the encodeComponent() method and assign it to variable encodedUri.

  • Line 10: We display the encoded URI.

  • Line 13: We decode the encoded URI in line 7 using the decodeComponent() method and assign it to the variable decodedUri.

  • Line 16: We display the decode URI.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved