parseTextString function
Expands Adaptive Cards {{DATE(...)}} and {{TIME(...)}} templates in display text.
Implementation
String parseTextString(String text, {String? locale}) {
return text.replaceAllMapped(RegExp('{{.*}}'), (match) {
final String? res = match.group(0);
String? input = res?.substring(2, res.length - 2);
input = input?.replaceAll(' ', '');
final String? type = input?.substring(0, 4);
if (type == 'DATE') {
final String? dateFunction = input?.substring(5, input.length - 1);
final List<String> items = dateFunction?.split(',') ?? [];
if (items.length == 1) {
items.add('COMPACT');
}
//if(items.length != 2) throw StateError('$dateFunction is not valid');
// Wrong format
if (items.length != 2) return res ?? '';
final DateTime? dateTime = DateTime.tryParse(items[0]);
DateFormat dateFormat;
if (dateTime == null) return res ?? '';
if (items[1] == 'COMPACT') {
dateFormat = DateFormat.yMd(locale);
return dateFormat.format(dateTime);
} else if (items[1] == 'SHORT') {
dateFormat = DateFormat('E, MMM d{n}, y', locale);
return dateFormat
.format(dateTime)
.replaceFirst('{n}', getDayOfMonthSuffix(dateTime.day));
} else if (items[1] == 'LONG') {
dateFormat = DateFormat('EEEE, MMMM d{n}, y', locale);
return dateFormat
.format(dateTime)
.replaceFirst('{n}', getDayOfMonthSuffix(dateTime.day));
} else {
// Wrong format
return res ?? '';
}
} else if (type == 'TIME') {
final String? time = input?.substring(5, input.length - 1);
final DateTime? dateTime = DateTime.tryParse(time ?? '');
if (dateTime == null) return res ?? '';
final DateFormat dateFormat = DateFormat('jm', locale);
return dateFormat.format(dateTime);
} else {
// Wrong format
return res ?? '';
//throw StateError('Function $type not found');
}
});
}