getContentAsString method

String getContentAsString()

Extension methods for Asset objects.

Provides additional functionality for Asset objects, such as retrieving the content as a string.

Example

final asset = Asset.fromFile('index.html');
final content = asset.getContentAsString();
print(content);

Implementation

String getContentAsString() {
  try {
    final file = File(getFilePath());
    if (file.existsSync()) {
      final content = file.readAsStringSync();
      return content;
    }

    return utf8.decode(getContentBytes());
  } catch (e) {
    try {
      return utf8.decode(getContentBytes());
    } catch (e) {
      try {
        return String.fromCharCodes(getContentBytes());
      } catch (e) {
        throw IllegalStateException('Failed to parse asset ${getFileName()}: $e');
      }
    }
  }
}