textSpan static method

List<InlineSpan> textSpan({
  1. required InlineSpan textSpan,
  2. TextStyle? defaultStyle,
  3. Color? linkColor,
})

Implementation

static List<InlineSpan> textSpan({
  required InlineSpan textSpan,
  TextStyle? defaultStyle,
  Color? linkColor,
}) {
  final List<InlineSpan> formattedText = [];

  textSpan.visitChildren((child) {
    final String? spanText = (child as TextSpan).text;
    final TextStyle? spanStyle = (child.style ?? defaultStyle);
    final TextStyle? linkStyle = spanStyle?.copyWith(
      color: linkColor,
      decoration: TextDecoration.underline,
    );

    if (spanText?.isNotEmpty ?? false) {
      final List<LinkifyElement> elements = linkify(spanText!);

      for (final element in elements) {
        if (element is TextElement) {
          formattedText.add(TextSpan(text: element.text, style: spanStyle));
        } else {
          late final Uri? url;
          late final String text;

          if (element is UrlElement) {
            text = element.url;
            url = Uri.tryParse(element.url);
          } else if (element is EmailElement) {
            text = element.emailAddress;
            url = Uri.tryParse(element.url);
          }

          formattedText.add(
            TextSpan(
              text: text,
              style: linkStyle,
              recognizer:
                  TapGestureRecognizer()
                    ..onTap = () async {
                      bool hasLaunched = false;

                      if (url != null) {
                        hasLaunched = await launchUrl(
                          url,
                          mode: LaunchMode.externalApplication,
                        );
                      }

                      if (!hasLaunched) {
                        throw 'Não abriu a url';
                        //TODO: toast
                      }
                    },
            ),
          );
        }
      }
    }
    return true;
  });

  return formattedText;
}