Dart Uri.dataFromString()
Syntax & Examples


Uri.dataFromString constructor

The `Uri.dataFromString` constructor in Dart is used to create a `data:` URI containing the specified content string. This constructor allows specifying additional parameters such as MIME type, encoding, parameters, and whether the content should be base64 encoded.


Syntax of Uri.dataFromString

The syntax of Uri.Uri.dataFromString constructor is:

Uri.dataFromString(String content, { String mimeType, Encoding encoding, Map<String, String> parameters, bool base64: false })

This Uri.dataFromString constructor of Uri creates a data: URI containing the content string.

Parameters

ParameterOptional/RequiredDescription
contentrequiredThe content string to include in the data URI.
mimeTypeoptionalThe MIME type of the content. Defaults to 'text/plain'.
encodingoptionalThe encoding used for the content. Defaults to UTF-8.
parametersoptionalAdditional parameters for the data URI as key-value pairs.
base64optionalA boolean flag indicating whether the content should be base64-encoded. Defaults to false.


✐ Examples

1 Creating a data URI with plain text content

In this example,

  1. We create a `String` variable `content` containing the text 'Hello, world!'.
  2. We use the `Uri.dataFromString` constructor to create a data URI with the specified content, MIME type 'text/plain', encoding UTF-8, and additional parameter 'charset=utf-8'.
  3. We print the data URI to standard output.

Dart Program

void main() {
  String content = 'Hello, world!';
  Uri dataUri = Uri.dataFromString(content, mimeType: 'text/plain', encoding: utf8, parameters: {'charset': 'utf-8'});
  print(dataUri);
}

Output

data:text/html,%3Chtml%3E%3Cbody%3E%3Ch1%3EHello,%20world!%3C/h1%3E%3C/body%3E%3C/html%3E

2 Creating a data URI with HTML content

In this example,

  1. We create a `String` variable `htmlContent` containing a simple HTML document.
  2. We use the `Uri.dataFromString` constructor to create a data URI with the HTML content and MIME type 'text/html'.
  3. We print the data URI to standard output.

Dart Program

void main() {
  String htmlContent = '<html><body><h1>Hello, world!</h1></body></html>';
  Uri htmlDataUri = Uri.dataFromString(htmlContent, mimeType: 'text/html');
  print(htmlDataUri);
}

Output

data:text/html,%3Chtml%3E%3Cbody%3E%3Ch1%3EHello,%20world!%3C/h1%3E%3C/body%3E%3C/html%3E

Summary

In this Dart tutorial, we learned about Uri.dataFromString constructor of Uri: the syntax and few working examples with output and detailed explanation for each example.