gyorgio88
gyorgio88

Reputation: 517

How to get bytes of a String in Dart?

How can I read the bytes of a String in dart? in Java it is possible through the String method getBytes().

See example

Upvotes: 46

Views: 68482

Answers (4)

Chuck Batson
Chuck Batson

Reputation: 2764

If you're looking for bytes in the form of Uint8List, use

import 'dart:convert';
import 'dart:typed_data';

var string = 'foo';
Uint8List.fromList(utf8.encode(string));

Upvotes: 7

Miguel Ruivo
Miguel Ruivo

Reputation: 17746

import 'dart:convert';

String foo = 'Hello world';
List<int> bytes = utf8.encode(foo);
print(bytes);

Output: [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

Also, if you want to convert back:

String bar = utf8.decode(bytes);

Upvotes: 94

A.Mushate
A.Mushate

Reputation: 455

For images they might be base64 encoded, use

Image.memory(base64.decode('base64EncodedImageString')),

import function from

import 'dart:convert';

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657128

There is a codeUnits getter that returns UTF-16

String foo = 'Hello world';
List<int> bytes = foo.codeUnits;
print(bytes);

[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

and runes that returns Unicode code-points

String foo = 'Hello world';
// Runes runes = foo.runes;
// or
Iterable<int> bytes = foo.runes;
print(bytes.toList());

[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

Upvotes: 17

Related Questions