evaluateAsync method

Future evaluateAsync({
  1. Map context = const {},
  2. List<MemberAccessor> memberAccessors = const [],
})

Evaluates the template into a dynamic result asynchronously. This only supports a single template expression and will throw an exception if there is more than one.

Implementation

Future<dynamic> evaluateAsync({
  Map<dynamic, dynamic> context = const {},
  List<MemberAccessor<dynamic>> memberAccessors = const [],
}) async {
  final ctx = <String, Object>{};
  for (var entry in context.entries) {
    if (entry.key != null && entry.value != null) {
      ctx[entry.key.toString()] = entry.value;
    }
  }

  final prepared = _prepare();
  dynamic result = prepared.data;

  if (prepared.entries.isNotEmpty) {
    if (prepared.entries.length > 1) {
      throw Exception(
        'The [evaluate] function only supports a single template expression but [${prepared.entries.length}] were found.',
      );
    } else {
      final evaluator = ExpressionEvaluator.async(
        memberAccessors: memberAccessors,
      );

      result = await evaluator
          .eval(
            Expression.parse(prepared.entries.first.content),
            ctx,
          )
          .first;
    }
  }

  return result;
}