Dart Uri.dataFromBytes()
Syntax & Examples


Uri.dataFromBytes constructor

The `Uri.dataFromBytes` constructor in Dart creates a `data:` URI containing an encoding of bytes.


Syntax of Uri.dataFromBytes

The syntax of Uri.Uri.dataFromBytes constructor is:

Uri.dataFromBytes(List<int> bytes, { dynamic mimeType: "application/octet-stream" Map<String, String> parameters, dynamic percentEncoded: false })

This Uri.dataFromBytes constructor of Uri creates a data: URI containing an encoding of bytes.

Parameters

ParameterOptional/RequiredDescription
bytesrequiredThe list of integers representing the bytes to include in the data URI.
mimeTypeoptionalThe MIME type of the data. Defaults to 'application/octet-stream'.
parametersoptionalAdditional parameters for the data URI as key-value pairs.
percentEncodedoptionalA boolean flag indicating whether the bytes should be percent-encoded. Defaults to false.


✐ Examples

1 Creating a basic data URI from bytes

In this example,

  1. We create a list of integers representing ASCII values for 'Hello'.
  2. We use the `Uri.dataFromBytes` constructor to create a data URI from these bytes.
  3. We print the URI as a string.

Dart Program

void main() {
  List<int> bytes = [72, 101, 108, 108, 111];
  Uri uri = Uri.dataFromBytes(bytes);
  print(uri.toString());
}

Output

data:application/octet-stream;base64,SGVsbG8=

2 Creating a data URI with a custom MIME type

In this example,

  1. We create a list of integers representing ASCII values for 'Hello'.
  2. We use the `Uri.dataFromBytes` constructor with a custom MIME type 'text/plain'.
  3. We print the URI as a string.

Dart Program

void main() {
  List<int> bytes = [72, 101, 108, 108, 111];
  Uri uri = Uri.dataFromBytes(bytes, mimeType: 'text/plain');
  print(uri.toString());
}

Output

data:text/plain;base64,SGVsbG8=

3 Creating a data URI with additional parameters

In this example,

  1. We create a list of integers representing ASCII values for 'Hello'.
  2. We use the `Uri.dataFromBytes` constructor with additional parameters, setting the charset to 'UTF-8'.
  3. We print the URI as a string.

Dart Program

void main() {
  List<int> bytes = [72, 101, 108, 108, 111];
  Uri uri = Uri.dataFromBytes(bytes, parameters: {'charset': 'UTF-8'});
  print(uri.toString());
}

Output

data:application/octet-stream;charset=UTF-8;base64,SGVsbG8=

Summary

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