getTextValue function

String getTextValue({
  1. required Map<String, dynamic> props,
  2. List<NestedContext>? contexts,
  3. Map<String, dynamic>? formData,
  4. String propName = 'text',
})

Implementation

String getTextValue({
  required Map<String, dynamic> props,
  List<NestedContext>? contexts,
  Map<String, dynamic>? formData,
  String propName = 'text',
}) {
  var text = props[propName] as String? ?? '';
  final prefix = (props['prefix'] as String?) != null
      ? getString(props['prefix'] as String)
      : null;
  final suffix = (props['suffix'] as String?) != null
      ? getString(props['suffix'] as String)
      : null;
  final useNumericFormatter = props['useNumericFormatter'] as bool? ?? false;

  final placeholderKey = extractFirstPlaceholderKey(
    props[propName] as String? ?? '',
  );
  if (placeholderKey != null && contexts != null && formData != null) {
    final updatedContexts = List<NestedContext>.from(contexts)
      ..add(NestedContext(placeholderKey));
    final value = getNestedFormValue(
      formData,
      FormSchemaTraversal.getFormFieldKey(updatedContexts),
    );

    text = value.toString();

    if (value is num && useNumericFormatter) {
      text = formatNumber(value);
    } else if (value is String) {
      // Check if the string is a valid ISO8601 date
      final parsedDate = DateTime.tryParse(value);
      if (parsedDate != null) {
        // It's a valid ISO8601 date, format it
        final dateFormat = props['dateFormat'] as String? ?? 'dd/MM/yyyy';
        text = parsedDate.formatLocalized(pattern: dateFormat);
      }
    }

    text = getString(text);
  } else {
    text = getString(text);
  }

  final buffer = StringBuffer();
  if (prefix != null) {
    buffer
      ..write(prefix)
      ..write(' ');
  }
  buffer.write(text);
  if (suffix != null) {
    buffer
      ..write(' ')
      ..write(suffix);
  }

  return buffer.toString();
}