convert 方法

Uint8List convert(
  1. String string,
  2. [int start = 0,
  3. int? end]
)
override

string 转换为其 UTF-8 代码单元(无符号 8 位整数列表)。

如果提供了 startend,则仅转换 string.substring(start, end) 的子字符串。

输入字符串中的任何不成对的代理字符(U+D800-U+DFFF)将被编码为 Unicode 替换字符 U+FFFD(�)。

实现

Uint8List convert(String string, [int start = 0, int? end]) {
  var stringLength = string.length;
  end = RangeError.checkValidRange(start, end, stringLength);
  var length = end - start;
  if (length == 0) return Uint8List(0);
  // Create a new encoder with a length that is guaranteed to be big enough.
  // A single code unit uses at most 3 bytes, a surrogate pair at most 4.
  var encoder = _Utf8Encoder.withBufferSize(length * 3);
  var endPosition = encoder._fillBuffer(string, start, end);
  assert(endPosition >= end - 1);
  if (endPosition != end) {
    // Encoding skipped the last code unit.
    // That can only happen if the last code unit is a leadsurrogate.
    // Force encoding of the lead surrogate by itself.
    var lastCodeUnit = string.codeUnitAt(end - 1);
    assert(_isLeadSurrogate(lastCodeUnit));
    // Write a replacement character to represent the unpaired surrogate.
    encoder._writeReplacementCharacter();
  }
  return encoder._buffer.sublist(0, encoder._bufferIndex);
}