toEL function

String toEL(
  1. String? data, {
  2. bool direct = true,
})

Converts the given value to a valid Dart statement.

  • data - the value to convert. It can be null.
  • direct - whether it is OK to return an expression, if any, directly without enclosing with """/ If true and data contains nothing but a single expression, the expression is output directly

Implementation

String toEL(String? data, {bool direct = true}) {
  if (data == null)
    return direct ? "null": '""';

  final sb = StringBuffer();
  for (int i = 0, len = data.length; i < len; ++i) {
    final cc = data.codeUnitAt(i);
    if (cc == $lbracket && i + 1 < len && data.codeUnitAt(i + 1) == $equal) { //found
      final j = _skipToELEnd(data, i + 2),
          val = data.substring(i + 2, j).trim();
      if (direct && i == 0 && j + 1 == len) //single EL
        return val;
      if (!val.isEmpty)
        sb..write("\${Rsp.nns(")..write(val)..write(")}");

      i = j;
      continue;
    }

    sb.writeCharCode(cc);
    if (cc == $backslash)
      sb.writeCharCode(data.codeUnitAt(++i));
  }
  final val = sb.toString();
  return val.indexOf('"') >= 0 ?
    val.indexOf("'") >= 0 ? '"""$val"""': "'$val'": '"$val"';
}