textWithLinks function

Widget textWithLinks(
  1. String text, {
  2. TextStyle? textStyle,
  3. RegExp? exp,
  4. TextStyle? linkTextStyle,
  5. required void onTapLink(
    1. String link
    ),
})

Parse text for links and return as RichText if at least one, else pure text

Implementation

Widget textWithLinks(
  String text, {
  TextStyle? textStyle,
  RegExp? exp,
  TextStyle? linkTextStyle,
  required void Function(String link) onTapLink,
}) {
  exp ??= RegExp(
      r'(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?');

  if (exp.hasMatch(text)) {
    List<TextSpan> spans = [];
    int start = 0;
    final List<RegExpMatch> matches = exp.allMatches(text).toList();

    for (RegExpMatch match in matches) {
      if (match.start > 0) {
        spans.add(TextSpan(
          text: text.substring(start, match.start),
          style: textStyle,
        ));
      }

      spans.add(
        TextSpan(
          text: text.substring(match.start, match.end),
          style: linkTextStyle,
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              onTapLink(text.substring(match.start, match.end));
            },
        ),
      );

      start = match.end;
    }

    if (start < text.length) {
      spans.add(TextSpan(
        text: text.substring(start),
        style: textStyle,
      ));
    }

    return Text.rich(
      TextSpan(children: spans),
      textAlign: TextAlign.left,
    );
  }

  return Text(
    text,
    style: textStyle,
  );
}