loadString method Null safety

Future<String> loadString(
  1. String key,
  2. {bool cache = true}
)

Retrieve a string from the asset bundle.

Throws an exception if the asset is not found.

If the cache argument is set to false, then the data will not be cached, and reading the data may bypass the cache. This is useful if the caller is going to be doing its own caching. (It might not be cached if it's set to true either, depending on the asset bundle implementation.)

The function expects the stored string to be UTF-8-encoded as Utf8Codec will be used for decoding the string. If the string is larger than 50 KB, the decoding process is delegated to an isolate to avoid jank on the main thread.

Implementation

Future<String> loadString(String key, { bool cache = true }) async {
  final ByteData data = await load(key);
  if (data == null)
    throw FlutterError('Unable to load asset: $key');
  // 50 KB of data should take 2-3 ms to parse on a Moto G4, and about 400 μs
  // on a Pixel 4.
  if (data.lengthInBytes < 50 * 1024) {
    return utf8.decode(data.buffer.asUint8List());
  }
  // For strings larger than 50 KB, run the computation in an isolate to
  // avoid causing main thread jank.
  return compute(_utf8decode, data, debugLabel: 'UTF8 decode for "$key"');
}