How to encode and decode a URI in dart
The
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 uriUri.encodeComponent(provide your uri here)//syntax to decode uriUri.decodeComponent(provide your encoded uri here to decode)
Code example
Let's go through an example below:
void main(){//given urivar uri = 'https://testurl.com/api?message=Hello World !!!';//encode urivar encodedUri = Uri.encodeComponent(uri);print(" ----- URI after Encoding ----- ");print(encodedUri);//decode urivar 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
uriwith a test URI as a value.Line 7: We encode the URI using the
encodeComponent()method and assign it to variableencodedUri.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 variabledecodedUri.Line 16: We display the decode URI.
Free Resources