toCharArray method
Converts this string to a UTF8 encoded byte array (a Int8List).
Uses utf8 for the encoding. If memoryWidth
is specified, the resulting
byte array will have exactly memoryWidth
bytes. If this string fits
exactly into this array, that will be the result. If it is shorter, the
remaining bytes will be filled with 0. If it is bigger, an ArgumentError
gets thrown.
By default, this whole string gets converted, even if it contains zeros in
the middle of it. If zeroTerminated
is set to true, this method stops
encoding this string as soon as the first 0 is reached and the rest of the
string gets dropped.
Implementation
Int8List toCharArray({int? memoryWidth, bool zeroTerminated = false}) {
final List<int> chars;
if (zeroTerminated) {
chars = utf8.encode(this).takeWhile((value) => value != 0).toList();
} else {
chars = utf8.encode(this);
}
if (memoryWidth != null) {
if (chars.length > memoryWidth) {
throw ArgumentError.value(
memoryWidth,
'memoryWidth',
'must be at least as long as the encoded string '
'(${chars.length} bytes)',
);
}
return Int8List(memoryWidth)
..setRange(0, chars.length, chars)
..fillRange(chars.length, memoryWidth, 0);
} else {
return Int8List.fromList(chars);
}
}