import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:mnemo_cards/utils/string_helper.dart'; class MnemoText extends StatelessWidget { final String? mnemo; final TextStyle? textStyle; final TextAlign? textAlign; final Color? color; final AutoSizeGroup? group; final int? maxLines; final bool? softWrap; const MnemoText( this.mnemo, { this.textStyle, this.textAlign, this.color, this.group, this.maxLines, this.softWrap, super.key, }); @override Widget build(BuildContext context) { if (mnemo == null) return SizedBox.shrink(); final matches = RegExp(r'\{(.*?)\}').allMatches(mnemo!); Color? color = this.color; color ??= Colors.red; List spans = []; RegExpMatch? lastMatch; for (final match in matches) { var mnemoText = matches.isEmpty ? '' : mnemo! .substring(match.start, match.end) .replaceAll(RegExp(r'[\}\{]'), ''); if (mnemoText.startsWith('#')) { // #123456mnemo color = mnemoText.substring(0, 7).asColor; mnemoText = mnemoText.substring(7); } spans.addAll([ if (lastMatch == null) TextSpan(text: mnemo!.substring(0, match.start), style: textStyle) else TextSpan( text: mnemo!.substring(lastMatch.end, match.start), style: textStyle), TextSpan( text: mnemoText, style: textStyle?.copyWith(color: color) ?? TextStyle(color: color), ), ]); lastMatch = match; } if (lastMatch == null) { spans.add( TextSpan(text: mnemo, style: textStyle), ); } else { spans.add(TextSpan( text: mnemo!.substring(lastMatch.end), style: textStyle, )); } return AutoSizeText.rich( maxLines: maxLines, softWrap: softWrap, TextSpan( children: spans, ), textAlign: textAlign ?? TextAlign.center, group: group, ); } }