How to get bytes of a String in Dart?

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);

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]